diff --git a/PERF.md b/PERF.md index 02566f46d0..804778dcc6 100644 --- a/PERF.md +++ b/PERF.md @@ -402,6 +402,33 @@ always coordinate through it, so no build leaves it out. On linux/amd64 it adds base), and the cap moves by the same amount, from 75,811,848 to 79,191,048, so the 56,063 bytes of headroom the base had are kept. +## Direct road binary size + +Every build links the direct road: the pion WebRTC stack (ICE, DTLS, SCTP and +the data channel) that lets two of a person's computers talk to each other +without the relay. It is built with CGO off, so it adds no C toolchain and no +shared library, and it is linked by `cmd/codeaf` alone: `internal/syncsetup` +states what it needs through a seam the program fills, so no other package pays +for it. The cap moves by 9,484,272 bytes, from 79,191,048 to 88,675,320: the +measured difference between two darwin/amd64 builds of `cmd/codeaf` with Go +1.26.5, `-trimpath -ldflags="-s -w"` and the same embedded artifacts, one of +`dev` at ca8e437b7 and one of the merged remote-control branch, so the headroom +the base had is kept. About 2.1 MB of that is pion's own code by symbol size and +about 0.2 MB is `internal/livedoor` and `internal/directroad`; the rest is what +roughly 6,700 more functions cost the whole binary in type data, line tables and +strings, because the program already links reflective method lookup and the +linker cannot drop exported methods. The design's estimate of 4.5 MB counted the +dependency alone and was wrong by half. The cheaper road, if this number ever +needs to fall, is to build the direct road from pion's ICE, DTLS, SCTP and data +channel packages without `pion/webrtc`, which drops the media packages (RTP, +RTCP, SRTP, SDP, interceptors and the TURN client) that nothing here uses; the +direct road is offered through a capability in the hello, so a later build can +change how it is made without breaking an older one. + +When remote control is off, or `CODEAF_REMOTE_ROAD=relay` is set, nothing from +this stack runs: no peer connection is built and no STUN request is made. The +linked code costs bytes, never time. + ## Usage writer identity startup `TestUsageMillionRowLedgerFlush` constructs 1,000,000 unique historical call @@ -894,3 +921,59 @@ It caps retained paths and visited entries at `2*N+100`, and Go allocations at bytes; afterward it allocated 2,505,888 bytes. The 5,000+5,000 proof allocated 21,807,368 bytes. Bounds tests require refusal for paths, entries, reply size and content bytes. Final metadata revalidation remains mandatory. + +## The last-seen copy of a chat on another computer + +A live view of a chat that another of the person's computers runs keeps, on the +viewer's own disk, the last thing it drew (`internal/viewcache`, under +`CODEAF_HOME/v3/viewed//.json`, directories 0700, files 0600). +The relay stores nothing of it. The bounds are constants in that package and +this section changes in the same commit as they do: the newest 200 entries of a +chat (`MaxEntries`), at most 1 MiB of file per chat (`MaxBytes`, oldest entries +out first), 40 chats across every computer (`MaxChats`, oldest out), and at most +one write of a chat every 2 seconds from `Save` (`WriteEvery`; `SaveNow` is for +the beat that ends a view). Pruning reads file times, never file contents, so +forty copies cost a directory read and not forty megabytes. +`TestASnapshotIsBoundedAndPlainTextOnlyOnTheViewersDisk`, +`TestOnlyTheNewestFortyChatsAreKept` and +`TestACopyIsNotRewrittenMoreThanOnceInTwoSeconds` pin them. + +## Live door limits + +Remote control live sessions (`internal/livedoor/limits.go` owns these +constants and duration variables) are bounded by the table below. A change to +any of them changes this section in the same commit. + +| Constant | Value | What it bounds | +| --- | --- | --- | +| `livedoor.MaxLine` | 256 KiB | A single EventWire JSON line so one oversized event cannot pin memory at the host or viewer above the tunnel. | +| `livedoor.ChunkBytes` | 16 KiB | A single multiplexer frame payload so concurrent channels interleave fairly on one tunnel and fit well inside a Noise plaintext record. | +| `livedoor.ChannelWindow` | 256 KiB | Unacknowledged data bytes in flight on one multiplexed channel so one unread chat cannot stall other chats on the same link. | +| `livedoor.LinkWindow` | 1 MiB | Total unacknowledged data bytes in flight across the entire tunnel so a blind relay cannot buffer unbounded data for a slow viewer. | +| `livedoor.QueueMax` | 4 MiB | The per-channel outbound queue at the host before a lagging viewer is reset back to Resume. | +| `livedoor.RingBytes` | 1 MiB | The holder's replay ring so a reset-then-Resume cycle either catches up within fixed memory or signals an explicit gap. | +| `livedoor.Rate` | 1 MiB/s | Outbound data payload bytes per second in each direction so a chatty session stays below the relay abuse breaker. | +| `livedoor.RateBurst` | 1 MiB | The token-bucket burst allowance paired with `Rate` so an initial welcome tail or burst of deltas up to one megabyte leaves without delay. | +| `livedoor.DailyBudget` | 256 MiB | The per-day carrier byte allowance before live sessions degrade to watch-only until midnight. | +| `livedoor.MaxLive` | 14 | Concurrent live-intent relay streams on the host so two of the sixteen relay stream slots stay reserved for Move. | +| `livedoor.MaxTunnelsPerDevice` | 2 | Simultaneous live tunnels from the same viewer device so a reconnecting link may briefly overlap its dying predecessor. | +| `livedoor.MaxChannelsPerLink` | 32 | Concurrent open channels on a single multiplexed tunnel so one viewer cannot allocate unbounded channel state. | +| `livedoor.FirstLineMax` | 64 KiB | The initial handshake line read on a local holder socket before the full session line limit applies. | +| `livedoor.PingEvery` | 3 s | The interval between multiplexer pings while a viewed chat is active. | +| `livedoor.DeadAfter` | 6 s | The silence window after a ping before an unanswered link is declared dead. | +| `livedoor.ActiveWindow` | 30 s | How long after a user action a viewed link remains in active ping mode before going quiet to keep the relay hibernated. | +| `livedoor.IdleDetach` | 10 min | How long an inactive viewer with no running turn stays attached before closing channels with reason `idle` so the relay costs nothing at rest. | +| `livedoor.WriteDeadline` | 2 s | How long the holder waits on a remote guest socket write before dropping that guest so a local surface never stalls. | +| `livedoor.MaxDirect` | 14 | Concurrent direct tunnels on the host; a direct tunnel holds no relay stream, so this is its own number, and `filesdoor.MaxDirect` is the same figure counted at the door. | +| `livedoor.DirectRate` | 64 MiB/s | Pacing (and burst) of a direct tunnel in each direction; the relay's 1 MiB/s exists for the relay's abuse breaker and bill, which a direct path has neither of. | +| `livedoor.SignalMax` | 8 KiB | One signalling payload (an offer, answer or candidate), half of `ChunkBytes`, so a signal fits one frame and an oversize one ends the link. | +| `livedoor.SignalRate` | 64 a minute | Signalling frames a link may carry in a minute before it is closed as `too-many`, so a viewer cannot turn the relay link into a flood. | +| `livedoor.PendingOffers` | 4 | Direct attempts a host has in flight at once over every viewer, so offers cannot make it build peer connections without limit. | +| `livedoor.OfferTTL` | 12 s | How long a host keeps an attempt that has produced no stream before it lets the attempt go. | +| `livedoor.DirectPingEvery` | 1 s | The multiplexer ping interval on a direct tunnel; it costs the relay nothing and is how a dead direct path is noticed. | +| `livedoor.DirectDeadAfter` | 2 s | The silence window after a ping before a direct tunnel is declared dead, so a dead path is noticed in about three seconds. | +| `livedoor.DirectSettle` | 500 ms | How long after a view's first channel opens that the viewer makes its first direct attempt, so the first paint never waits on the path finding. | +| `livedoor.DirectConnectWithin` | 8 s | The time one direct attempt gets to finish ICE, DTLS, SCTP, the handshake and the hello before it is abandoned. | +| `livedoor.DirectBackoff` | 5 s, 15 s, 1 min, 5 min, 10 min (repeating) | The wait after each failed direct attempt, ending in a ten-minute wait that repeats, so a blocked network costs a handful of packets an hour. | +| `livedoor.DirectStableAfter` | 60 s | How long a direct tunnel must stay up before the backoff ladder starts over. | + diff --git a/SIZE-BUDGET b/SIZE-BUDGET index 4a76e6f9f4..03d6ffc43f 100644 --- a/SIZE-BUDGET +++ b/SIZE-BUDGET @@ -1 +1 @@ -79191048 +88675320 diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index f10603f6cd..dfcb53a811 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -2936,6 +2936,334 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` +## github.com/pion/datachannel + +- Version: v1.6.4 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2026 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/dtls/v3 + +- Version: v3.1.16 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2026 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/ice/v4 + +- Version: v4.4.9 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2026 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/interceptor + +- Version: v0.1.51 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2026 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/logging + +- Version: v0.2.4 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2023 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/mdns/v2 + +- Version: v2.2.2 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2018 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +## github.com/pion/randutil + +- Version: v0.1.0 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2020 Pion + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` + +## github.com/pion/rtcp + +- Version: v1.2.20 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2026 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/rtp + +- Version: v1.10.6 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/sctp + +- Version: v1.12.1 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2026 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/sdp/v3 + +- Version: v3.0.20 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2026 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/srtp/v3 + +- Version: v3.1.3 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2026 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/stun/v4 + +- Version: v4.0.1 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2026 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/transport/v5 + +- Version: v5.1.5 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2026 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/turn/v5 + +- Version: v5.1.3 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2026 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + +## github.com/pion/webrtc/v4 + +- Version: v4.2.29 +- Licence: MIT + +### LICENSE + +```text +MIT License + +Copyright (c) 2026 The Pion community + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +``` + ## github.com/remyoudompheng/bigfft - Version: v0.0.0-20230129092748-24d4a6f8daec @@ -3269,6 +3597,44 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` +## github.com/wlynxg/anet + +- Version: v0.0.5 +- Licence: BSD-3-Clause + +### LICENSE + +```text +BSD 3-Clause License + +Copyright (c) 2023, wlynxg + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. 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. + +3. Neither the name of the copyright holder 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. +``` + ## github.com/x448/float16 - Version: v0.8.4 diff --git a/cmd/codeaf-release/main.go b/cmd/codeaf-release/main.go index d39e2c1447..a6f34850f2 100644 --- a/cmd/codeaf-release/main.go +++ b/cmd/codeaf-release/main.go @@ -11,7 +11,7 @@ // codeaf-release next --channel dev|staging --sha --date YYYYMMDD // codeaf-release kind // codeaf-release prune --channel dev|staging -// codeaf-release service [--url ] +// codeaf-release service [--url ] package main import ( @@ -95,8 +95,8 @@ func usage(w io.Writer) { Print stable, rc, dev, staging, or other. prune --channel dev|staging Read lines and print expired tags. - service [--url ] | relay-url --channel stable|rc|staging|dev - Check a live sync service's capabilities, or print a channel's hosted URL. + service [--url ] | relay-url --channel stable|rc|staging|dev + Check a live relay's capabilities, or print a channel's hosted URL. promotion-plan|promotion-decision|promotion-recheck|promotion-release|promotion-published|promotion-jobs|promotion-push-error|promotion-message Plan, check, and report the staging promotion. See docs/rules/promotion.md. `) diff --git a/cmd/codeaf-release/service.go b/cmd/codeaf-release/service.go index 098e60912f..5e44e67ceb 100644 --- a/cmd/codeaf-release/service.go +++ b/cmd/codeaf-release/service.go @@ -26,18 +26,18 @@ func runService(args []string, stdout io.Writer) error { case len(args) == 2 && args[0] == "--url": url = args[1] case len(args) != 0: - return usageErr("service takes only --url ") + return usageErr("service takes only --url ") } ctx, cancel := context.WithTimeout(context.Background(), serviceProbeWithin) defer cancel() missing, err := probeService(ctx, url) if err != nil { - return fmt.Errorf("could not check the sync service at %s: %w", url, err) + return fmt.Errorf("could not check the relay at %s: %w", url, err) } if len(missing) > 0 { - return fmt.Errorf("the sync service at %s must be updated before this build ships; it does not promise %s", url, describe(missing)) + return fmt.Errorf("the relay at %s must be updated before this build ships; it does not promise %s", url, describe(missing)) } - fmt.Fprintf(stdout, "the sync service at %s promises everything this build needs\n", url) + fmt.Fprintf(stdout, "the relay at %s promises everything this build needs\n", url) return nil } diff --git a/cmd/codeaf/app.go b/cmd/codeaf/app.go index 45ee90f09d..7404a733b0 100644 --- a/cmd/codeaf/app.go +++ b/cmd/codeaf/app.go @@ -363,6 +363,18 @@ type appConn struct { // Lent says this is a factory stage the factory owns, lent as a view // (app_lend.go): its model, posture and budget are not the app's to set. Lent bool + // Remote says this is a LIVE VIEW of a chat another computer holds + // (app_live_open.go): the conversation runs there, and its model, posture, + // budget and client tools are that computer's to set, never this one's. + Remote bool + // Gone is closed when the connection is released, for what watches it and + // must stop with it; nil where nothing does. + Gone <-chan struct{} + // Held says this desktop keeps the chat behind its holder door + // ([appDeskHost]), so another computer may be in it and the keyboard may be + // theirs. It is false with remote control off, which is the chat as it + // always was. + Held bool } type appOpener func(appOpenAsk) (*appConn, error) @@ -413,39 +425,52 @@ func appOpenInProcess(ask appOpenAsk) (*appConn, error) { // carry on by itself (appinterrupted.go). HoldInterruptedWork: ask.HoldInterruptedWork, } + return appOpenAssembled(hello, func(h remote.Hello) (*remote.Engine, error) { + // THE APP'S OWN OPENER FIRST, so a process half that failed for the + // want of a key before the window handed one over is opened again + // now; [assembleEngine] then finds it open. Without it a first + // message sent after the key arrived failed on the memo's old error. + if _, err := openAppEngineProcess(); err != nil { + return nil, err + } + eng, err := assembleEngine(h, workspace, transcript, workspace, ask.IntentSiblingNames) + if err == nil { + // In-process chats are the desktop's hot path. Remote surfaces keep + // one frame per event until someone measures them. + eng.DeltaWindow = remote.DefaultDeltaWindow + err = enableAppConversationModels(eng.Agent, ask.Models) + } + if err == nil && ask.AutomaticModels != nil { + if door, ok := eng.Agent.(interface{ SetAutomaticModels(bool) error }); ok { + err = door.SetAutomaticModels(*ask.AutomaticModels) + } else { + err = fmt.Errorf("model selection policy is unsupported") + } + } + return eng, err + }) +} + +// appOpenAssembled opens the conversation boot builds as the app's own, over +// one in-process attach, and returns the connection the app holds it by. +// +// WHEN REMOTE CONTROL IS ON the conversation is kept by a persistent session the +// desktop's holder door can hand to another computer's viewer ([appDeskHost]); +// when it is off, or the door could not start, it is the loopback it has always +// been. Either way the connection's release ends the chat, and what the app sees +// through it is the same. +func appOpenAssembled(hello remote.Hello, boot func(remote.Hello) (*remote.Engine, error)) (*appConn, error) { // The agent this boot built, kept so the app can tell when somebody else - // closes it (below). Boot runs once, before Loopback returns. + // closes it (below). Boot runs once, before the attach returns. var booted atomic.Pointer[closedAgent] - loop, err := remote.Loopback(hello, remote.Options{ - Boot: func(h remote.Hello) (*remote.Engine, error) { - // THE APP'S OWN OPENER FIRST, so a process half that failed for the - // want of a key before the window handed one over is opened again - // now; [assembleEngine] then finds it open. Without it a first - // message sent after the key arrived failed on the memo's old error. - if _, err := openAppEngineProcess(); err != nil { - return nil, err - } - eng, err := assembleEngine(h, workspace, transcript, workspace, ask.IntentSiblingNames) - if err == nil { - // In-process chats are the desktop's hot path. Remote surfaces keep - // one frame per event until someone measures them. - eng.DeltaWindow = remote.DefaultDeltaWindow - err = enableAppConversationModels(eng.Agent, ask.Models) + loop, held, err := deskHost.open(hello, func(h remote.Hello) (*remote.Engine, error) { + eng, err := boot(h) + if err == nil && eng != nil { + if c, ok := eng.Agent.(closedAgent); ok { + booted.Store(&c) } - if err == nil && ask.AutomaticModels != nil { - if door, ok := eng.Agent.(interface{ SetAutomaticModels(bool) error }); ok { - err = door.SetAutomaticModels(*ask.AutomaticModels) - } else { - err = fmt.Errorf("model selection policy is unsupported") - } - } - if err == nil { - if c, ok := eng.Agent.(closedAgent); ok { - booted.Store(&c) - } - } - return eng, err - }, + } + return eng, err }) if err != nil { return nil, err @@ -462,13 +487,22 @@ func appOpenInProcess(ask appOpenAsk) (*appConn, error) { release := func() { once.Do(func() { close(stop) + // OFF THE DOOR FIRST, so nobody joins a chat that is closing. + held.drop() + held.endViewers() recordFinalSaveFailure(loop.Close()) + held.close() }) } if c := booted.Load(); c != nil { watchAgentClosed(*c, stop, release) } - return appConnOf(loop.Client, release, true), nil + conn := appConnOf(loop.Client, release, true) + if held != nil { + // WHAT WATCHES THE KEYBOARD STOPS WITH THE CHAT ([appBackend.watchHeldDriver]). + conn.Held, conn.Gone = true, stop + } + return conn, nil } // appJoinExisting joins only a conversation an engine already holds. @@ -700,6 +734,14 @@ type appBackend struct { turns atomic.Uint64 assembled atomic.Bool + // liveMu guards liveHosts, the roads to the other computers this process + // holds live views on (app_live_open.go). It is a leaf lock: nothing else is + // taken or called while it is held. liveViews counts the live agents, so the + // hook every agents.* call goes through costs nothing when there are none. + liveMu sync.Mutex + liveHosts map[string]*appLiveHost + liveViews atomic.Int32 + // unreadSay is held from working an agent's unread and saved spend out // to saying them, so the last readings the window hears are the latest // (appunread.go). It is taken before mu and the app file's lock, never @@ -856,6 +898,13 @@ type appAgent struct { // viewOpen preserves the person's open view through idle sweeps. Retiring // it would let its next read immediately take back the released hold. viewOpen bool + // liveRemote is set once the agent has been opened as a live view of a chat + // another computer holds (app_live_open.go); nil for every other agent. + liveRemote *appLiveRemote + // heldKeyboard is who holds the keyboard of this chat when it is held here + // and another window than the desktop's own has it (app_held_keyboard.go); + // nil says the desktop's window holds it. Guarded by the backend's lock. + heldKeyboard *appwire.LiveDriver // crewHeld keeps an established crew hold due after its engine closes. crewHeld bool // What it has said to the person (appunread.go): repliedAt its last @@ -1342,7 +1391,7 @@ func (b *appBackend) findLocal(id string) (*appAgent, error) { held := false b.locked(func() { a = b.agents[id] - held = a != nil && a.transcript != "" + held = a != nil && (a.transcript != "" || a.liveRemote != nil) }) if held { // A cached transcript is not a lease on another window's working state. @@ -1444,7 +1493,7 @@ func (b *appBackend) ListAgents(workspace string) ([]appwire.Agent, error) { var beyond []beyondWalk b.locked(func() { for id, a := range b.agents { - if !seen[id] && !a.view.FactoryOwned && !factoryOwnedConversation(a.transcript) && (a.live != nil || a.opening) && matches(a.view.Workspace) { + if !seen[id] && !a.view.FactoryOwned && !a.liveOnly() && !factoryOwnedConversation(a.transcript) && (a.live != nil || a.opening) && matches(a.view.Workspace) { beyond = append(beyond, beyondWalk{view: a.view, transcript: a.transcript, said: a.saidLocked()}) } } @@ -1960,7 +2009,14 @@ func (b *appBackend) ensureLocked(a *appAgent) (appwire.Agent, bool, error) { } }) var moved bool - b.locked(func() { moved = a.windowMoved }) + var liveRemote *appLiveRemote + b.locked(func() { moved, liveRemote = a.windowMoved, a.liveRemote }) + // A LIVE VIEW IS OPENED OVER THE LIVE DOOR, NEVER BUILT HERE: the chat runs + // on another computer, so this process spends nothing on it, moves nothing + // and is not held by the day's cap (app_live_open.go). + if liveRemote != nil { + return b.ensureLive(a, liveRemote) + } if moved { return appwire.Agent{}, false, appwire.Errorf(appwire.CodeConflict, "%s", appWindowConflict) } @@ -2165,6 +2221,9 @@ func (b *appBackend) hold(a *appAgent, conn *appConn, workspace string) appwire. b.flushSync(a) b.locked(func() { view = a.view }) b.openingNotices(a, conn) + if conn.Held { + b.watchHeldDriver(a, conn) + } lane, stop := conn.Conv.WatchTaskUpdates() live.stopTasks = stop id := view.ID @@ -3933,6 +3992,13 @@ func (b *appBackend) EntriesWithFallback(id, before string, limit int) (appwire. if err != nil { return appwire.EntriesResult{}, err } + // A LIVE VIEW READS ITS HISTORY OVER THE LIVE DOOR, never from a folder + // here and never from a saved head (app_live_open.go). + var liveView bool + b.locked(func() { liveView = a.liveRemote != nil }) + if liveView { + return b.liveEntries(a, before, limit) + } if a.hosted != nil { return b.hostedEntries(a, before, limit) } @@ -4403,8 +4469,8 @@ func (b *appBackend) SetModel(id, model string) (appwire.Agent, error) { live = a.live live.lastUse = b.now() }) - if live.conn.Lent { - return appwire.Agent{}, errLentStage("model") + if live.conn.Lent || live.conn.Remote { + return appwire.Agent{}, appFenceError(live.conn, "model") } if checked, ok := live.conn.Conv.(interface{ SetModelChecked(string) error }); ok { if err := checked.SetModelChecked(model); err != nil { @@ -4953,6 +5019,9 @@ func (b *appBackend) Close() error { } b.clientTools.disconnect() appClientToolsBackend.CompareAndSwap(b, nil) + // The links to other computers go first: a view being redialled would + // otherwise hold the relay's tunnel while the app leaves. + b.closeLive() already := false var waitClosed chan struct{} var crews *appCrewRun @@ -5109,6 +5178,9 @@ func (b *appBackend) Close() error { } wg.Wait() lap("conversations") + // THE HOLDER DOOR GOES DOWN LAST OF THE CHATS' BUSINESS: every chat has + // been let go, so nothing is left for another computer to be handed. + deskHost.closeListener() // An unfinished crew open owns its gate but has no held conversation to // release. Optional file cleanup must not join that open; retain its files. var settled []*appAgent @@ -5234,6 +5306,17 @@ func (b *appBackend) sweepAgent(a *appAgent, now time.Time) { live = a.live keep = live == nil || a.viewOpen || live.running || a.readers > 0 || now.Sub(live.lastUse) < appAgentIdle }) + // A CHAT ANOTHER COMPUTER IS WATCHING THROUGH THIS DESKTOP IS KEPT, whatever + // the clock says: the viewer is somebody looking at it, the same as a view + // open here (app_live.go). The clock starts again when the viewer leaves. + if !keep && b.deskViewed(a) { + b.locked(func() { + if a.live == live { + live.lastUse = b.now() + } + }) + return + } // A member of an open crew stays held while it has work in flight or a // reason the crew would open it again at once; one with nothing to do goes // like any other, and the crew opens it when traffic comes (applazy.go). diff --git a/cmd/codeaf/app_chat_preview.go b/cmd/codeaf/app_chat_preview.go index af6231cce8..726acffbb7 100644 --- a/cmd/codeaf/app_chat_preview.go +++ b/cmd/codeaf/app_chat_preview.go @@ -11,6 +11,7 @@ import ( "github.com/Agent-Field/codeaf/internal/cell" "github.com/Agent-Field/codeaf/internal/cellsync" "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/config" "github.com/Agent-Field/codeaf/internal/filesdoor" "github.com/Agent-Field/codeaf/internal/guard" "github.com/Agent-Field/codeaf/internal/session" @@ -28,6 +29,13 @@ const ( chatPreviewWithin = 12 * time.Second ) +// appCanLive says a chat may be opened live: another computer is running it, is +// online and is named, and remote control is on here. With it off no row says +// anything about live at all. +func appCanLive(row appwire.ChatRow, fact chatlist.Row, online bool) bool { + return !row.Here && row.Status == string(chatlist.Running) && online && fact.DeviceID != "" && config.RemoteControlOn() +} + // describeChatRows keeps directory projections intact while filling titles from // online peers. The inventory lock serializes it with moves and other reads. func (c *appChats) describeChatRows(ctx context.Context, s *syncsetup.Sync, rows []appwire.ChatRow, facts map[string]chatlist.Row) { @@ -52,6 +60,9 @@ func (c *appChats) describeChatRows(ctx context.Context, s *syncsetup.Sync, rows fact := facts[row.Cell] online := !fact.HolderRemoved && (row.Online == nil || *row.Online) row.CanPreview = !row.Here && fact.Head != "" && (storage || live && online) + // A CHAT ANOTHER COMPUTER IS RUNNING CAN BE OPENED LIVE while remote + // control is on (app_live_open.go); with it off the row says nothing. + row.CanLive = appCanLive(*row, fact, online) if row.Here { continue } @@ -134,7 +145,7 @@ func (b *appBackend) PreviewChat(id string) (appwire.ChatPreview, error) { return appwire.ChatPreview{}, appEntriesBusy(err) } if errors.Is(err, cellsync.ErrTranscriptTooLarge) { - return appwire.ChatPreview{}, appwire.Errorf(appwire.CodeUnreachable, "This saved conversation is too large to preview. Continue here to read its full history.") + return appwire.ChatPreview{}, appwire.Errorf(appwire.CodeUnreachable, "This saved conversation is too large to preview. Move here to read its full history.") } return appwire.ChatPreview{}, appwire.Errorf(appwire.CodeUnreachable, "Couldn't load the saved messages. Check that the other computer is running and try again.") } diff --git a/cmd/codeaf/app_chatread.go b/cmd/codeaf/app_chatread.go index 04a2597dc1..7022468dc8 100644 --- a/cmd/codeaf/app_chatread.go +++ b/cmd/codeaf/app_chatread.go @@ -79,7 +79,7 @@ func (b *appBackend) ReadChat(p appwire.ChatReadParams) (appwire.ChatReadResult, case errors.Is(err, cellsync.ErrBadCursor): return appwire.ChatReadResult{}, appwire.Errorf(appwire.CodeBadParams, "before is not a cursor this engine wrote") case errors.Is(err, directory.ErrUnreachable) || errors.Is(err, wireauth.ErrUnavailable) || errors.Is(err, context.DeadlineExceeded): - return appwire.ChatReadResult{}, appwire.Errorf(appwire.CodeUnreachable, "The sync service can't be reached, so this chat can't be read right now.") + return appwire.ChatReadResult{}, appwire.Errorf(appwire.CodeUnreachable, "The relay can't be reached, so this chat can't be read right now.") case err != nil: return appwire.ChatReadResult{}, appEngineError(err) } diff --git a/cmd/codeaf/app_chats.go b/cmd/codeaf/app_chats.go index 640fbf5089..cef0b3c5e0 100644 --- a/cmd/codeaf/app_chats.go +++ b/cmd/codeaf/app_chats.go @@ -270,7 +270,7 @@ func (b *appBackend) localChats(s *syncsetup.Sync) map[string]appLocalChat { } b.locked(func() { for id, a := range b.agents { - if a.transcript != "" { + if a.transcript != "" && !a.liveOnly() { local = append(local, entry{id, a.transcript}) } } @@ -697,6 +697,12 @@ func (b *appBackend) publishChatRows(rows []appwire.ChatRow, version uint64, emi b.locked(func() { a = b.agents[r.LocalAgent] }) if a != nil { b.located(a, chatLocation(r)) + // A WINDOW THAT WAS VIEWING A CHAT THIS COMPUTER HELD, AND SAW + // ANOTHER COMPUTER TAKE IT, VIEWS THE NEW HOLDER LIVE instead of + // a stale copy (Superseded -> live, app_live_open.go). + if b.liveSwapWanted(a, r) { + b.liveSwap(r) + } } } } diff --git a/cmd/codeaf/app_devices_permit_test.go b/cmd/codeaf/app_devices_permit_test.go new file mode 100644 index 0000000000..8ce3383704 --- /dev/null +++ b/cmd/codeaf/app_devices_permit_test.go @@ -0,0 +1,97 @@ +package main + +import ( + "context" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/cell/celltest" + "github.com/Agent-Field/codeaf/internal/devname" + "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/pair" +) + +// V15 (the host's own switches): devices.permit edits THIS computer's permit +// book and nothing else, only for the switches named, answers the row as it now +// stands with the host's sentence, and emits devices.changed. The roster shows +// the switches on every row but this computer's own, only while remote control +// is on; a computer the roster does not name is refused and nothing is written. +func TestAppDevicesPermitEditsTheHostsOwnBookOnly(t *testing.T) { + celltest.Available(t) + _, hits, _ := appDevicesRelay(t) + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + a, other := t.TempDir(), t.TempDir() + id, err := identity.Ensure(a) + if err != nil { + t.Fatal(err) + } + if _, err := identity.Adopt(other, id, false); err != nil { + t.Fatal(err) + } + sa, sb := appDeviceSync(t, a), appDeviceSync(t, other) + for dir, name := range map[string]string{a: "desk", other: "laptop"} { + if _, err := devname.Set(dir, name); err != nil { + t.Fatal(err) + } + if err := appDeviceSync(t, dir).Rename(context.Background(), name); err != nil { + t.Fatal(err) + } + } + _, rec, wire := appDeviceBackend(t, a) + if !slices.Contains(wire.hello, appwire.FeatureDevicesPermit) { + t.Fatalf("with remote control on hello must name devices.permit: %v", wire.hello) + } + view := appDeviceList(t, wire) + if len(view.Devices) != 2 || view.Devices[0].Permit != nil || view.Devices[1].Permit == nil { + t.Fatalf("the switches belong on the other computer's row and never on this one's: %+v", view.Devices) + } + before := *view.Devices[1].Permit + + book := pair.Permits() + bookFile := filepath.Join(a, "v3", "remote", "permits.json") + untouched, _ := os.ReadFile(bookFile) + if _, err := wire.call("devices.permit", map[string]any{"id": "nosuchdevice", "watch": true}); err == nil || err.Code != appwire.CodeNotFound { + t.Fatalf("an unknown computer must be not_found, got %v", err) + } + if _, err := wire.call("devices.permit", map[string]any{"id": sa.Device.ID(), "drive": true}); err == nil || err.Code != appwire.CodeBadParams { + t.Fatalf("this computer's own row has no switches, got %v", err) + } + if _, err := wire.call("devices.permit", map[string]any{"id": sb.Device.ID()}); err == nil || err.Code != appwire.CodeBadParams { + t.Fatalf("a call that names no switch changes nothing, got %v", err) + } + if after, _ := os.ReadFile(bookFile); string(after) != string(untouched) { + t.Fatalf("a refused change wrote the permit book:\n%s\nwas:\n%s", after, untouched) + } + + requests := hits.Load() + on := !before.Drive + got := machineCall[appwire.DevicePermitResult](t, wire, "devices.permit", map[string]any{"id": sb.Device.ID(), "drive": on}) + if got.Device == nil || got.Device.ID != sb.Device.ID() || got.Device.Permit == nil || got.Device.Permit.Drive != on || got.Device.Permit.Watch != before.Watch { + t.Fatalf("only the named switch changes, and the row comes back as it now stands: %+v (was %+v)", got.Device, before) + } + if !strings.Contains(got.Line, "laptop") { + t.Fatalf("the receipt names the computer: %q", got.Line) + } + if hits.Load() != requests { + t.Fatalf("a permit change is this computer's own book and sent the relay %d requests", hits.Load()-requests) + } + appDeviceEvent(t, rec, func(v appwire.Devices) bool { + return len(v.Devices) == 2 && v.Devices[1].Permit != nil && v.Devices[1].Permit.Drive == on + }) + if p, _ := book.For(id.ID(), sb.Device.ID()); p.Drive != on || p.By != "person" { + t.Fatalf("the host's own book says %+v", p) + } + // The other computer's own book is never touched. + if _, err := os.Stat(filepath.Join(other, "v3", "remote", "permits.json")); err == nil { + t.Fatal("a permit change reached another computer's book") + } + // A switch the call did not name stays where it was. + got = machineCall[appwire.DevicePermitResult](t, wire, "devices.permit", map[string]any{"id": sb.Device.ID(), "watch": false}) + if got.Device.Permit.Watch || got.Device.Permit.Drive != on { + t.Fatalf("naming watch must leave drive alone: %+v", got.Device.Permit) + } +} diff --git a/cmd/codeaf/app_handoff_qa_test.go b/cmd/codeaf/app_handoff_qa_test.go index 1047951199..84ae0e0c8a 100644 --- a/cmd/codeaf/app_handoff_qa_test.go +++ b/cmd/codeaf/app_handoff_qa_test.go @@ -17,7 +17,7 @@ import ( "github.com/Agent-Field/codeaf/internal/syncsetup" ) -// Observe the same row a second desktop uses to arm Continue here, with a real +// Observe the same row a second desktop uses to arm Move here, with a real // background process and its owed follow-up on the first desktop. func TestQAMoveWaitsForBackgroundJobAndItsReply(t *testing.T) { celltest.RequireEngine(t) @@ -80,7 +80,7 @@ func TestQAMoveWaitsForBackgroundJobAndItsReply(t *testing.T) { rows := machineCall[appwire.ChatsResult](t, b.w, "chats.list", struct{}{}).Chats for _, r := range rows { if r.Cell == row.Cell && !r.Working { - t.Fatalf("Continue here became ready while the background job was running; source processes: %+v", machineCall[appwire.ProcessesResult](t, a.w, "processes.list", map[string]any{"agent": created.ID}).Processes) + t.Fatalf("Move here became ready while the background job was running; source processes: %+v", machineCall[appwire.ProcessesResult](t, a.w, "processes.list", map[string]any{"agent": created.ID}).Processes) } } time.Sleep(30 * time.Millisecond) @@ -169,7 +169,7 @@ func TestQAReadOnlyChatFollowsRemoteSavesWithoutTaking(t *testing.T) { a = e2StartApp(t, dirA) old := workingChatRow(t, a, row.Cell, func(r appwire.ChatRow) bool { return !r.Here && r.Seen.Device != row.Seen.Device }) // Reading the remote saved history must not replace the journal/tools root - // that an eventual Continue here still needs to reconcile. + // that an eventual Move here still needs to reconcile. local := takeRootForAt(dirA, row.Cell) before, err := os.ReadFile(filepath.Join(local, ".cell", "transcript.jsonl")) if err != nil { diff --git a/cmd/codeaf/app_held_keyboard.go b/cmd/codeaf/app_held_keyboard.go new file mode 100644 index 0000000000..b301501eb1 --- /dev/null +++ b/cmd/codeaf/app_held_keyboard.go @@ -0,0 +1,145 @@ +package main + +// ── THE KEYBOARD OF A CHAT THIS DESKTOP HOLDS FOR OTHERS ──────────────────── +// +// With remote control on, another of the person's computers can open a chat the +// desktop is running and, if its permit allows, take the keyboard. The desktop's +// own window is then refused with the engine's sentence (it always was), but +// until now it had no way to SAY who had the keyboard or to take it back: +// the fact lived only in the engine's per-window driver answer. +// +// THE FACT IS THE ENGINE'S, NEVER THE DESKTOP'S. The desktop's own connection +// to its chat is a [remote.Client] like any other window's, so its driver answer +// is read exactly as a live view's is (app_live_open.go) and said on the agent's +// location as [appwire.Location.Keyboard]. It is present only while another +// window holds the keyboard of a chat held here, and absent for every other +// chat, which is why a desktop with remote control off says nothing new. + +import ( + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/remote" +) + +// heldKeyboardOf is the keyboard fact of a driver answer: nothing while the +// desktop's own window holds the keyboard (or nobody does yet), and the other +// window's name otherwise. +func heldKeyboardOf(d remote.Driver) *appwire.LiveDriver { + if d.Yours || d == (remote.Driver{}) { + return nil + } + return &appwire.LiveDriver{Machine: d.Machine, Here: d.Here} +} + +// layKeyboardLocked lays the agent's keyboard fact onto its location and says +// whether the view changed. A chat with no location of its own gets the plainest +// one, "held here", so the fact has somewhere to ride, and loses it again when +// the fact goes. A chat the list says is held elsewhere carries no fact: this +// desktop is not running it. The caller holds the backend's lock. +func (a *appAgent) layKeyboardLocked() bool { + kb, loc := a.heldKeyboard, a.view.Location + switch { + case kb != nil && loc == nil: + a.view.Location = &appwire.Location{Here: true, Keyboard: kb} + return true + case kb != nil && loc.Here: + if loc.Keyboard != nil && *loc.Keyboard == *kb { + return false + } + next := *loc + next.Keyboard = kb + a.view.Location = &next + return true + case loc != nil && loc.Keyboard != nil: + next := *loc + next.Keyboard = nil + if next == (appwire.Location{Here: true}) { + a.view.Location = nil + } else { + a.view.Location = &next + } + return true + } + return false +} + +// holdKeyboardFact reads the desktop's own driver answer into the agent's +// location and says agent.changed when that moved the view. It does nothing +// for a connection that is no longer the agent's (a later open owns the fact). +func (b *appBackend) holdKeyboardFact(a *appAgent, conn *appConn, client *remote.Client) { + kb := heldKeyboardOf(client.Driver()) + var view appwire.Agent + changed := false + b.locked(func() { + if a.live == nil || a.live.conn != conn { + return + } + a.heldKeyboard = kb + changed = a.layKeyboardLocked() + view = a.view + }) + if changed { + b.emit.Emit(appwire.EventAgentChanged, appwire.AgentChanged{Agent: view}) + } +} + +// watchHeldDriver says who has the keyboard of a chat this desktop holds +// whenever the engine's answer moves, and stops with the connection. +func (b *appBackend) watchHeldDriver(a *appAgent, conn *appConn) { + agent, ok := conn.Conv.(*remote.Agent) + if !ok || conn.Gone == nil { + return + } + client := agent.Client() + b.holdKeyboardFact(a, conn, client) + guard.Go("app/held-driver", func() { + for { + changed := client.DriverChanged() + select { + case <-conn.Gone: + // THE CHAT IS LET GO: the fact goes with it, unless a later open + // of the same agent has already taken it over. + var view appwire.Agent + cleared := false + b.locked(func() { + if a.live == nil || a.live.conn == conn { + a.heldKeyboard = nil + cleared = a.layKeyboardLocked() + view = a.view + } + }) + if cleared { + b.emit.Emit(appwire.EventAgentChanged, appwire.AgentChanged{Agent: view}) + } + return + case <-changed: + } + b.holdKeyboardFact(a, conn, client) + } + }) +} + +// heldKeyboardCall is chats.live_keyboard for a chat this desktop holds: who +// has the keyboard and, when asked, the desktop's own window takes it. It is +// answered only for a chat the desktop opened behind its door with remote +// control on; for every other chat it says what it always said. +func (b *appBackend) heldKeyboardCall(a *appAgent, p appwire.ChatLiveKeyboardParams) (appwire.ChatLiveKeyboardResult, error) { + notLive := appwire.Errorf(appwire.CodeConflict, "this chat is not open live") + live := b.liveOf(a) + if live == nil || !live.conn.Held || !config.RemoteControlOn() { + return appwire.ChatLiveKeyboardResult{}, notLive + } + agent, ok := live.conn.Conv.(*remote.Agent) + if !ok { + return appwire.ChatLiveKeyboardResult{}, notLive + } + client := agent.Client() + if p.Take { + if err := client.Take(); err != nil { + return appwire.ChatLiveKeyboardResult{}, appwire.Errorf(appwire.CodeConflict, "%s", err.Error()) + } + } + b.holdKeyboardFact(a, live.conn, client) + return appwire.ChatLiveKeyboardResult{Driver: appLiveDriverOf(client.Driver())}, nil +} diff --git a/cmd/codeaf/app_held_keyboard_test.go b/cmd/codeaf/app_held_keyboard_test.go new file mode 100644 index 0000000000..799b604b9b --- /dev/null +++ b/cmd/codeaf/app_held_keyboard_test.go @@ -0,0 +1,286 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/remote" +) + +// These tests are the desk's way of taking the keyboard back on a chat it holds +// (contract K1-K6 in NOTES-POLISH). They use the real chat opener over a real +// holder door and a real second computer dialled to it, and read what the app is +// TOLD (agent.changed carrying location.keyboard) and what the app's one call +// (chats.live_keyboard) does, never how the engine keeps the fact. + +// driverViewer is another computer that may type: the hello the live door's +// router writes for a computer whose permit allows driving, so it can take the +// keyboard by asking. The rig's own viewer only watches. +func (r *deskHeldRig) driverViewer(socket string) (*remote.Client, error) { + r.t.Helper() + conn, err := livedoor.UnixTransport().Dial(context.Background(), socket) + if err != nil { + r.t.Fatalf("the holder door did not accept a connection: %v", err) + } + client, err := remote.Dial(conn, "studio", remote.Hello{ + Workspace: r.root, Session: r.file, Join: true, Back: true, Surface: "laptop", + Remote: &remote.RemoteViewer{Device: "devicelaptop0002", Label: "laptop", Watch: true, Drive: true}, + }) + if err != nil { + _ = conn.Close() + return nil, err + } + r.t.Cleanup(func() { _ = client.Close() }) + return client, nil +} + +// keyboardOf is the keyboard fact an agent.changed carries, nil when it carries +// none. +func keyboardOf(data any) *appwire.LiveDriver { + changed, ok := data.(appwire.AgentChanged) + if !ok || changed.Agent.Location == nil { + return nil + } + return changed.Agent.Location.Keyboard +} + +// heldKeyboardRig is a desk with one held chat open, a backend over it, and the +// door's socket. +type heldKeyboardRig struct { + *deskHeldRig + b *appBackend + rec *appRecorder + id string + socket string +} + +func newHeldKeyboardRig(t *testing.T) *heldKeyboardRig { + t.Helper() + r := newDeskHeldRig(t, true) + rec := newAppRecorder() + b := newFakeBackend(rec, func(appOpenAsk) (*appConn, error) { return r.open(), nil }) + t.Cleanup(func() { _ = b.Close() }) + agent, err := mustCreate(t, b, appwire.CreateAsk{}) + if err != nil { + t.Fatal(err) + } + a, _ := b.find(agent.ID) + b.locked(func() { a.transcript = r.file }) + socket, found := r.registry() + if !found { + t.Fatal("the held chat has no holder door") + } + return &heldKeyboardRig{deskHeldRig: r, b: b, rec: rec, id: agent.ID, socket: socket} +} + +// view is the agent as the app would draw it now. +func (h *heldKeyboardRig) view() appwire.Agent { + h.t.Helper() + a, err := h.b.find(h.id) + if err != nil { + h.t.Fatal(err) + } + var view appwire.Agent + h.b.locked(func() { view = a.view }) + return view +} + +// waitKeyboard waits for an agent.changed for this chat whose keyboard fact +// satisfies ok, after the events already seen. +func (h *heldKeyboardRig) waitKeyboard(what string, ok func(*appwire.LiveDriver) bool) { + h.t.Helper() + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + var last *appwire.LiveDriver + found := false + h.rec.mu.Lock() + for i, event := range h.rec.events { + if event != appwire.EventAgentChanged { + continue + } + if changed, isAgent := h.rec.data[i].(appwire.AgentChanged); isAgent && changed.Agent.ID == h.id { + last, found = keyboardOf(changed), true + } + } + h.rec.mu.Unlock() + if found && ok(last) { + return + } + time.Sleep(20 * time.Millisecond) + } + h.t.Fatalf("the app was never told %s; the view says %+v", what, h.view().Location) +} + +// K3: nothing is said while the desk holds the keyboard, whether or not another +// computer is attached; it is said when another computer takes it (K1), the +// fact names the computer and is not "yours", and it goes (K4) the moment that +// computer leaves, with no click, because the engine hands the keyboard back. +func TestADeskHeldChatSaysWhoHasTheKeyboardAndWhenItIsBack(t *testing.T) { + h := newHeldKeyboardRig(t) + if loc := h.view().Location; loc != nil && loc.Keyboard != nil { + t.Fatalf("a chat nobody else is in carries a keyboard fact: %+v", loc.Keyboard) + } + laptop, err := h.driverViewer(h.socket) + if err != nil { + t.Fatalf("another computer could not join: %v", err) + } + // Joining does not move the keyboard: a remote viewer takes it only by asking. + time.Sleep(200 * time.Millisecond) + if loc := h.view().Location; loc != nil && loc.Keyboard != nil { + t.Fatalf("another computer joined without taking the keyboard and the desk says %+v", loc.Keyboard) + } + if err := laptop.Take(); err != nil { + t.Fatal(err) + } + h.waitKeyboard("that the laptop has the keyboard", func(d *appwire.LiveDriver) bool { + return d != nil && d.Machine == "laptop" && !d.Yours && !d.Here + }) + if loc := h.view().Location; loc == nil || !loc.Here || loc.Keyboard == nil || loc.Keyboard.Machine != "laptop" { + t.Fatalf("the agent's own view does not carry the fact on a chat held here: %+v", loc) + } + // The computer leaves; the desk is the typist again without anybody pressing. + _ = laptop.Close() + h.waitKeyboard("that the keyboard came back", func(d *appwire.LiveDriver) bool { return d == nil }) + if loc := h.view().Location; loc != nil && loc.Keyboard != nil { + t.Fatalf("the fact outlived the other computer: %+v", loc.Keyboard) + } +} + +// K2, K6: pressing Type here is one call; the desk is the typist at once, the +// fact goes, the other computer is told and its own send is refused in the +// engine's sentence; and while the other computer holds the keyboard the desk's +// own send is refused the same way, which is the sentence the composer shows. +func TestTheDeskTakesTheKeyboardBackOnAChatItHolds(t *testing.T) { + h := newHeldKeyboardRig(t) + laptop, err := h.driverViewer(h.socket) + if err != nil { + t.Fatal(err) + } + if err := laptop.Take(); err != nil { + t.Fatal(err) + } + h.waitKeyboard("that the laptop has the keyboard", func(d *appwire.LiveDriver) bool { return d != nil && d.Machine == "laptop" }) + + a, _ := h.b.find(h.id) + live := h.b.liveOf(a) + if live == nil { + t.Fatal("the held chat is not open") + } + // K6: the desk's own words are refused with the engine's sentence naming who has it. + if _, err := live.conn.Conv.Submit(context.Background(), "typed on the desk"); err == nil || !strings.Contains(err.Error(), "laptop") { + t.Fatalf("the desk's send while the laptop types was %v, want a refusal naming the laptop", err) + } + + got, err := h.b.LiveKeyboard(appwire.ChatLiveKeyboardParams{Agent: h.id, Take: true}) + if err != nil { + t.Fatalf("Type here was refused: %v", err) + } + if !got.Driver.Yours { + t.Fatalf("the answer to Type here says %+v, want the desk as the typist", got.Driver) + } + h.waitKeyboard("that the keyboard is the desk's", func(d *appwire.LiveDriver) bool { return d == nil }) + if loc := h.view().Location; loc != nil && loc.Keyboard != nil { + t.Fatalf("the desk took the keyboard and still says %+v", loc.Keyboard) + } + // The laptop is told, and its own send is now refused in the engine's words. + deadline := time.Now().Add(10 * time.Second) + for laptop.Driver().Yours && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + if laptop.Driver().Yours { + t.Fatal("the laptop still thinks it has the keyboard after the desk took it") + } + if _, err := laptop.Agent().Submit(context.Background(), "typed on the laptop"); err == nil { + t.Fatal("the laptop's send was accepted while the desk has the keyboard") + } + // Nothing was lost: the desk's answer to its own words goes on as always. + if told := h.say(h.liveConn(), "back on the desk"); len(told) == 0 { + t.Fatal("the desk's own turn after taking the keyboard back said nothing") + } +} + +func (h *heldKeyboardRig) liveConn() *appConn { + h.t.Helper() + a, _ := h.b.find(h.id) + live := h.b.liveOf(a) + if live == nil { + h.t.Fatal("the held chat is not open") + } + return live.conn +} + +// K3, K5: Type here is answered only for a chat this desktop holds for others +// and only while remote control is on. On a desktop with it off the call +// answers what it always did, and no agent ever carries a keyboard fact. +func TestWithRemoteControlOffThereIsNoKeyboardFactAndTheCallAnswersAsBefore(t *testing.T) { + r := newDeskHeldRig(t, false) + rec := newAppRecorder() + b := newFakeBackend(rec, func(appOpenAsk) (*appConn, error) { return r.open(), nil }) + t.Cleanup(func() { _ = b.Close() }) + agent, err := mustCreate(t, b, appwire.CreateAsk{}) + if err != nil { + t.Fatal(err) + } + _, err = b.LiveKeyboard(appwire.ChatLiveKeyboardParams{Agent: agent.ID, Take: true}) + var wireErr *appwire.Error + if !errors.As(err, &wireErr) || wireErr.Code != appwire.CodeConflict || !strings.Contains(wireErr.Message, "this chat is not open live") { + t.Fatalf("Type here on a chat that is not offered answered %v", err) + } + rec.mu.Lock() + defer rec.mu.Unlock() + for i, event := range rec.events { + if event == appwire.EventAgentChanged && keyboardOf(rec.data[i]) != nil { + t.Fatalf("an agent carried a keyboard fact with remote control off: %+v", rec.data[i]) + } + } +} + +// The fact is the app's own and the chat list's word about where the chat is +// held must not wipe it: a refreshed location (the chat is here) or none keeps +// what the engine last said, and a location that says the chat is NOT here +// carries no keyboard, because the desk is not running it. +func TestAChatListUpdateKeepsTheKeyboardFactOfAChatHeldHere(t *testing.T) { + h := newHeldKeyboardRig(t) + laptop, err := h.driverViewer(h.socket) + if err != nil { + t.Fatal(err) + } + if err := laptop.Take(); err != nil { + t.Fatal(err) + } + h.waitKeyboard("that the laptop has the keyboard", func(d *appwire.LiveDriver) bool { return d != nil && d.Machine == "laptop" }) + a, _ := h.b.find(h.id) + + h.b.located(a, &appwire.Location{Here: true, Cell: "c1", Seen: &appwire.Seen{Device: "d", Fence: 3}}) + loc := h.view().Location + if loc == nil || loc.Cell != "c1" || loc.Keyboard == nil || loc.Keyboard.Machine != "laptop" { + t.Fatalf("a refreshed location lost the keyboard fact: %+v", loc) + } + h.b.located(a, nil) + if loc := h.view().Location; loc == nil || !loc.Here || loc.Keyboard == nil { + t.Fatalf("a missing location lost the keyboard fact: %+v", loc) + } + h.b.located(a, &appwire.Location{Here: false, Cell: "c1", Line: "tower has this chat"}) + if loc := h.view().Location; loc == nil || loc.Keyboard != nil { + t.Fatalf("a chat the list says is held elsewhere still carries a keyboard fact: %+v", loc) + } +} + +// The wire shape: absent unless the desk holds a chat another window types in, +// spelled with the same three words a live view's driver uses. +func TestTheKeyboardFactIsOmittedUnlessSaid(t *testing.T) { + raw, err := json.Marshal(appwire.Location{Here: true}) + if err != nil || strings.Contains(string(raw), "keyboard") { + t.Fatalf("a location with no fact says %s, %v", raw, err) + } + raw, err = json.Marshal(appwire.Location{Here: true, Keyboard: &appwire.LiveDriver{Machine: "laptop"}}) + if err != nil || !strings.Contains(string(raw), `"keyboard":{"machine":"laptop"}`) { + t.Fatalf("the fact says %s, %v", raw, err) + } +} diff --git a/cmd/codeaf/app_lend.go b/cmd/codeaf/app_lend.go index f2a828309b..f619b3dfa0 100644 --- a/cmd/codeaf/app_lend.go +++ b/cmd/codeaf/app_lend.go @@ -108,8 +108,8 @@ func (b *appBackend) lentFence(a *appAgent, what string) error { var live *appLive var transcript string b.locked(func() { live, transcript = a.live, a.transcript }) - if live != nil && live.conn.Lent { - return errLentStage(what) + if live != nil && (live.conn.Lent || live.conn.Remote) { + return appFenceError(live.conn, what) } if live == nil && transcript != "" { if _, staged := liveStageFor(transcript); staged { @@ -122,7 +122,7 @@ func (b *appBackend) lentFence(a *appAgent, what string) error { // bindBudgetConn is [appBackend.bindBudget] for a held connection: a lent stage // keeps the factory's budget, so the app's saved agent figure is not bound onto it. func (b *appBackend) bindBudgetConn(id string, conn *appConn) error { - if conn.Lent { + if conn.Lent || conn.Remote { return nil } return b.bindBudget(id, conn.Conv) diff --git a/cmd/codeaf/app_live.go b/cmd/codeaf/app_live.go new file mode 100644 index 0000000000..977c1a13f6 --- /dev/null +++ b/cmd/codeaf/app_live.go @@ -0,0 +1,304 @@ +package main + +import ( + "errors" + "path/filepath" + "sync" + + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/home" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/remote" +) + +// ── THE DESKTOP AS A HOLDER OF CHATS ───────────────────────────────────────── +// +// Another computer opens a chat THIS desktop is running by dialling the holder's +// own live door (livedoor.Listen: a socket beside a registry file under +// /v3/live, named by this process's id), which hands it the very +// conversation the desktop's own window is looking at. For that the +// conversation has to be something a second surface can join, which a +// conversation opened through [remote.Loopback] is not: Loopback's session +// belongs to its one pipe, and a torn pipe ends it. +// +// SO A CHAT THE DESKTOP BUILDS WHILE REMOTE CONTROL IS ON GETS A PERSISTENT +// SESSION INSTEAD ([appDeskHost.open]), and nothing else about it changes. The +// desktop's own view is still one in-process attach over an in-memory pipe, the +// connection is still marked Assembled, and every road that ends the chat still +// ends in [appConn.Release]: the view lets go, the session is closed behind it, +// and the chat leaves the door. The persistent flag matters only to somebody +// ELSE arriving: a viewer's torn pipe keeps the conversation, because the +// desktop's window is still in the room. +// +// WITH REMOTE CONTROL OFF (the default) NONE OF THIS RUNS. No listener, no +// registry file, no socket, no persistent session: [appDeskHost.ready] answers +// false and the open is the one it was before this file existed. +// +// IT IS PROCESS-WIDE BECAUSE THE DOOR IS. One process has one pid, one socket +// and one registry file, however many backends a test makes, and the chat opener +// ([appOpenInProcess]) is a plain function with no backend to hang this on. + +// appDeskHost is the desktop's holder door and the chats behind it. +type appDeskHost struct { + // listen starts the door. It is a field so a test can stand in a different + // one, never to change what the door does. + listen func(homeDir string, open func(transcript string) (*remote.Session, bool), tr livedoor.Transport) (*livedoor.Listener, error) + + mu sync.Mutex + listener *livedoor.Listener + // failed says starting the door failed once in this process (a state folder + // whose path is too long for a socket, a read-only home). It is remembered, + // so a desktop that cannot be a holder says so once and goes on opening its + // chats the way it did, instead of retrying on every chat. + failed bool + sessions map[string]*remote.Session +} + +// locked runs f under the door's lock, which is released from a defer even if f +// panics (the guarded tree's law: a panic absorbed upstream must not become a +// deadlock here). +func (h *appDeskHost) locked(f func()) { + h.mu.Lock() + defer h.mu.Unlock() + f() +} + +// deskHost is this process's holder door. +var deskHost = newAppDeskHost() + +func newAppDeskHost() *appDeskHost { + return &appDeskHost{ + listen: livedoor.Listen, + sessions: map[string]*remote.Session{}, + } +} + +// appDeskKey is how a chat's transcript is looked up: the path the door names +// is the holder's own spelling of it, and the engine's may differ by a symlink +// (the macOS temporary folder is one), so both sides are spelled physically. +func appDeskKey(transcript string) string { + if transcript == "" { + return "" + } + path := filepath.Clean(transcript) + if physical, err := filepath.EvalSymlinks(path); err == nil { + return physical + } + if dir, err := filepath.EvalSymlinks(filepath.Dir(path)); err == nil { + return filepath.Join(dir, filepath.Base(path)) + } + return path +} + +// ready says the door is up for a chat about to be opened, starting it the +// first time. It is false with remote control off, and false when the door could +// not be started: those chats stay ordinary desktop chats. +func (h *appDeskHost) ready() bool { + if !config.RemoteControlOn() { + return false + } + h.mu.Lock() + defer h.mu.Unlock() + if h.listener != nil { + return true + } + if h.failed { + return false + } + l, err := h.listen(home.Dir(), h.lookup, livedoor.UnixTransport()) + if err != nil { + h.failed = true + return false + } + h.listener = l + return true +} + +// lookup is the door's question: is this chat open here. A chat that has ended +// is not, and an answer "no" is the refusal the viewer reads as not-running. +func (h *appDeskHost) lookup(transcript string) (*remote.Session, bool) { + // THE SETTING IS READ AGAIN HERE, so switching remote control off stops + // handing chats out at once, without waiting for the chats to close. + if !config.RemoteControlOn() { + return nil, false + } + key := appDeskKey(transcript) + var sess *remote.Session + h.locked(func() { sess = h.sessions[key] }) + // THE SESSION IS ASKED OUTSIDE THIS LOCK, so that no order between the + // door's lock and the session's own is ever taken. + if sess == nil || sess.Ended() { + return nil, false + } + return sess, true +} + +// viewers is how many OTHER surfaces are watching the chat on this transcript: +// everybody attached except the desktop's own view. It is zero for a chat that +// is not held through the door. +func (h *appDeskHost) viewers(transcript string) int { + if h == nil || transcript == "" { + return 0 + } + key := appDeskKey(transcript) + var sess *remote.Session + h.locked(func() { sess = h.sessions[key] }) + if sess == nil || sess.Ended() { + return 0 + } + return max(sess.Attached()-1, 0) +} + +// closeListener takes the door down once the app has let every chat go. A chat +// still registered (a second backend in a test, nothing in production) keeps it. +func (h *appDeskHost) closeListener() { + var l *livedoor.Listener + h.locked(func() { + l = h.listener + if len(h.sessions) > 0 { + l = nil + } else { + h.listener = nil + } + }) + if l != nil { + _ = l.Close() + } +} + +// appHeld is one chat the door can reach: the persistent session behind it and +// the key it is filed under. +type appHeld struct { + host *appDeskHost + sess *remote.Session + key string +} + +// drop takes the chat off the door, so nobody new can join it while it closes. +func (h *appHeld) drop() { + if h == nil { + return + } + h.host.locked(func() { + if h.host.sessions[h.key] == h.sess { + delete(h.host.sessions, h.key) + } + }) +} + +// endViewers tells everybody else watching the chat that it is over, by closing +// their connections. +func (h *appHeld) endViewers() { + if h == nil { + return + } + h.host.endViewers(h.key) +} + +// close ends the conversation behind the door. The desktop's view has already +// let go, so a chat nobody else is watching closes through the same door it +// always did (a retirement), and one a viewer is still watching tells that +// viewer the engine stopped. +// +// THE RESULT IS NOT RECORDED, which is what the in-process open has always done +// with it: the final save's failure is carried by the conversation's own close +// notices, and [recordFinalSaveFailure] of the pipe's close (the only thing the +// loopback open records) is nil. +func (h *appHeld) close() { + if h == nil { + return + } + _ = h.sess.Close() +} + +// open is [remote.Loopback] for a chat the door can reach. boot is the engine's +// own opener, called exactly once with the hello the engine receives from any +// loopback. +// +// IT RETURNS A NIL appHeld WHEN THE DOOR IS NOT UP, AND THE LOOPBACK IT RETURNS +// THEN IS THE ONE THE DESKTOP ALWAYS OPENED. The caller releases both the same +// way either time. +func (h *appDeskHost) open(hello remote.Hello, boot func(remote.Hello) (*remote.Engine, error)) (*remote.Loop, *appHeld, error) { + if !h.ready() { + loop, err := remote.Loopback(hello, remote.Options{Boot: boot}) + return loop, nil, err + } + var sess *remote.Session + var key string + loop, err := remote.LoopbackAttach(hello, remote.AttachOptions{ + Open: func(asked remote.Hello) (*remote.Session, error) { + // The same refusal [remote.Serve] gives: this door opens its own + // conversation, and a join names one that is already open. + if asked.Join { + return nil, errors.New("this engine opens one conversation for one connection, so there is none already open here to join") + } + engine, err := boot(asked) + if err != nil { + return nil, err + } + if engine == nil { + return nil, nil + } + key = appDeskKey(engine.SessionFile) + sess = remote.NewSession(engine, true) + return sess, nil + }, + }) + if err != nil { + // A PERSISTENT SESSION SURVIVES A FAILED ATTACH, which Loopback's does + // not: with nothing to close it the agent would stay open on a + // conversation nobody holds. + if sess != nil { + _ = sess.Close() + } + return nil, nil, err + } + held := &appHeld{host: h, sess: sess, key: key} + if key != "" { + h.locked(func() { h.sessions[key] = sess }) + } + return loop, held, nil +} + +// deskViewed says another computer is watching the agent's chat through this +// desktop's door. It reads the transcript under the backend's lock and asks the +// door outside it, so the two locks are never held together. +func (b *appBackend) deskViewed(a *appAgent) bool { + var transcript string + b.locked(func() { transcript = a.transcript }) + return deskHost.viewers(transcript) > 0 +} + +// ── ENDING A CHAT'S VIEWERS ────────────────────────────────────────────────── +// +// A remote.Session that is closed tells its attached surfaces nothing and leaves +// their pipes open: the one door that ever closed a conversation with a window +// still in it (a goodbye) ends only the window that said it. A viewer of a chat +// the desktop lets go has to be told, and the way the live door's router tells a +// person is the holder's socket closing: it reads the end of the local +// connection as "the holder is gone", ends the channel with that reason, and the +// viewer's roaming client redials and finds the chat not running. +// +// THE LISTENER KNOWS WHICH CONNECTION OPENED WHICH CHAT, so letting a chat go is +// one call to [livedoor.Listener.CloseChat]. (Before it did, this file wrapped +// the transport to read every connection's hello on its way past.) + +// endAllViewers closes every connection another computer holds to any chat this +// desktop is running. It is what turning remote control off does for the people +// already looking, beside the door's own refusal of anyone new. +func (h *appDeskHost) endAllViewers() { + var l *livedoor.Listener + h.locked(func() { l = h.listener }) + if l != nil { + l.CloseAllChats() + } +} + +// endViewers closes every connection another computer holds to the chat on key. +func (h *appDeskHost) endViewers(key string) { + var l *livedoor.Listener + h.locked(func() { l = h.listener }) + if l != nil { + l.CloseChat(key) + } +} diff --git a/cmd/codeaf/app_live_host_test.go b/cmd/codeaf/app_live_host_test.go new file mode 100644 index 0000000000..0d002198df --- /dev/null +++ b/cmd/codeaf/app_live_host_test.go @@ -0,0 +1,393 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/home" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" +) + +// The rig of these tests is the real chat opener's own tail +// ([appOpenAssembled]) over a real conversation and a stand-in provider, so +// what is asserted is how the desktop holds a chat and who else can reach it, +// never how the engine was assembled. The holder door is a real one on a real +// socket under a short state root, and the "other computer" is a real client +// dialled to it the way the live door's router dials a holder. + +type deskHeldRig struct { + t *testing.T + root string + file string + engine *session.Agent + provider *httptest.Server + asked atomic.Int32 + booted atomic.Int32 +} + +func newDeskHeldRig(t *testing.T, remoteControl bool) *deskHeldRig { + t.Helper() + shortStateRoot(t) + t.Setenv("HOME", t.TempDir()) + t.Setenv(config.ProfileDirEnv, t.TempDir()) + t.Setenv(config.APIKeyEnv, "") + t.Setenv("CODEAF_SYNC_URL", "off") + if remoteControl { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + } else { + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + } + // A door of this test's own, taken down with it. + previous := deskHost + deskHost = newAppDeskHost() + t.Cleanup(func() { + deskHost.mu.Lock() + l := deskHost.listener + deskHost.listener = nil + deskHost.mu.Unlock() + if l != nil { + _ = l.Close() + } + deskHost = previous + }) + + r := &deskHeldRig{t: t} + r.provider = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + r.asked.Add(1) + _, _ = io.Copy(io.Discard, req.Body) + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "data: "+`{"choices":[{"index":0,"delta":{"role":"assistant","content":"desk answer"},"finish_reason":"stop"}]}`+"\n\n") + fmt.Fprint(w, "data: [DONE]\n\n") + })) + t.Cleanup(r.provider.Close) + r.root = t.TempDir() + r.file = filepath.Join(r.root, "transcript.jsonl") + engine, err := session.New(session.Config{Workspace: r.root, SessionFile: r.file, Model: "test/model", APIKey: "fixture", + BaseURL: r.provider.URL, OneModel: true, DeterministicNames: true, PromptProfile: "full"}) + if err != nil { + t.Fatal(err) + } + r.engine = engine + return r +} + +// open is the desktop opening this chat as its own. +func (r *deskHeldRig) open() *appConn { + r.t.Helper() + conn, err := appOpenAssembled(remote.Hello{Workspace: r.root, Session: r.file}, func(remote.Hello) (*remote.Engine, error) { + r.booted.Add(1) + return &remote.Engine{Agent: r.engine, SessionFile: r.file, Workspace: r.root}, nil + }) + if err != nil { + r.t.Fatal(err) + } + return conn +} + +// registry reads the holder door's registry file for this process, the file the +// live door's resolver dials, and returns its socket's full path. +func (r *deskHeldRig) registry() (socket string, ok bool) { + r.t.Helper() + raw, err := os.ReadFile(filepath.Join(home.Dir(), "v3", "live", fmt.Sprint(os.Getpid())+".json")) + if err != nil { + return "", false + } + var entry struct { + PID int `json:"pid"` + Socket string `json:"socket"` + } + if err := json.Unmarshal(raw, &entry); err != nil || entry.PID != os.Getpid() || entry.Socket == "" { + r.t.Fatalf("the registry file is not the holder's own: %s", raw) + } + return filepath.Join(home.Dir(), "v3", "live", entry.Socket), true +} + +// viewer is another computer's connection to the chat through the holder door: +// the hello the live door's router writes for a watcher, over the door's socket. +func (r *deskHeldRig) viewer(socket string) (*remote.Client, error) { + r.t.Helper() + conn, err := livedoor.UnixTransport().Dial(context.Background(), socket) + if err != nil { + r.t.Fatalf("the holder door did not accept a connection: %v", err) + } + client, err := remote.Dial(conn, "studio", remote.Hello{ + Workspace: r.root, Session: r.file, Join: true, Watch: true, Back: true, + Remote: &remote.RemoteViewer{Device: "devicelaptop0001", Label: "laptop", Watch: true}, + }) + if err != nil { + _ = conn.Close() + return nil, err + } + r.t.Cleanup(func() { _ = client.Close() }) + return client, nil +} + +// say is the desktop's person sending one message in the chat, and what the +// desktop's own view was told of the turn, in order. +func (r *deskHeldRig) say(conn *appConn, text string) []string { + r.t.Helper() + events, err := conn.Conv.Submit(context.Background(), text) + if err != nil { + r.t.Fatal(err) + } + var told []string + for ev := range events { + told = append(told, fmt.Sprintf("%v|%s|%s", ev.Kind, ev.Tool, ev.Text)) + } + return told +} + +func (r *deskHeldRig) transcriptOf(client *remote.Client) []string { + r.t.Helper() + page, err := client.Agent().TranscriptPage(context.Background(), 0, 50) + if err != nil { + r.t.Fatal(err) + } + var out []string + for _, entry := range page.Entries { + out = append(out, entry.Role+"|"+entry.Text) + } + return out +} + +// V-desk-1 / V-desk-2 / V-desk-3 (a chat the desktop is running is reachable +// through the desktop's holder door, and only while the desktop holds it): with +// remote control on, a chat the desktop opens is listed in the holder door's +// registry and another computer's watcher joins THE SAME conversation the +// desktop's own window is in, seeing a turn the desktop sends. Closing the chat +// takes it off the door at once, ends the watcher's connection, and closes the +// engine's conversation; a second watcher is told the chat is not open here. A +// watcher's own departure ends nothing: the desktop's window is still in the room. +func TestADeskHeldChatIsRoutableByTheDoorAndReleasedWhenClosed(t *testing.T) { + r := newDeskHeldRig(t, true) + if _, found := r.registry(); found { + t.Fatal("the door must not exist before a chat is held") + } + conn := r.open() + t.Cleanup(conn.Release) + socket, found := r.registry() + if !found { + t.Fatal("a chat the desktop opened with remote control on has no holder door") + } + if got := deskHost.viewers(r.file); got != 0 { + t.Fatalf("nobody else is watching yet, the door says %d", got) + } + if !conn.Conv.(*remote.Agent).WorkOutlivesExit() { + t.Fatal("the chat behind the door is a persistent conversation, so a viewer's torn pipe keeps it") + } + + viewer, err := r.viewer(socket) + if err != nil { + t.Fatalf("another computer could not join the chat through the door: %v", err) + } + if got := deskHost.viewers(r.file); got != 1 { + t.Fatalf("one other computer is watching, the door says %d", got) + } + r.say(conn, "from the desktop") + if r.asked.Load() == 0 { + t.Fatal("the desktop's own turn never reached the provider") + } + var seen []string + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + if seen = r.transcriptOf(viewer); strings.Contains(strings.Join(seen, "\n"), "desk answer") { + break + } + time.Sleep(50 * time.Millisecond) + } + if want := "user|from the desktop"; !strings.Contains(strings.Join(seen, "\n"), want) || !strings.Contains(strings.Join(seen, "\n"), "assistant|desk answer") { + t.Fatalf("the watcher joined another conversation: %q does not hold %q and the answer", seen, want) + } + + // A watcher leaving is not the chat ending. + _ = viewer.Close() + deadline = time.Now().Add(10 * time.Second) + for deskHost.viewers(r.file) != 0 && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + if deskHost.viewers(r.file) != 0 || r.engine.Closed() { + t.Fatal("a watcher's departure closed the desktop's chat or was never noticed") + } + second, err := r.viewer(socket) + if err != nil { + t.Fatalf("a watcher that came back could not join: %v", err) + } + + conn.Release() + if !r.engine.Closed() { + t.Fatal("closing the chat left its conversation open") + } + if _, ok := deskHost.lookup(r.file); ok { + t.Fatal("a closed chat is still handed out by the door") + } + deadline = time.Now().Add(10 * time.Second) + for second.Err() == nil && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + if second.Err() == nil { + t.Fatal("the watcher of a closed chat was never told") + } + if _, err := r.viewer(socket); err == nil || !strings.Contains(err.Error(), "not open here") { + t.Fatalf("a chat that is not open here must say so, got %v", err) + } + deskHost.closeListener() + if _, found := r.registry(); found { + t.Fatal("the registry file outlived the door") + } +} + +// V-desk-4 (a desktop with remote control off has no door and holds chats as it +// always did): no listener, no registry file, no socket, and the chat's +// conversation is a lifetime of its one pipe, the shape the desktop has always +// opened. +func TestADeskChatWithRemoteControlOffHasNoDoor(t *testing.T) { + r := newDeskHeldRig(t, false) + conn := r.open() + t.Cleanup(conn.Release) + if _, found := r.registry(); found { + t.Fatal("remote control is off, and the desktop opened a holder door") + } + if entries, err := os.ReadDir(filepath.Join(home.Dir(), "v3", "live")); err == nil && len(entries) > 0 { + t.Fatalf("remote control is off, and the desktop left files in the live folder: %v", entries) + } + if conn.Conv.(*remote.Agent).WorkOutlivesExit() { + t.Fatal("remote control is off, and the chat is a persistent conversation") + } + deskHost.mu.Lock() + held := len(deskHost.sessions) + deskHost.mu.Unlock() + if held != 0 { + t.Fatalf("remote control is off, and the desktop filed %d chats under a door", held) + } +} + +// V-desk-5 (a desk chat nobody else is watching behaves as it always did): the +// same exchange through the door and without it tells the desktop's own view the +// same turn in the same order, leaves the same record, tells the app the same +// opening facts, and ends the conversation the same way when it is let go. The +// persistent shape is invisible to the one view that was always there. +func TestADeskChatNobodyElseWatchesBehavesAsWithoutTheDoor(t *testing.T) { + type observed struct { + told []string + transcript []string + note string + interrupted string + inRoot bool + users int + closed bool + } + run := func(on bool) observed { + r := newDeskHeldRig(t, on) + conn := r.open() + out := observed{note: conn.Note, interrupted: strings.Join(conn.Interrupted, ","), inRoot: conn.Workspace == r.root, users: conn.UserMessages} + out.told = r.say(conn, "same words") + out.told = append(out.told, r.say(conn, "and again")...) + page, err := conn.Conv.(*remote.Agent).TranscriptPage(context.Background(), 0, 50) + if err != nil { + t.Fatal(err) + } + for _, entry := range page.Entries { + out.transcript = append(out.transcript, entry.Role+"|"+entry.Text) + } + conn.Release() + out.closed = r.engine.Closed() + // Letting go twice is the same as once, as it has always been. + conn.Release() + return out + } + off, on := run(false), run(true) + // THE TITLE ARRIVES FROM ITS OWN GOROUTINE, so where among the turn's first + // events it lands is the engine's timing on either shape and not something + // the door could change. It is compared as a fact (the same words, once); + // everything else is compared in order. + titled := func(told []string) (title string, rest []string) { + mark := fmt.Sprintf("%v||", session.EventTitleChanged) + for _, line := range told { + if strings.HasPrefix(line, mark) { + title += line + continue + } + rest = append(rest, line) + } + return title, rest + } + offTitle, offRest := titled(off.told) + onTitle, onRest := titled(on.told) + off.told, on.told = offRest, onRest + if offTitle != onTitle || offTitle == "" { + t.Fatalf("the chat was named differently: without the door %q, with it %q", offTitle, onTitle) + } + if strings.Join(off.told, "\n") != strings.Join(on.told, "\n") || len(off.told) == 0 { + t.Fatalf("the desktop's own view was told a different turn:\n without the door: %q\n with the door: %q", off.told, on.told) + } + if strings.Join(off.transcript, "\n") != strings.Join(on.transcript, "\n") || len(off.transcript) < 4 { + t.Fatalf("the record differs:\n without the door: %q\n with the door: %q", off.transcript, on.transcript) + } + if off.note != on.note || off.interrupted != on.interrupted || off.inRoot != on.inRoot || off.users != on.users { + t.Fatalf("the app was told different opening facts: %+v vs %+v", off, on) + } + if !off.closed || !on.closed { + t.Fatalf("a chat let go must be closed: without the door %v, with it %v", off.closed, on.closed) + } +} + +// V-desk-6 (a chat somebody is watching through this desktop is not let go as +// idle, and is again once they leave): the idle sweep keeps a held chat while +// another computer is attached to it, and the clock starts over when they go. +func TestTheIdleSweepKeepsAChatAnotherComputerIsWatching(t *testing.T) { + r := newDeskHeldRig(t, true) + rec := newAppRecorder() + b := newFakeBackend(rec, func(appOpenAsk) (*appConn, error) { return r.open(), nil }) + t.Cleanup(func() { _ = b.Close() }) + agent, err := mustCreate(t, b, appwire.CreateAsk{}) + if err != nil { + t.Fatal(err) + } + a, _ := b.find(agent.ID) + b.locked(func() { a.transcript = r.file }) + socket, found := r.registry() + if !found { + t.Fatal("the held chat has no holder door") + } + viewer, err := r.viewer(socket) + if err != nil { + t.Fatal(err) + } + old := func() { + b.locked(func() { + if live := a.live; live != nil { + live.lastUse = b.now().Add(-appAgentIdle - time.Second) + live.running = false + } + }) + } + old() + b.sweepAgent(a, b.now()) + if b.liveOf(a) == nil { + t.Fatal("the sweep let go a chat another computer is watching") + } + _ = viewer.Close() + deadline := time.Now().Add(10 * time.Second) + for deskHost.viewers(r.file) != 0 && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + old() + b.sweepAgent(a, b.now()) + if b.liveOf(a) != nil { + t.Fatal("the sweep kept an idle chat nobody is watching") + } +} diff --git a/cmd/codeaf/app_live_open.go b/cmd/codeaf/app_live_open.go new file mode 100644 index 0000000000..331be3dc9c --- /dev/null +++ b/cmd/codeaf/app_live_open.go @@ -0,0 +1,846 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "path/filepath" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/cell" + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/devname" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" + "github.com/Agent-Field/codeaf/internal/syncsetup" +) + +// ── OPENING ANOTHER COMPUTER'S CHAT LIVE ───────────────────────────────────── +// +// A chat a paired computer is running is served to the desktop AS A LOCAL-LOOKING +// AGENT: the engine dials that computer's live door, wraps the connection the +// way a join of a window's host is wrapped (appJoinExisting), and files it as an +// agent, so the chat page, its composer, asks, steer, queue and stop work +// unchanged. A live send is therefore `agents.send`, NEVER `chats.send`: the +// computer is on and the words reach its running conversation, so nothing is +// stored on a relay and the storage refusal that belongs to a waiting note does +// not apply (app_notes.go keeps it for the OFFLINE case). +// +// Everything is behind `config.RemoteControlOn()`, which is OFF by default: with +// it off the desktop is never told the feature exists (ChatsLiveOffered), so it +// sends no new call and the engine behaves as it did before this file. + +// appLiveWindow is how many display entries one older-page read asks the host +// for. It is the host's own cap, so one read never materializes an unbounded +// batch over a live link. +const appLiveWindow = 200 + +// appLivePlaceholder marks an entry that stands in for a message of the +// person's older than the window held here: it keeps every id counted from the +// first message, and it is never shown. +const appLivePlaceholder = "\x00live" + +// Tests stand in for the relay: the dialer a host's link is built from and the +// answer to "can this engine dial the live door at all". +var ( + appLiveDialable = func(b *appBackend) bool { return syncsetup.MayTalk(b.relayHome()) } + appLiveNewLink = func(b *appBackend, hostID, hostName string, active func() bool, onState func(livedoor.State)) (*livedoor.Link, error) { + s, ok, err := syncsetup.Open(b.relayHome()) + if err != nil { + return nil, err + } + if !ok { + return nil, errors.New("this computer is not paired") + } + return s.LiveLink(hostID, hostName, active, onState), nil + } + appLiveRoam = remote.Roam +) + +var ( + _ appwire.ChatsLiveOpener = (*appBackend)(nil) + _ appwire.ChatsLiveOffer = (*appBackend)(nil) + _ appwire.CallNoter = (*appBackend)(nil) +) + +// appLiveHost is the one link to a paired computer, shared by every chat this +// process views on it. users counts the connections and dials in flight: the +// link is closed, and the relay's tunnel with it, the moment the last is gone, +// so a view nobody is using costs the relay nothing (H1). +type appLiveHost struct { + id, name string + link *livedoor.Link + users int // guarded by appBackend.liveMu +} + +// appLiveRemote is what makes an agent a live view. Its fields are guarded by +// b.mu except win, which has its own lock. +type appLiveRemote struct { + cell string + hostID string + hostName string + // pure says no folder of this chat is on this computer: the agent has only + // this view, and agents.list leaves it out. + pure bool + // state is the link's last word about the road to the host, and driver the + // host's last word about who has the keyboard. + state livedoor.State + hasState bool + driver appwire.LiveDriver + + win appLiveWindowCache +} + +// appLiveWindowCache keeps the older part of the host's transcript already +// read, so scrolling back does not read it again. The tail is always read +// fresh: only the past is immutable. +type appLiveWindowCache struct { + mu sync.Mutex + entries []session.DisplayEntry // host entries [base, base+len) + base int + total int +} + +// liveOnly reports a view with no folder here. Callers hold b.mu. +func (a *appAgent) liveOnly() bool { return a.liveRemote != nil && a.liveRemote.pure } + +// appFenceError is the refusal for a change that is not the app's to make: a +// lent factory stage's is the factory's, a live view's is the other computer's. +func appFenceError(conn *appConn, what string) error { + if conn != nil && conn.Remote { + return appwire.Errorf(appwire.CodeConflict, "this chat is running on another computer: its %s is set there, not from here", what) + } + return errLentStage(what) +} + +// ChatsLiveOffered says the desktop may be told about chats.live: remote +// control is on and this engine can dial a live door. +func (b *appBackend) ChatsLiveOffered() bool { + return config.RemoteControlOn() && appLiveDialable(b) +} + +// appLiveRefusal puts a live-door failure in the host's own words, with the +// closed reason in the detail so the desktop can act on it without reading the +// sentence. A host that is simply not answering is unreachable; one that +// answered and said no is a conflict. +func appLiveRefusal(err error, host string) error { + reason, ok := livedoor.ReasonOf(err) + if !ok && errors.Is(err, livedoor.ErrHostOffline) { + reason, ok = livedoor.ReasonNotRunning, true + } + if !ok { + return &appwire.Error{Code: appwire.CodeUnreachable, Message: chatlist.LiveSaid("", host), Detail: appwire.LiveRefused{Kind: "live_refused", Reason: ""}} + } + code := appwire.CodeUnreachable + switch reason { + case livedoor.ReasonNotAllowed, livedoor.ReasonRemoved, livedoor.ReasonPermitChanged, livedoor.ReasonRemoteControlOff: + code = appwire.CodeConflict + } + return &appwire.Error{Code: code, Message: chatlist.LiveSaid(reason, host), Detail: appwire.LiveRefused{Kind: "live_refused", Reason: reason}} +} + +// OpenLive opens the chat in row cell live. The agent it answers is the agent +// the app opens for it: its id is the chat's local copy when this computer has +// one, else the cell's own id. +func (b *appBackend) OpenLive(p appwire.ChatOpenLiveParams) (appwire.Agent, error) { + if !b.ChatsLiveOffered() { + return appwire.Agent{}, appwire.Errorf(appwire.CodeUnknownMethod, "this engine does not serve %s", "chats.open_live") + } + if !cell.ValidID(p.Cell) { + return appwire.Agent{}, appwire.Errorf(appwire.CodeNotFound, "that chat is not available") + } + row, found := b.chats.rowFor(p.Cell) + if !found { + return appwire.Agent{}, appwire.Errorf(appwire.CodeNotFound, "This chat is no longer listed.") + } + if row.Here { + return appwire.Agent{}, appwire.Errorf(appwire.CodeConflict, "This chat is on this computer.") + } + if row.Holder == nil || row.Holder.ID == "" { + return appwire.Agent{}, appwire.Errorf(appwire.CodeNotFound, "that chat is not available") + } + name := row.Holder.Name + if row.Status != string(chatlist.Running) || (row.Online != nil && !*row.Online) { + return appwire.Agent{}, appLiveRefusal(&livedoor.ReasonError{Reason: livedoor.ReasonNotRunning, Host: name}, name) + } + id := row.LocalAgent + if id == "" { + id = row.Cell + } + return b.openLiveAs(id, row) +} + +func (b *appBackend) openLiveAs(id string, row appwire.ChatRow) (appwire.Agent, error) { + hostID, hostName := row.Holder.ID, row.Holder.Name + created := false + var a *appAgent + b.locked(func() { + a = b.agents[id] + if a == nil { + a = b.agentLocked(id) + created = true + } + }) + a.gate.Lock() + defer a.gate.Unlock() + var refusal error + b.locked(func() { + if a.live != nil && a.liveRemote == nil { + refusal = appwire.Errorf(appwire.CodeConflict, "This chat is open on this computer.") + return + } + if a.liveRemote == nil { + r := &appLiveRemote{cell: row.Cell, hostID: hostID, hostName: hostName} + if a.transcript == "" { + // A FOLDER NO ONE WILL EVER FILL: every read of the disk this + // agent's record makes lands on nothing, never on the working + // directory an empty path would mean (session.DirOf("") is "."). + a.transcript = filepath.Join(b.relayHome(), "live-views", row.Cell, cell.TranscriptPath) + r.pure = true + } + a.liveRemote = r + b.liveViews.Add(1) + } else { + a.liveRemote.hostID, a.liveRemote.hostName = hostID, hostName + } + a.windowMoved = false + if a.view.Title == "" { + a.view.Title = row.Title + } + if a.view.UpdatedAt.IsZero() { + a.view.UpdatedAt = row.SavedAt + } + location := chatLocation(row) + if old := a.view.Location; old != nil && old.Live != nil { + location.Live = old.Live + } + a.view.Location = location + }) + if refusal != nil { + return appwire.Agent{}, refusal + } + view, opened, err := b.ensureLocked(a) + if err != nil { + if created { + b.locked(func() { + if a.live == nil && a.liveOnly() { + delete(b.agents, id) + b.liveViews.Add(-1) + } + }) + } + return appwire.Agent{}, err + } + b.locked(func() { a.viewOpen = true }) + if opened { + b.emit.Emit(appwire.EventAgentChanged, appwire.AgentChanged{Agent: view}) + } + b.dress(&view) + return view, nil +} + +// liveLocked runs f under liveMu, released from a defer even if f panics. +func (b *appBackend) liveLocked(f func()) { + b.liveMu.Lock() + defer b.liveMu.Unlock() + f() +} + +// liveHostOf answers the shared link to a host, making it on first use, and +// counts the caller as a user of it; liveHostDone gives that back. +func (b *appBackend) liveHostOf(hostID, hostName string) (*appLiveHost, error) { + var shared *appLiveHost + b.liveLocked(func() { + if h := b.liveHosts[hostID]; h != nil { + h.users++ + shared = h + } + }) + if shared != nil { + return shared, nil + } + h := &appLiveHost{id: hostID, name: hostName} + link, err := appLiveNewLink(b, hostID, hostName, func() bool { return b.liveActive(hostID) }, func(st livedoor.State) { b.liveStateMoved(hostID, st) }) + if err != nil { + return nil, err + } + h.link = link + link.OnChannelEnd(func(chat, reason string) { b.liveChannelEnded(hostID, chat, reason) }) + var other *appLiveHost + b.liveLocked(func() { + if other = b.liveHosts[hostID]; other != nil { + other.users++ + return + } + if b.liveHosts == nil { + b.liveHosts = map[string]*appLiveHost{} + } + h.users = 1 + b.liveHosts[hostID] = h + }) + if other != nil { + link.Close() + return other, nil + } + return h, nil +} + +// liveHostDone gives one use of the link back, and closes the link when none is +// left: nothing holds the relay's tunnel open for a view nobody uses. +func (b *appBackend) liveHostDone(h *appLiveHost) { + closing := false + b.liveLocked(func() { + h.users-- + closing = h.users <= 0 + if closing && b.liveHosts[h.id] == h { + delete(b.liveHosts, h.id) + } + }) + if closing { + h.link.Close() + } +} + +// closeLive closes every link when the app leaves. +func (b *appBackend) closeLive() { + var hosts map[string]*appLiveHost + b.liveLocked(func() { + hosts = b.liveHosts + b.liveHosts = nil + }) + for _, h := range hosts { + h.link.Close() + } +} + +// liveActive is the link's "is something happening" question: a turn running +// on a chat viewed through it. The link asks it holding its own lock, so it +// never waits for b.mu: a busy answer is the safe one, since it only keeps the +// connection a little longer. +func (b *appBackend) liveActive(hostID string) bool { + if !b.mu.TryLock() { + return true + } + defer b.mu.Unlock() + for _, a := range b.agents { + if r := a.liveRemote; r != nil && r.hostID == hostID && a.live != nil && (a.live.running || a.live.compacting || a.live.adopting > 0) { + return true + } + } + return false +} + +// NoteCall is the idle rule's other half: any agents.* call that names a live +// agent counts as the person touching it, so the link does not detach under +// them. The call itself reconnects through the usual open when it needs to. +func (b *appBackend) NoteCall(method string, params json.RawMessage) { + if b.liveViews.Load() == 0 { + return + } + var named struct { + ID string `json:"id"` + Agent string `json:"agent"` + } + if json.Unmarshal(params, &named) != nil { + return + } + id := named.ID + if id == "" { + id = named.Agent + } + if id == "" { + return + } + var hostID string + b.locked(func() { + if a := b.agents[id]; a != nil && a.liveRemote != nil && a.live != nil { + hostID = a.liveRemote.hostID + } + }) + if hostID == "" { + return + } + var h *appLiveHost + b.liveLocked(func() { h = b.liveHosts[hostID] }) + if h != nil { + guard.Go("app/live-touch", h.link.Touch) + } +} + +// ensureLive holds the live conversation for a: the connection another +// computer's chat is reached through, opened if none is held. Callers hold +// a.gate. +func (b *appBackend) ensureLive(a *appAgent, r *appLiveRemote) (appwire.Agent, bool, error) { + var view appwire.Agent + var held bool + b.locked(func() { view, held = a.view, a.live != nil }) + if held { + return view, false, nil + } + if b.isClosing() { + return appwire.Agent{}, false, appwire.Errorf(appwire.CodeClosed, "codeaf is shutting down") + } + if !config.RemoteControlOn() { + return appwire.Agent{}, false, appwire.Errorf(appwire.CodeConflict, "Remote control is off on this computer.") + } + b.locked(func() { + a.opening = true + if a.openDone == nil { + a.openDone = make(chan struct{}) + } + }) + conn, err := b.dialLive(a, r) + if err != nil { + return appwire.Agent{}, false, err + } + b.unmarkTidy(view.ID) + b.hold(a, conn, view.Workspace) + b.watchLiveDriver(a, conn) + return b.liveSay(a), true, nil +} + +// dialLive opens the connection: a roaming client over the host's link, so a +// dropped connection is redialled by the client for itself, and the same +// wrapping a join of a window's host gets. +func (b *appBackend) dialLive(a *appAgent, r *appLiveRemote) (*appConn, error) { + h, err := b.liveHostOf(r.hostID, r.hostName) + if err != nil { + return nil, appLiveRefusal(err, r.hostName) + } + hello := remote.Hello{Surface: devname.Name(b.relayHome()), Join: true} + client, err := appLiveRoam(r.hostName, hello, remote.Roaming{Dial: h.link.Opener(r.cell), MaxLine: livedoor.MaxLine, ResendUnanswered: true, SpreadReturns: true}) + if err != nil { + b.liveHostDone(h) + return nil, appLiveRefusal(err, r.hostName) + } + var once sync.Once + released := make(chan struct{}) + release := func() { + once.Do(func() { + close(released) + _ = client.Close() + b.liveHostDone(h) + b.liveDetached(r) + }) + } + conn := appConnOf(client, release, false) + // NOTHING OF THE HOST'S PATHS IS KEPT: its transcript and workspace are + // folders on another computer, and every disk read the app makes of an + // agent's own would otherwise be a read of a path that means something + // else here. + conn.Transcript, conn.Workspace, conn.Remote = "", "", true + conn.Gone = released + // THE ROAD'S STATE IS READ NOW: a link already open for another chat on this + // host says nothing new when this chat joins it. + road := h.link.State() + b.locked(func() { + r.driver = appLiveDriverOf(client.Driver()) + r.state, r.hasState = road, true + }) + return conn, nil +} + +func appLiveDriverOf(d remote.Driver) appwire.LiveDriver { + return appwire.LiveDriver{Yours: d.Yours, Machine: d.Machine, Here: d.Here} +} + +// watchLiveDriver says who has the keyboard whenever the host's answer moves. +func (b *appBackend) watchLiveDriver(a *appAgent, conn *appConn) { + agent, ok := conn.Conv.(*remote.Agent) + if !ok { + return + } + client := agent.Client() + guard.Go("app/live-driver", func() { + for { + changed := client.DriverChanged() + select { + case <-conn.Gone: + return + case <-changed: + } + b.locked(func() { + if r := a.liveRemote; r != nil { + r.driver = appLiveDriverOf(client.Driver()) + } + }) + b.emitLive(a) + } + }) +} + +// liveStateMoved is the link's word about a host reaching every live view on +// it. +func (b *appBackend) liveStateMoved(hostID string, st livedoor.State) { + var moved []*appAgent + b.locked(func() { + for _, a := range b.agents { + if r := a.liveRemote; r != nil && r.hostID == hostID { + r.state, r.hasState = st, true + moved = append(moved, a) + } + } + }) + for _, a := range moved { + b.emitLive(a) + if st.Kind == livedoor.Revoked { + b.sayLiveNotice(a, st.Reason) + } + } +} + +// liveChannelEnded is a view's channel closing. A quiet spell is the link's +// own detach: the connection is let go the way an idle conversation is, and the +// next call to the agent opens it again. Every other reason the client's own +// redial answers, or says. +func (b *appBackend) liveChannelEnded(hostID, chat, reason string) { + var a *appAgent + b.locked(func() { + for _, other := range b.agents { + if r := other.liveRemote; r != nil && r.hostID == hostID && r.cell == chat { + a = other + return + } + } + }) + if a == nil { + return + } + if reason == livedoor.ReasonIdle { + guard.Go("app/live-idle", func() { b.liveIdle(a) }) + return + } + switch reason { + case livedoor.ReasonHolderGone, livedoor.ReasonNotRunning, livedoor.ReasonNotAllowed, livedoor.ReasonRemoved, livedoor.ReasonHostClosing, livedoor.ReasonFrameTooLarge: + b.sayLiveNotice(a, reason) + } +} + +func (b *appBackend) liveIdle(a *appAgent) { + a.gate.Lock() + defer a.gate.Unlock() + running := false + b.locked(func() { running = a.live != nil && a.live.running }) + if running { + return + } + b.release(a) + // The window is still looking at it: letting go of the connection is not + // closing the view. + b.locked(func() { a.viewOpen = true }) +} + +// liveDetached is a connection let go. A view that was healthy reads idle from +// then on, which is the truth: nothing is held, and the next touch reconnects. +// A view whose road already said offline or revoked keeps saying that. +func (b *appBackend) liveDetached(r *appLiveRemote) { + var a *appAgent + b.locked(func() { + for _, other := range b.agents { + if other.liveRemote == r { + a = other + switch r.state.Kind { + case livedoor.Connecting, livedoor.Live, livedoor.WatchOnly, livedoor.StateBudget, livedoor.Idle: + r.state, r.hasState = livedoor.State{Kind: livedoor.Idle, Reason: livedoor.ReasonIdle, Since: time.Now(), Permit: r.state.Permit, Road: r.state.Road}, true + } + return + } + } + }) + if a != nil { + guard.Go("app/live-detached", func() { b.emitLive(a) }) + } +} + +func (b *appBackend) sayLiveNotice(a *appAgent, reason string) { + var host string + b.locked(func() { + if a.liveRemote != nil { + host = a.liveRemote.hostName + } + }) + line := chatlist.LiveSaid(reason, host) + b.sayLocalNotice(a, appwire.NoticeSync, "live:"+reason, line) +} + +// appLiveOf is the Location.live fact of a view, spelled as the desktop reads +// it: a closed set of states, who has the keyboard, and, for a view that may +// read but not type, the sentence that says why exactly as the host's words +// give it. +func appLiveOf(r *appLiveRemote) *appwire.LocationLive { + st := r.state + live := &appwire.LocationLive{Road: st.Road} + if !r.hasState { + live.State = appwire.LiveStateReconnecting + } else { + switch st.Kind { + case livedoor.Live: + live.State = appwire.LiveStateLive + case livedoor.WatchOnly, livedoor.StateBudget: + live.State = appwire.LiveStateWatching + words := chatlist.LiveWatchOnly(r.hostName) + switch { + case st.Kind == livedoor.StateBudget || st.Reason == livedoor.ReasonBudget: + words = chatlist.LiveBudget + case st.Reason == livedoor.ReasonPermitChanged: + words = chatlist.LiveSaid(livedoor.ReasonPermitChanged, r.hostName) + } + live.Permit = &appwire.LivePermit{Watch: true, Drive: false, Reason: words} + case livedoor.WentOffline, livedoor.Revoked: + live.State = appwire.LiveStateOffline + live.SeenAt = st.Since.UTC().Format(time.RFC3339) + case livedoor.Idle: + live.State = appwire.LiveStateIdle + default: + live.State = appwire.LiveStateReconnecting + } + } + if r.driver != (appwire.LiveDriver{}) { + d := r.driver + live.Driver = &d + } + return live +} + +// liveSay lays the view's live fact on its Location and answers the agent as it +// now stands, emitting nothing. +func (b *appBackend) liveSay(a *appAgent) (view appwire.Agent) { + b.locked(func() { view, _ = b.liveSayLocked(a) }) + return view +} + +func (b *appBackend) liveSayLocked(a *appAgent) (appwire.Agent, bool) { + r := a.liveRemote + if r == nil { + return a.view, false + } + live := appLiveOf(r) + location := a.view.Location + if location == nil { + location = &appwire.Location{Cell: r.cell} + } + if equalLive(location.Live, live) { + return a.view, false + } + next := *location + next.Live = live + a.view.Location = &next + return a.view, true +} + +func equalLive(x, y *appwire.LocationLive) bool { + if x == nil || y == nil { + return x == y + } + a, _ := json.Marshal(x) + c, _ := json.Marshal(y) + return string(a) == string(c) +} + +// emitLive says the view's agent when its live fact moved. +func (b *appBackend) emitLive(a *appAgent) { + var view appwire.Agent + changed := false + b.locked(func() { view, changed = b.liveSayLocked(a) }) + if changed { + b.emit.Emit(appwire.EventAgentChanged, appwire.AgentChanged{Agent: view}) + } +} + +// LiveKeyboard answers who has the keyboard of a live view and, when asked, +// takes it. The host's own words come back unchanged when it refuses. +func (b *appBackend) LiveKeyboard(p appwire.ChatLiveKeyboardParams) (appwire.ChatLiveKeyboardResult, error) { + a, err := b.find(p.Agent) + if err != nil { + return appwire.ChatLiveKeyboardResult{}, err + } + var r *appLiveRemote + b.locked(func() { r = a.liveRemote }) + if r == nil { + // NOT A VIEW OF ANOTHER COMPUTER'S CHAT: it may still be a chat THIS + // desktop holds for others, whose keyboard the desktop's own window can + // take back (app_held_keyboard.go). + return b.heldKeyboardCall(a, p) + } + if _, _, err := b.ensure(a); err != nil { + return appwire.ChatLiveKeyboardResult{}, err + } + live := b.liveOf(a) + if live == nil { + return appwire.ChatLiveKeyboardResult{}, appwire.Errorf(appwire.CodeUnreachable, "%s", chatlist.LiveSaid("", r.hostName)) + } + agent, ok := live.conn.Conv.(*remote.Agent) + if !ok { + return appwire.ChatLiveKeyboardResult{}, appwire.Errorf(appwire.CodeConflict, "this chat is not open live") + } + client := agent.Client() + if p.Take { + if err := client.Take(); err != nil { + return appwire.ChatLiveKeyboardResult{}, appwire.Errorf(appwire.CodeConflict, "%s", err.Error()) + } + } + driver := appLiveDriverOf(client.Driver()) + b.locked(func() { r.driver = driver }) + b.emitLive(a) + return appwire.ChatLiveKeyboardResult{Driver: driver}, nil +} + +// ── READING A LIVE CHAT'S HISTORY ─────────────────────────────────────────── + +// liveEntries serves agents.entries for a live view: the host's tail, read +// fresh, laid under the older part already read. Entry ids count the person's +// messages from the first, so the part of the past not held here is stood in +// for by placeholders that are never shown. +func (b *appBackend) liveEntries(a *appAgent, before string, limit int) (appwire.EntriesResult, error) { + if _, _, err := b.ensure(a); err != nil { + return appwire.EntriesResult{}, err + } + live := b.liveOf(a) + if live == nil { + return appwire.EntriesResult{}, appwire.Errorf(appwire.CodeUnreachable, "the chat is not connected right now; try again in a moment") + } + agent, ok := live.conn.Conv.(*remote.Agent) + if !ok { + return appwire.EntriesResult{}, appwire.Errorf(appwire.CodeConflict, "this chat is not open live") + } + var r *appLiveRemote + var id string + var at time.Time + var users int + marks := map[int]appTurnMark{} + b.locked(func() { + r, id, at, users = a.liveRemote, a.view.ID, a.view.UpdatedAt, a.users + for n, mark := range a.marks { + marks[n] = mark + } + }) + ctx, cancel := context.WithTimeout(context.Background(), chatPreviewWithin) + defer cancel() + tail, err := agent.TranscriptPage(ctx, 0, appLiveWindow) + if err != nil { + return appwire.EntriesResult{}, appLiveReadError(err, r.hostName) + } + r.win.mu.Lock() + defer r.win.mu.Unlock() + if tail.Total < r.win.total { + r.win.entries, r.win.base = nil, 0 + } + r.win.total = tail.Total + for range 16 { + record, held := r.win.record(tail, users) + page, more, err := appEntryPage(id, session.Record{Entries: record}, at, marks, before, limit, nil) + if err != nil { + return appwire.EntriesResult{}, appEntriesBusy(err) + } + touched := false + kept := page[:0] + for _, entry := range page { + if entry.Text == appLivePlaceholder { + touched = true + continue + } + kept = append(kept, entry) + } + if touched && held > 0 { + older, err := agent.TranscriptPage(ctx, held, appLiveWindow) + if err != nil { + return appwire.EntriesResult{}, appLiveReadError(err, r.hostName) + } + if len(older.Entries) == 0 { + return appwire.EntriesResult{Entries: kept}, nil + } + r.win.prepend(older) + continue + } + // Placeholders left over with nothing older to read are the messages a + // compaction took: there is nothing more to show. + return appwire.EntriesResult{Entries: kept, More: more && !(touched && held == 0)}, nil + } + return appwire.EntriesResult{}, appwire.Errorf(appwire.CodeBusy, "this chat's history is still being read; ask again in a moment") +} + +func appLiveReadError(err error, host string) error { + var wire *appwire.Error + if errors.As(err, &wire) { + return wire + } + return appwire.Errorf(appwire.CodeUnreachable, "%s", chatlist.LiveSaid("", host)) +} + +// record is the host's transcript as the app tells it: placeholders for the +// messages older than what is held, then the held entries, cut at the first +// message of the person's so every answer counts from its own message. held is +// the host's index of the first entry read, cut or not: an older page is read +// ending there. +func (w *appLiveWindowCache) record(tail remote.Page, users int) (entries []session.DisplayEntry, held int) { + read, base := tail.Entries, tail.Base + if n := len(w.entries); n > 0 && w.base+n == tail.Base { + read = append(append([]session.DisplayEntry(nil), w.entries...), tail.Entries...) + base = w.base + } + cut := 0 + for cut < len(read) && read[cut].Role != "user" { + cut++ + } + if cut == len(read) && base > 0 { + // No message of the person's in what is read: it is all the end of an + // answer whose message is older, and none of it can be told alone. + return placeholders(users), base + } + kept := read[cut:] + in := 0 + for _, entry := range kept { + if entry.Role == "user" { + in++ + } + } + return append(placeholders(users-in), kept...), base +} + +func placeholders(n int) []session.DisplayEntry { + if n <= 0 { + return nil + } + out := make([]session.DisplayEntry, n) + for i := range out { + out[i] = session.DisplayEntry{Role: "user", Text: appLivePlaceholder} + } + return out +} + +// prepend keeps an older page as the held past, joined to what was held. +func (w *appLiveWindowCache) prepend(older remote.Page) { + if n := len(w.entries); n > 0 && w.base == older.Base+len(older.Entries) { + w.entries = append(append([]session.DisplayEntry(nil), older.Entries...), w.entries...) + } else { + w.entries = append([]session.DisplayEntry(nil), older.Entries...) + } + w.base = older.Base +} + +// ── HEARING WHO HOLDS A CHAT, AND SWAPPING TO A VIEW OF THEM ──────────────── + +// liveSwapWanted says a window that was viewing a chat the desktop held, and +// had it taken by another computer, should now view the new holder instead of +// a stale copy (Superseded -> live). Callers hold no lock. +func (b *appBackend) liveSwapWanted(a *appAgent, r appwire.ChatRow) bool { + if !r.CanLive || r.Here { + return false + } + wanted := false + b.locked(func() { wanted = a.windowMoved && a.viewOpen && a.live == nil }) + return wanted && b.ChatsLiveOffered() +} + +func (b *appBackend) liveSwap(r appwire.ChatRow) { + guard.Go("app/live-swap", func() { + // A swap that fails leaves the window as the move left it: a copy that + // says who holds the chat, with Enter to ask again. + _, _ = b.OpenLive(appwire.ChatOpenLiveParams{Cell: r.Cell}) + }) +} diff --git a/cmd/codeaf/app_live_test.go b/cmd/codeaf/app_live_test.go new file mode 100644 index 0000000000..99666771ff --- /dev/null +++ b/cmd/codeaf/app_live_test.go @@ -0,0 +1,433 @@ +package main + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" +) + +// The rig of these tests is a host that is a real conversation behind a real +// remote session, reached through the same client a live view uses, with only +// the relay and its tunnel stood in for: the link's dialer is never run, and +// the roaming client is attached to the host in-process. What is asserted is +// therefore what the desktop sees, never how the engine got it. + +const liveRigHostName = "studio" +const liveRigHostID = "devicestudio0001" +const liveRigCell = "01JD6Z8K3M4N5P6Q7R8S9T0V1W" + +type liveRig struct { + t *testing.T + b *appBackend + rec *appRecorder + host *remote.Session + engine *session.Agent + provider *httptest.Server + asked atomic.Int32 + roams atomic.Int32 + hellos chan remote.Hello + links chan string + loops []*remote.Loop + file string + mu sync.Mutex +} + +func newLiveRig(t *testing.T, remoteControl bool) *liveRig { + t.Helper() + shortStateRoot(t) + t.Setenv("HOME", t.TempDir()) + t.Setenv(config.ProfileDirEnv, t.TempDir()) + t.Setenv(config.APIKeyEnv, "") + t.Setenv("CODEAF_SYNC_URL", "off") + if remoteControl { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + } else { + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + } + r := &liveRig{t: t, rec: newAppRecorder(), hellos: make(chan remote.Hello, 8), links: make(chan string, 8)} + r.provider = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + r.asked.Add(1) + _, _ = io.Copy(io.Discard, req.Body) + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "data: "+`{"choices":[{"index":0,"delta":{"role":"assistant","content":"live answer"},"finish_reason":"stop"}]}`+"\n\n") + fmt.Fprint(w, "data: [DONE]\n\n") + })) + t.Cleanup(r.provider.Close) + root := t.TempDir() + file := filepath.Join(root, "transcript.jsonl") + r.file = file + engine, err := session.New(session.Config{Workspace: root, SessionFile: file, Model: "test/model", APIKey: "fixture", + BaseURL: r.provider.URL, OneModel: true, DeterministicNames: true, PromptProfile: "full"}) + if err != nil { + t.Fatal(err) + } + r.engine = engine + r.host = remote.NewSession(&remote.Engine{Agent: engine, SessionFile: file, Workspace: root}, true) + t.Cleanup(func() { _ = r.host.Close() }) + // The host's chat already holds one exchange, so there is a past to read. + r.hostSays("first question") + + oldDial, oldLink, oldRoam := appLiveDialable, appLiveNewLink, appLiveRoam + t.Cleanup(func() { appLiveDialable, appLiveNewLink, appLiveRoam = oldDial, oldLink, oldRoam }) + appLiveDialable = func(*appBackend) bool { return true } + appLiveNewLink = func(_ *appBackend, hostID, hostName string, _ func() bool, _ func(livedoor.State)) (*livedoor.Link, error) { + r.links <- hostID + return livedoor.NewLink(livedoor.LinkConfig{ + Dial: func(context.Context) (io.ReadWriteCloser, error) { + return nil, errors.New("this rig's link is never dialled") + }, + Host: hostID, HostName: hostName, + }), nil + } + appLiveRoam = func(host string, hello remote.Hello, roam remote.Roaming) (*remote.Client, error) { + r.roams.Add(1) + r.hellos <- hello + if roam.Dial == nil || roam.MaxLine != livedoor.MaxLine { + t.Errorf("a live view must roam over the link's opener with the live line cap: %+v", roam) + } + // The host's live door names the conversation from the chat id the + // channel was opened for; the rig does what the door's resolver does. + hello.Session = r.file + loop, err := remote.LoopbackAttach(hello, remote.AttachOptions{Open: func(remote.Hello) (*remote.Session, error) { return r.host, nil }}) + if err != nil { + t.Logf("the rig's loopback attach failed: %v", err) + return nil, err + } + r.mu.Lock() + r.loops = append(r.loops, loop) + r.mu.Unlock() + return loop.Client, nil + } + r.b = newFakeBackend(r.rec, refuseAppOpen) + t.Cleanup(func() { _ = r.b.Close() }) + r.listRunning() + return r +} + +// hostSays runs one turn on the host's own conversation, as the host's person +// typing there would. +func (r *liveRig) hostSays(text string) { + r.t.Helper() + events, err := r.engine.Submit(context.Background(), text) + if err != nil { + r.t.Fatal(err) + } + for range events { + } +} + +// listRunning files the chat list's row for a chat the studio is running. +func (r *liveRig) listRunning() { + online := true + r.b.chats.cacheRows([]appwire.ChatRow{{ + Cell: liveRigCell, Title: "Studio chat", Status: string(chatlist.Running), Online: &online, + Holder: &appwire.LocationHolder{ID: liveRigHostID, Name: liveRigHostName}, + Seen: appwire.Seen{Device: liveRigHostID, Fence: 7}, CanTake: true, + }}, 1, false) +} + +func (r *liveRig) open() appwire.Agent { + r.t.Helper() + agent, err := r.b.OpenLive(appwire.ChatOpenLiveParams{Cell: liveRigCell}) + if err != nil { + r.t.Fatalf("OpenLive: %v", err) + } + return agent +} + +// stateEvents are the agent.changed events that carry a live fact, in order. +func (r *liveRig) liveEvents() []appwire.LocationLive { + r.rec.mu.Lock() + defer r.rec.mu.Unlock() + var out []appwire.LocationLive + for i, event := range r.rec.events { + if event != appwire.EventAgentChanged { + continue + } + if changed, ok := r.rec.data[i].(appwire.AgentChanged); ok && changed.Agent.Location != nil && changed.Agent.Location.Live != nil { + out = append(out, *changed.Agent.Location.Live) + } + } + return out +} + +// V1/V2 (a chat another computer is running opens on the desktop as an ordinary +// agent): chats.open_live answers an agent of the chat's own id whose location +// says it is held elsewhere and viewed live; its history is the host's, with +// the ids an app agent's entries always have; it is not listed as a chat of +// this computer; and the live fact moves with the link's word, in the closed +// spellings the desktop reads. +func TestAppOpenLiveServesARemoteChatAsALocalLookingAgent(t *testing.T) { + r := newLiveRig(t, true) + if !r.b.ChatsLiveOffered() { + t.Fatal("with remote control on and a door to dial, chats.live must be offered") + } + agent := r.open() + if agent.ID != liveRigCell { + t.Fatalf("the live agent's id = %q, want the chat's own %q", agent.ID, liveRigCell) + } + loc := agent.Location + if loc == nil || loc.Here || loc.Cell != liveRigCell || loc.Holder == nil || loc.Holder.Name != liveRigHostName || loc.Live == nil { + t.Fatalf("location = %+v, want held elsewhere by %s and viewed live", loc, liveRigHostName) + } + if got := <-r.links; got != liveRigHostID { + t.Fatalf("the link was made to %q, want the holder %q", got, liveRigHostID) + } + hello := <-r.hellos + if !hello.Join || hello.Surface == "" { + t.Fatalf("a live view joins the host's conversation and names this computer: %+v", hello) + } + + listed, err := r.b.ListAgents("") + if err != nil { + t.Fatal(err) + } + for _, other := range listed { + if other.ID == liveRigCell { + t.Fatalf("a chat with no folder here is not one of this computer's agents: %+v", other) + } + } + + page, err := r.b.EntriesWithFallback(agent.ID, "", 50) + if err != nil { + t.Fatalf("entries: %v", err) + } + var said []string + for _, entry := range page.Entries { + said = append(said, entry.ID+"/"+entry.Kind+":"+entry.Text) + if strings.Contains(entry.Text, appLivePlaceholder) { + t.Fatalf("a stand-in for an older message was shown: %+v", entry) + } + } + if len(page.Entries) < 2 || page.Entries[0].ID != "u0" || page.Entries[0].Text != "first question" || !strings.Contains(strings.Join(said, "|"), "live answer") { + t.Fatalf("the host's history did not arrive as an agent's entries: %v", said) + } + + // The link's word becomes agent.changed with the whole agent. + now := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) + for _, step := range []struct { + state livedoor.State + check func(appwire.LocationLive) bool + name string + }{ + {livedoor.State{Kind: livedoor.Live, Road: "relay"}, func(l appwire.LocationLive) bool { return l.State == "live" && l.Road == "relay" }, "live"}, + {livedoor.State{Kind: livedoor.Reconnecting}, func(l appwire.LocationLive) bool { return l.State == "reconnecting" }, "reconnecting"}, + {livedoor.State{Kind: livedoor.WentOffline, Since: now}, func(l appwire.LocationLive) bool { + return l.State == "offline" && l.SeenAt == "2026-11-23T12:00:00Z" + }, "offline"}, + {livedoor.State{Kind: livedoor.WatchOnly}, func(l appwire.LocationLive) bool { + return l.State == "watching" && l.Permit != nil && l.Permit.Watch && !l.Permit.Drive && l.Permit.Reason == chatlist.LiveWatchOnly(liveRigHostName) + }, "watching"}, + {livedoor.State{Kind: livedoor.StateBudget, Reason: livedoor.ReasonBudget}, func(l appwire.LocationLive) bool { + return l.State == "watching" && l.Permit != nil && l.Permit.Reason == chatlist.LiveBudget + }, "watching with the allowance used"}, + {livedoor.State{Kind: livedoor.Idle, Reason: livedoor.ReasonIdle}, func(l appwire.LocationLive) bool { return l.State == "idle" }, "idle"}, + } { + r.b.liveStateMoved(liveRigHostID, step.state) + events := r.liveEvents() + if len(events) == 0 || !step.check(events[len(events)-1]) { + t.Fatalf("after a %s link the last live fact was %+v", step.name, events) + } + } + + // A removed computer is offline here, and says why in the host's words. + r.b.liveStateMoved(liveRigHostID, livedoor.State{Kind: livedoor.Revoked, Reason: livedoor.ReasonRemoved, Since: now}) + r.rec.waitFor(t, 2*time.Second, func(event string, data any) bool { + added, ok := data.(appwire.EntryAdded) + return event == appwire.EventEntryAdded && ok && added.Entry.Text == chatlist.LiveRemoved + }) +} + +// V41 (the road of a live view reaches the desktop): a road flip the link +// reports is one agent.changed that carries the new road with the view still +// live, and the same word said again is no event at all. The desktop draws its +// strip from this field, so a flip it never hears of would leave the strip +// saying the wrong road until something else moved. +func TestARoadFlipReachesTheDesktopAsOneAgentChangedAndARepeatIsSilent(t *testing.T) { + r := newLiveRig(t, true) + r.open() + r.b.liveStateMoved(liveRigHostID, livedoor.State{Kind: livedoor.Live, Road: "relay"}) + settled := len(r.liveEvents()) + + r.b.liveStateMoved(liveRigHostID, livedoor.State{Kind: livedoor.Live, Road: "direct"}) + events := r.liveEvents() + if len(events) != settled+1 || events[len(events)-1].State != "live" || events[len(events)-1].Road != "direct" { + t.Fatalf("a flip to the direct road must be exactly one live fact that still says live: %+v", events[min(settled, len(events)):]) + } + r.b.liveStateMoved(liveRigHostID, livedoor.State{Kind: livedoor.Live, Road: "direct"}) + if n := len(r.liveEvents()); n != settled+1 { + t.Fatalf("the same road said twice emitted %d more events, want none", n-settled-1) + } + + r.b.liveStateMoved(liveRigHostID, livedoor.State{Kind: livedoor.Live, Road: "relay"}) + events = r.liveEvents() + if len(events) != settled+2 || events[len(events)-1].Road != "relay" { + t.Fatalf("a flip back to the relay must be one more live fact that says relay: %+v", events[min(settled, len(events)):]) + } +} + +// V2 (typing in a live view): a send to a live agent is agents.send, which +// reaches the host's running conversation and needs no stored copy anywhere: +// with no sync service the waiting-note door refuses, and the live send is not +// that door. +func TestALiveSendIsAnAgentsSendAndNeverAChatsSend(t *testing.T) { + r := newLiveRig(t, true) + agent := r.open() + // The rig has no sync service at all, so nothing can be stored anywhere. + if _, err := r.b.SendToChat(appwire.ChatSendParams{Cell: liveRigCell, Text: "a waiting note"}); err == nil { + t.Fatal("the waiting-note door must keep refusing while storage is off: the live send is not that door") + } + before := r.asked.Load() + if _, err := r.b.Send(agent.ID, "second question", "client-1"); err != nil { + t.Fatalf("agents.send on a live agent: %v", err) + } + r.rec.waitFor(t, 10*time.Second, appTurnDone) + if r.asked.Load() == before { + t.Fatal("the send never reached the host's conversation") + } + record := session.ReadTranscript(r.file) + var users []string + for _, entry := range appRecordItems(record) { + if entry.Role == "user" { + users = append(users, entry.Text) + } + } + if !slices.Equal(users, []string{"first question", "second question"}) { + t.Fatalf("the host's record holds %v: the live send must land as one message of its own conversation", users) + } + page, err := r.b.EntriesWithFallback(agent.ID, "", 50) + if err != nil { + t.Fatal(err) + } + ids := map[string]bool{} + for _, entry := range page.Entries { + ids[entry.ID] = true + } + if !ids["u0"] || !ids["u1"] { + t.Fatalf("the two messages must be u0 and u1, counted from the first: %v", ids) + } + // The entry the send announced is the one a later read finds under that id. + r.rec.waitFor(t, 2*time.Second, func(event string, data any) bool { + added, ok := data.(appwire.EntryAdded) + return event == appwire.EventEntryAdded && ok && added.Entry.Kind == "user" && added.Entry.Text == "second question" && added.Entry.ID == "u1" + }) + if notes := r.b.chats.notes.deliveredTo(liveRigCell, false); len(notes) != 0 { + t.Fatalf("a live send left a waiting note behind: %v", notes) + } +} + +// V13 (an engine without the feature is never sent a new call): with remote +// control off the desktop's hello names neither chats.live nor devices.permit, +// the two calls answer unknown_method if one is sent anyway, no row says it can +// be opened live, and no device row carries a permit. +func TestWithoutTheFeatureTheDeskNeverSeesTheNewCalls(t *testing.T) { + r := newLiveRig(t, false) + if r.b.ChatsLiveOffered() || r.b.DevicePermitsOffered() { + t.Fatal("with remote control off neither door may be offered") + } + if _, err := r.b.OpenLive(appwire.ChatOpenLiveParams{Cell: liveRigCell}); err == nil { + t.Fatal("chats.open_live must refuse while remote control is off") + } + if r.roams.Load() != 0 { + t.Fatal("a refused open must dial nothing") + } + + wire := newActionWire(t, r.b) + for _, feature := range wire.hello { + if feature == appwire.FeatureChatsLive || feature == appwire.FeatureDevicesPermit { + t.Fatalf("hello names %v with remote control off: %v", feature, wire.hello) + } + } + for method, params := range map[string]any{ + "chats.open_live": appwire.ChatOpenLiveParams{Cell: liveRigCell}, + "devices.permit": map[string]any{"id": "x", "watch": true}, + "chats.live_keyboard": appwire.ChatLiveKeyboardParams{Agent: liveRigCell, Take: true}, + } { + if _, err := wire.call(method, params); err == nil || err.Code != appwire.CodeUnknownMethod { + t.Fatalf("%s while the feature is off answered %v", method, err) + } + } + + // And its behaviour is the same as before for a chat that is not live: no + // row says it can be opened live, and an agent held elsewhere with no live + // view is still refused. + online := true + row := appwire.ChatRow{Cell: liveRigCell, Status: string(chatlist.Running), Online: &online} + if appCanLive(row, chatlist.Row{DeviceID: liveRigHostID}, true) { + t.Fatal("a row said it could be opened live with remote control off") + } + refusal := appLocationRefusal(&appwire.Location{Cell: liveRigCell, Line: "held by studio", Holder: &appwire.LocationHolder{ID: liveRigHostID, Name: liveRigHostName}}) + var held *appwire.Error + if !errors.As(refusal, &held) || held.Code != appwire.CodeConflict { + t.Fatalf("an agent held elsewhere without a live view must keep its refusal: %v", refusal) + } + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + if !appCanLive(row, chatlist.Row{DeviceID: liveRigHostID}, true) { + t.Fatal("with remote control on a running chat on an online computer can be opened live") + } +} + +// V12 (leaving the app): closing the backend closes every link, and the link of +// a host nothing views any more is closed at once, so a view nobody is using +// costs the relay nothing. +func TestAnIdleLiveViewHoldsNoLinkAndTheNextTouchReconnects(t *testing.T) { + r := newLiveRig(t, true) + agent := r.open() + <-r.links + a, err := r.b.find(agent.ID) + if err != nil { + t.Fatal(err) + } + r.b.liveChannelEnded(liveRigHostID, liveRigCell, livedoor.ReasonIdle) + deadline := time.Now().Add(5 * time.Second) + for r.b.liveOf(a) != nil { + if time.Now().After(deadline) { + t.Fatal("an idle detach never let go of the connection") + } + time.Sleep(5 * time.Millisecond) + } + r.b.liveMu.Lock() + hosts := len(r.b.liveHosts) + r.b.liveMu.Unlock() + if hosts != 0 { + t.Fatalf("%d links are still held with no view using them", hosts) + } + if last := r.liveEvents(); len(last) == 0 || last[len(last)-1].State != "idle" { + t.Fatalf("a view whose connection was let go reads idle, got %+v", last) + } + // The next agents.* call reconnects, through the usual open. + if _, err := r.b.Send(agent.ID, "back again", "client-2"); err != nil { + t.Fatalf("the send that follows an idle detach must reconnect: %v", err) + } + r.rec.waitFor(t, 10*time.Second, appTurnDone) + if r.roams.Load() != 2 { + t.Fatalf("the connection was opened %d times, want 2 (the open, then the reconnect)", r.roams.Load()) + } +} + +// V16 (a live view is the other computer's to set): its model, posture and +// budget are fenced, and a live agent leaves its client tools alone. +func TestALiveViewsDialsAreTheHostsToSet(t *testing.T) { + r := newLiveRig(t, true) + agent := r.open() + if _, err := r.b.SetModel(agent.ID, "other/model"); err == nil || !strings.Contains(err.Error(), "another computer") { + t.Fatalf("the model of a live view is set on its own computer, got %v", err) + } +} diff --git a/cmd/codeaf/app_notes.go b/cmd/codeaf/app_notes.go index 4ffda324bf..e128c710bb 100644 --- a/cmd/codeaf/app_notes.go +++ b/cmd/codeaf/app_notes.go @@ -27,14 +27,14 @@ import ( // appNoteWords are the sentences a refused message says, in the person's words. var appNoteWords = map[error]string{ - syncsetup.ErrNotesUnsupported: "This sync service can't carry a message to another computer yet. Bring the chat here to write to it.", + syncsetup.ErrNotesUnsupported: "This relay can't carry a message to another computer yet. Move the chat here to write to it.", syncsetup.ErrOutboxFull: appNoteSpelled(directory.MaxNotes) + " messages sent from this computer, in this chat or others, haven't been delivered yet. Send this one once some of them are.", syncsetup.ErrNoteEmpty: "The message is empty.", syncsetup.ErrNoteLong: "Messages to another computer are limited to 2000 characters.", syncsetup.ErrNoOwnRecord: "This computer isn't listed by sync yet. Try again in a moment.", // The verb is not offered while storage is off, so this answers only a // client that sent anyway or one connected before storage was switched off. - syncwords.ErrNotesWaitForStorage: "Sync storage is off for this account, so a message can't wait for another computer. Bring the chat here to write to it.", + syncwords.ErrNotesWaitForStorage: "Relay storage is off for this account, so a message can't wait for another computer. Move the chat here to write to it.", } // appNoteUnreachable is a message this computer could not leave because its diff --git a/cmd/codeaf/app_notes_live_e2e_test.go b/cmd/codeaf/app_notes_live_e2e_test.go index c3bc1b7059..a7faa3cfce 100644 --- a/cmd/codeaf/app_notes_live_e2e_test.go +++ b/cmd/codeaf/app_notes_live_e2e_test.go @@ -172,7 +172,7 @@ func TestLiveAMessageToAnotherComputerFollowsTheChat(t *testing.T) { return waiting && row.CanTake }) - // 3. Continue here: the waiting message runs on B, with B's model. + // 3. Move here: the waiting message runs on B, with B's model. taken := machineCall[appwire.TakeResult](t, b.w, "agents.take", appwire.TakeParams{Cell: row.Cell, Seen: row.Seen}).Agent if taken.Location == nil || !taken.Location.Here { t.Fatalf("taken: %+v", taken) diff --git a/cmd/codeaf/app_notes_test.go b/cmd/codeaf/app_notes_test.go index a019a80112..f08a739044 100644 --- a/cmd/codeaf/app_notes_test.go +++ b/cmd/codeaf/app_notes_test.go @@ -49,7 +49,7 @@ func TestAMessageSentToAChatElsewhereIsWaitingThenDeliveredOnItsRow(t *testing.T } _, rec, w := appDeviceBackend(t, deskDir) if !slices.Contains(w.hello, appwire.FeatureChatsSend) { - t.Fatal("hello does not offer chats.send where sync storage is not closed") + t.Fatal("hello does not offer chats.send where relay storage is not closed") } if _, err := w.call("chats.send", appwire.ChatSendParams{Cell: c.ID, Text: " "}); err == nil { t.Fatal("an empty message was sent") @@ -199,10 +199,10 @@ func TestAMessageToAChatElsewhereIsNotOfferedAndLeavesNothingWhileSyncStorageIsO backend, _, w := appDeviceBackend(t, deskDir) if slices.Contains(w.hello, appwire.FeatureChatsSend) { - t.Fatal("hello offers chats.send while sync storage is off") + t.Fatal("hello offers chats.send while relay storage is off") } _, refused := w.call("chats.send", appwire.ChatSendParams{Cell: c.ID, Text: "PLAINTEXT-NOTE-MARKER-77d2 while storage is off"}) - if refused == nil || refused.Message != appNoteWords[syncwords.ErrNotesWaitForStorage] || !strings.Contains(strings.ToLower(refused.Message), "sync storage") { + if refused == nil || refused.Message != appNoteWords[syncwords.ErrNotesWaitForStorage] || !strings.Contains(strings.ToLower(refused.Message), "relay storage") { t.Fatalf("a send while storage is off = %+v; want %q", refused, appNoteWords[syncwords.ErrNotesWaitForStorage]) } l, err := tower.Dir.List(t.Context()) @@ -228,7 +228,7 @@ func TestAMessageToAChatElsewhereIsNotOfferedAndLeavesNothingWhileSyncStorageIsO } _, _, again := appDeviceBackend(t, deskDir) if !slices.Contains(again.hello, appwire.FeatureChatsSend) { - t.Fatal("hello does not offer chats.send once sync storage is approved") + t.Fatal("hello does not offer chats.send once relay storage is approved") } sent := machineCall[appwire.ChatSendResult](t, again, "chats.send", appwire.ChatSendParams{Cell: c.ID, Text: "now that storage is on"}) if sent.Note.State != appwire.ChatNoteWaiting { diff --git a/cmd/codeaf/app_outage_test.go b/cmd/codeaf/app_outage_test.go index 3b7b55538a..570b32c335 100644 --- a/cmd/codeaf/app_outage_test.go +++ b/cmd/codeaf/app_outage_test.go @@ -367,7 +367,7 @@ func appRelayOutage(t *testing.T, competing bool) { var event appwire.AgentChanged _ = json.Unmarshal(f.Data, &event) l := event.Agent.Location - return event.Agent.ID == taken.ID && l != nil && !l.Here && l.Holder != nil && l.Holder.Name == "A" && strings.Contains(l.Line, "A continued this chat") + return event.Agent.ID == taken.ID && l != nil && !l.Here && l.Holder != nil && l.Holder.Name == "A" && strings.Contains(l.Line, "A moved this chat") }) outageWait(t, "O2 pending work kept on relay", func() bool { listing, err := appDeviceSync(t, dirA).Dir.List(t.Context()) @@ -439,7 +439,7 @@ func appRelayOutage(t *testing.T, competing bool) { t.Fatalf("O1 own chat became a viewer: %s", f.Data) } } - if f.Event == appwire.EventEntryAdded && strings.Contains(string(f.Data), "B continued this chat") { + if f.Event == appwire.EventEntryAdded && strings.Contains(string(f.Data), "B moved this chat") { t.Fatalf("O1 self displacement notice: %s", f.Data) } } diff --git a/cmd/codeaf/app_pair.go b/cmd/codeaf/app_pair.go index b24d75730e..847fd36fca 100644 --- a/cmd/codeaf/app_pair.go +++ b/cmd/codeaf/app_pair.go @@ -396,7 +396,7 @@ func (o *appPairOperation) perform(p appwire.PairStartParams) (error, bool) { asking, err := who.Look(o.ctx, ref) if errors.Is(err, pair.ErrLinkDecided) && approvedHere(who, ref.Code, "") == requestApprovedHere { // An approval whose reply was lost: the device is in, so this computer is shared. - if err := identity.EndSolo(dir); err != nil { + if err := pair.EndSoloAt(dir, pair.Permits()); err != nil { return err, false } record() @@ -408,7 +408,7 @@ func (o *appPairOperation) perform(p appwire.PairStartParams) (error, bool) { } label := pair.ComputerLabel(asking.Name, asking.Platform) o.line(appPairApproveTitle(label)) - answer := o.ask(o.ctx, "approve", appPairApproveTitle(label), appPairCheck(asking.Check), pairApprovalOptions()) + answer := o.ask(o.ctx, "approve", appPairApproveTitle(label), appPairCheck(label, asking.Check), pairApprovalOptions()) if answer != "y" { if o.ctx.Err() != nil { return o.ctx.Err(), false @@ -423,7 +423,7 @@ func (o *appPairOperation) perform(p appwire.PairStartParams) (error, bool) { return err, false } } - if err := identity.EndSolo(dir); err != nil { + if err := pair.EndSoloAt(dir, pair.Permits()); err != nil { return err, false } record() @@ -447,7 +447,7 @@ func (o *appPairOperation) Show(code *pair.Code, lines string) { func (o *appPairOperation) Burned() { o.line(appPairBurned) } func (o *appPairOperation) Ask(ctx context.Context, label, words string) bool { o.update(func(p *appwire.Pairing) { p.Words = words }) - return o.ask(ctx, "approve", appPairApproveTitle(label), appPairWords(words), pairApprovalOptions()) == "y" + return o.ask(ctx, "approve", appPairApproveTitle(label), appPairWords(label, words), pairApprovalOptions()) == "y" } func (o *appPairOperation) Waiting(words string) { o.update(func(p *appwire.Pairing) { diff --git a/cmd/codeaf/app_pair_copy.go b/cmd/codeaf/app_pair_copy.go index 96be8bcc58..2a2677936e 100644 --- a/cmd/codeaf/app_pair_copy.go +++ b/cmd/codeaf/app_pair_copy.go @@ -36,8 +36,8 @@ func appPairCodeLines(code string) []string { return []string{"Pairing shares your chats with another computer.", fmt.Sprintf("On your other computer, choose Pair a computer, then Enter a code from the other computer, and type %s (dashes optional). This code lasts %d minutes.", code, int(pair.CodeValidFor/time.Minute))} } func appPairApproveTitle(name string) string { return fmt.Sprintf("Pair with %s?", name) } -func appPairWords(words string) string { - return "Pair only if your other computer shows the same three words: " + words + "." +func appPairWords(label, words string) string { + return "Pair only if your other computer shows the same three words: " + words + ". " + pair.PairedControlLine(label) } func appPairWaiting(words string) string { return "Waiting for approval on your other computer. It should show: " + words + "." @@ -58,8 +58,8 @@ func appPairJoinedLine(j pair.Joined) string { func appPairInviteLines(check string, expires time.Duration) []string { return []string{"Open this pairing link on a computer you already use.", "Compare the check number on both computers: " + check + ".", fmt.Sprintf("Waiting for approval. This link lasts %d minutes.", int(expires/time.Minute))} } -func appPairCheck(check string) string { - return "Pair only if your other computer shows the same check number: " + check + "." +func appPairCheck(label, check string) string { + return "Pair only if your other computer shows the same check number: " + check + ". " + pair.PairedControlLine(label) } // appPairError is a failed pairing as the app shows it: one sentence, and the diff --git a/cmd/codeaf/app_remote_control_settings_test.go b/cmd/codeaf/app_remote_control_settings_test.go new file mode 100644 index 0000000000..e592e78116 --- /dev/null +++ b/cmd/codeaf/app_remote_control_settings_test.go @@ -0,0 +1,227 @@ +package main + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" +) + +// These tests are the desk's Remote control switch (contract R1–R8 in +// NOTES-POLISH): the row the terminal's Settings > Devices tab writes, reached +// through settings.get and settings.set, announced by one hello word, and +// taking effect as the contract says. They never set CODEAF_REMOTE_CONTROL to +// a value except where the environment's own pin is the thing under test, +// because a set variable would make the row read only and the switch +// untestable. + +// R1, R2, R3, R7: over the real wire, a fresh desk engine announces the switch, +// reads it off, turns it on and off through settings.set, and says +// settings.changed with the new value each time. A value that is not a plain +// true or false is refused and leaves the row alone. +func TestAppRemoteControlSwitchIsAnnouncedReadAndWrittenOverTheWire(t *testing.T) { + s := newLocalSetup(t) + t.Setenv("CODEAF_REMOTE_CONTROL", "") + s.backend.emit = s.server + profile := config.ProfileDir() + if !strings.Contains(s.hello, appwire.FeatureSettingsRemoteControl) { + t.Fatalf("the desk engine's hello omits %s: %s", appwire.FeatureSettingsRemoteControl, s.hello) + } + read := func(method string, params any, want bool) { + t.Helper() + var reply struct { + Settings struct { + RemoteControl *bool `json:"remote_control"` + PinnedBy string `json:"remote_control_pinned_by"` + } `json:"settings"` + } + s.must(method, params, &reply) + got := reply.Settings.RemoteControl + if got == nil || *got != want || reply.Settings.PinnedBy != "" { + t.Fatalf("%s says remote_control=%v pinned_by=%q, want %v and no pin", method, got, reply.Settings.PinnedBy, want) + } + } + read("settings.get", struct{}{}, false) + if config.RemoteControlAt(profile) { + t.Fatal("a fresh home has remote control on") + } + read("settings.set", map[string]any{"remote_control": true}, true) + if !config.RemoteControlAt(profile) || settingsRow(profile, config.KeyRemoteControl) != "on" { + t.Fatalf("turning it on wrote %q, and the engine reads %v", settingsRow(profile, config.KeyRemoteControl), config.RemoteControlAt(profile)) + } + read("settings.get", struct{}{}, true) + // A patch that names other fields leaves the switch where it was. + read("settings.set", map[string]any{"dock_badge": false}, true) + read("settings.set", map[string]any{"remote_control": false}, false) + if config.RemoteControlAt(profile) { + t.Fatal("turning it off left it on") + } + for _, bad := range []any{nil, "on", 1} { + s.mustFail("settings.set", map[string]any{"remote_control": bad}, appwire.CodeBadParams) + } + if config.RemoteControlAt(profile) { + t.Fatal("a refused write changed the row") + } + s.mu.Lock() + defer s.mu.Unlock() + var told []string + for _, line := range s.lines { + if strings.Contains(line, "settings.changed") { + told = append(told, line) + } + } + if len(told) < 2 || !strings.Contains(told[0], `"remote_control":true`) || !strings.Contains(strings.Join(told, "\n"), `"remote_control":false`) { + t.Fatalf("settings.changed did not carry the switch both ways: %v", told) + } +} + +// R4: when the environment fixes the value, the row says so by name, the write +// is refused in the engine's own sentence, and it is refused WHOLE: a patch that +// also names a field that would otherwise land changes nothing. +func TestAppRemoteControlSwitchPinnedByTheEnvironmentRefusesTheWholePatch(t *testing.T) { + backend := settingsBackend(t) + profile := config.ProfileDir() + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + got, err := backend.Settings() + if err != nil { + t.Fatal(err) + } + if got.RemoteControl == nil || !*got.RemoteControl || got.RemoteControlPinnedBy != "CODEAF_REMOTE_CONTROL" { + t.Fatalf("a pinned row reads remote_control=%v pinned_by=%q", got.RemoteControl, got.RemoteControlPinnedBy) + } + off, deny := false, "deny" + before := config.ToolApprovalModeAt(profile) + _, err = backend.SetSettings(appwire.SettingsPatch{RemoteControl: &off, AsksBefore: &deny}) + if err == nil || !strings.Contains(err.Error(), "Remote control is set by CODEAF_REMOTE_CONTROL") { + t.Fatalf("writing a pinned row answered %v", err) + } + var wireErr *appwire.Error + if !errors.As(err, &wireErr) || wireErr.Code != appwire.CodeBadParams { + t.Fatalf("the refusal is %v, want a bad_params error", err) + } + if config.ToolApprovalModeAt(profile) != before { + t.Fatal("a refused patch still changed another field") + } + if _, saved := persistedRemoteControl(profile); saved { + t.Fatal("a refused write was persisted behind the pin") + } + // With the pin gone the same write goes through. + t.Setenv("CODEAF_REMOTE_CONTROL", "") + got, err = backend.SetSettings(appwire.SettingsPatch{RemoteControl: &off}) + if err != nil || got.RemoteControl == nil || *got.RemoteControl || got.RemoteControlPinnedBy != "" { + t.Fatalf("after the pin went: %+v, %v", got, err) + } +} + +// persistedRemoteControl reads only the saved row, which the environment does +// not touch. +func persistedRemoteControl(profile string) (bool, bool) { + raw, err := os.ReadFile(config.BudgetConfigPath(profile)) + if err != nil { + return false, false + } + var fields map[string]json.RawMessage + if json.Unmarshal(raw, &fields) != nil { + return false, false + } + value, ok := fields[config.KeyRemoteControl] + if !ok { + return false, false + } + var on bool + _ = json.Unmarshal(value, &on) + return on, true +} + +// R5, R6: turning it ON starts nothing by itself and leaves the chats already +// open as they were; the NEXT chat the desktop opens is offered. Turning it OFF +// stops handing chats out at once and ends what another computer has open on +// them, which that computer reads as the chat closing, while the desktop's own +// chat goes on and keeps what was said. +func TestAppRemoteControlSwitchOnOffMovesTheDoorAsTheContractSays(t *testing.T) { + r := newDeskHeldRig(t, false) + // The rig fixes the variable; the switch under test must be free to move. + t.Setenv("CODEAF_REMOTE_CONTROL", "") + backend := newFakeBackend(newAppRecorder(), nil) + t.Cleanup(func() { backend.Close() }) + + // A chat opened with the switch off is an ordinary chat. + first := r.open() + t.Cleanup(first.Release) + if _, found := r.registry(); found { + t.Fatal("remote control is off, and the desktop opened a door") + } + on, off := true, false + if _, err := backend.SetSettings(appwire.SettingsPatch{RemoteControl: &on}); err != nil { + t.Fatal(err) + } + if _, found := r.registry(); found { + t.Fatal("turning the switch on started a door with no chat to offer") + } + if _, ok := deskHost.lookup(r.file); ok { + t.Fatal("a chat opened before the switch was turned on was offered afterwards") + } + + // The next chat opened is offered, and another computer joins it. + file2 := filepath.Join(r.root, "second.jsonl") + engine2, err := session.New(session.Config{Workspace: r.root, SessionFile: file2, Model: "test/model", APIKey: "fixture", + BaseURL: r.provider.URL, OneModel: true, DeterministicNames: true, PromptProfile: "full"}) + if err != nil { + t.Fatal(err) + } + second, err := appOpenAssembled(remote.Hello{Workspace: r.root, Session: file2}, func(remote.Hello) (*remote.Engine, error) { + return &remote.Engine{Agent: engine2, SessionFile: file2, Workspace: r.root}, nil + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(second.Release) + socket, found := r.registry() + if !found { + t.Fatal("the next chat opened after turning the switch on has no door") + } + // The rig joins the chat it was built for, so point it at this one for the + // join and back again. It holds an atomic counter, so it is never copied. + opened := r.file + r.file = file2 + viewer, err := r.viewer(socket) + r.file = opened + if err != nil { + t.Fatalf("another computer could not open the chat opened after the switch: %v", err) + } + if deskHost.viewers(file2) != 1 { + t.Fatalf("the door counts %d viewers, want 1", deskHost.viewers(file2)) + } + + // Off: the door stops handing out at once and the viewer is told. + if _, err := backend.SetSettings(appwire.SettingsPatch{RemoteControl: &off}); err != nil { + t.Fatal(err) + } + if _, ok := deskHost.lookup(file2); ok { + t.Fatal("the switch is off and the door still hands the chat out") + } + deadline := time.Now().Add(10 * time.Second) + for viewer.Err() == nil && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + if viewer.Err() == nil { + t.Fatal("turning the switch off left another computer's view of the chat open") + } + if deskHost.viewers(file2) != 0 { + t.Fatalf("the door still counts %d viewers after the switch went off", deskHost.viewers(file2)) + } + if engine2.Closed() { + t.Fatal("turning the switch off closed the desktop's own chat") + } + if told := r.say(second, "still here"); len(told) == 0 { + t.Fatal("the desktop's own chat stopped answering when the switch went off") + } +} diff --git a/cmd/codeaf/app_take.go b/cmd/codeaf/app_take.go index 8d948339b2..b7dd828ea1 100644 --- a/cmd/codeaf/app_take.go +++ b/cmd/codeaf/app_take.go @@ -179,7 +179,7 @@ func (b *appBackend) takeAgent(p appwire.TakeParams, available bool) (agent appw busy = existing.opening || existing.starting || existing.live != nil && (existing.live.running || existing.live.needsYou()) }) if busy { - return appwire.Errorf(appwire.CodeBusy, "Finish this chat's work before continuing it here.") + return appwire.Errorf(appwire.CodeBusy, "Finish this chat's work before moving it here.") } if available || moved { b.release(existing) diff --git a/cmd/codeaf/appapproval.go b/cmd/codeaf/appapproval.go index 1c5aa0a1d0..0e70ce974d 100644 --- a/cmd/codeaf/appapproval.go +++ b/cmd/codeaf/appapproval.go @@ -141,8 +141,8 @@ func (b *appBackend) SetApprovalPosture(id, posture string) (appwire.Agent, erro live, transcript = a.live, a.transcript live.lastUse = b.now() }) - if live.conn.Lent { - return appwire.Agent{}, errLentStage("approval posture") + if live.conn.Lent || live.conn.Remote { + return appwire.Agent{}, appFenceError(live.conn, "approval posture") } door, ok := live.conn.Conv.(appPostureDoor) if !ok { diff --git a/cmd/codeaf/appclienttools_remote.go b/cmd/codeaf/appclienttools_remote.go index da45257ccd..bf0e7bd57f 100644 --- a/cmd/codeaf/appclienttools_remote.go +++ b/cmd/codeaf/appclienttools_remote.go @@ -24,7 +24,7 @@ func (b *appBackend) clientToolRemoteAgent(a *appAgent) *remote.Agent { if a.view.Location != nil && !a.view.Location.Here { return } - if a.live != nil && !a.live.conn.Assembled && !a.live.conn.Lent { + if a.live != nil && !a.live.conn.Assembled && !a.live.conn.Lent && !a.live.conn.Remote { agent, _ = a.live.conn.Conv.(*remote.Agent) } }) @@ -138,7 +138,9 @@ func (b *appBackend) callRemoteClientTool(ctx context.Context, door *appClientTo } func (b *appBackend) holdClientTools(a *appAgent, live *appLive) { - if live.conn.Assembled || live.conn.Lent { + // A live view of another computer's chat never gives that computer's chat + // this computer's client tools: the holder would run them for the guest. + if live.conn.Assembled || live.conn.Lent || live.conn.Remote { return } agent, ok := live.conn.Conv.(*remote.Agent) diff --git a/cmd/codeaf/appclose.go b/cmd/codeaf/appclose.go index f3b5593805..76de98dbcf 100644 --- a/cmd/codeaf/appclose.go +++ b/cmd/codeaf/appclose.go @@ -307,7 +307,8 @@ func (b *appBackend) refreshElsewhereWith(a *appAgent, watch bool) { b.locked(func() { // AN AGENT THIS PROCESS IS OPENING IS ITS OWN WORD: the disk has not // heard of its turn yet, and reading it there said idle mid-start. - if a.live == nil && a.transcript != "" && !a.opening && !a.starting { + // A LIVE VIEW HAS NO FOLDER HERE: its state is the live link's. + if a.live == nil && a.transcript != "" && !a.opening && !a.starting && a.liveRemote == nil { dir = session.DirOf(a.transcript) } }) diff --git a/cmd/codeaf/appdevices.go b/cmd/codeaf/appdevices.go index a784f29a3a..0ce9c1f9b7 100644 --- a/cmd/codeaf/appdevices.go +++ b/cmd/codeaf/appdevices.go @@ -5,6 +5,7 @@ import ( "context" "encoding/json" "errors" + "fmt" "runtime" "slices" "sync" @@ -13,12 +14,14 @@ import ( "github.com/Agent-Field/codeaf/internal/appwire" "github.com/Agent-Field/codeaf/internal/cell" "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/config" "github.com/Agent-Field/codeaf/internal/devname" "github.com/Agent-Field/codeaf/internal/directory" "github.com/Agent-Field/codeaf/internal/dirwatch" "github.com/Agent-Field/codeaf/internal/guard" "github.com/Agent-Field/codeaf/internal/home" "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/livedoor" "github.com/Agent-Field/codeaf/internal/pair" "github.com/Agent-Field/codeaf/internal/syncsetup" "github.com/Agent-Field/codeaf/internal/wireauth" @@ -166,6 +169,18 @@ func (d *appDevices) snapshotState() (appwire.Devices, bool, error) { } view.Devices = append(view.Devices, row) } + // WHAT EACH COMPUTER MAY DO IN THIS ONE'S CHATS is read from this computer's + // own permit book, and said only while remote control is on: with it off the + // rows are as they always were (devices.permit, app_live_open.go). + if view.Mode == appwire.DevicesOn && config.RemoteControlOn() { + book := pair.Permits() + for i := range view.Devices { + if row := view.Devices[i]; !row.Self && !row.Removed { + p, _ := book.For(id.ID(), row.ID) + view.Devices[i].Permit = &appwire.DevicePermit{Watch: p.Watch, Drive: p.Drive} + } + } + } selfAt := slices.IndexFunc(view.Devices, func(row appwire.Device) bool { return row.Self }) if selfAt < 0 { view.Devices = append(view.Devices, appwire.Device{ID: self.ID(), Self: true}) @@ -234,6 +249,56 @@ func (b *appBackend) RenameDevice(typed string) (appwire.DeviceRenameResult, err return appwire.DeviceRenameResult{Device: view.Devices[0], Line: line}, nil } +var ( + _ appwire.DevicePermitter = (*appBackend)(nil) + _ appwire.DevicePermitOffer = (*appBackend)(nil) +) + +// DevicePermitsOffered says the desktop may be told about devices.permit: the +// switches only mean something while remote control is on. +func (*appBackend) DevicePermitsOffered() bool { return config.RemoteControlOn() } + +// PermitDevice sets what a paired computer may do in THIS computer's chats. It +// edits this computer's own permit book and nothing else: the book never leaves +// the machine, so it asks the relay for no write and no other computer for its +// word. Only the switches named change; the host's own watcher closes the open +// views the change affects. +func (b *appBackend) PermitDevice(p appwire.DevicePermitParams) (appwire.DevicePermitResult, error) { + d := b.devices + d.op.Lock() + defer d.op.Unlock() + view, err := d.snapshot() + if err != nil { + return appwire.DevicePermitResult{}, err + } + at := slices.IndexFunc(view.Devices, func(row appwire.Device) bool { return row.ID == p.ID }) + switch { + case at < 0 || view.Mode != appwire.DevicesOn: + return appwire.DevicePermitResult{}, appwire.Errorf(appwire.CodeNotFound, "%s", chatlist.DeviceMissing) + case view.Devices[at].Self: + return appwire.DevicePermitResult{}, appwire.Errorf(appwire.CodeBadParams, "this computer is always allowed in its own chats") + case view.Devices[at].Removed: + return appwire.DevicePermitResult{}, appwire.Errorf(appwire.CodeNotFound, "%s", chatlist.DeviceMissing) + } + id, err := identity.Load(d.home) + if err != nil || id.ID() == "" { + return appwire.DevicePermitResult{}, appwire.Errorf(appwire.CodeEngine, "this computer has no identity yet") + } + book := pair.Permits() + if err := book.Set(id.ID(), p.ID, p.Watch, p.Drive, "person"); err != nil { + return appwire.DevicePermitResult{}, appEngineError(err) + } + view, err = d.snapshot() + if err != nil { + return appwire.DevicePermitResult{}, err + } + d.publish(b.emit) + row := view.Devices[slices.IndexFunc(view.Devices, func(r appwire.Device) bool { return r.ID == p.ID })] + got, class := book.For(id.ID(), p.ID) + line := fmt.Sprintf("%s: watch %s, type %s (%s)", row.Name, permitWord(got.Watch), permitWord(got.Drive), permitClassWord(class)) + return appwire.DevicePermitResult{Device: &row, Line: line}, nil +} + func (b *appBackend) RemoveDevice(deviceID string) (appwire.DeviceRemoveResult, error) { d := b.devices d.op.Lock() @@ -274,6 +339,9 @@ func (b *appBackend) RemoveDevice(deviceID string) (appwire.DeviceRemoveResult, if err := s.Dir.Revoke(ctx, deviceID); err != nil { return appwire.DeviceRemoveResult{}, deviceError(err) } + livedoor.NotifyRemoved(home.Dir(), deviceID) + _ = pair.Permits().Forget(deviceID) + forgetViewed(home.Dir(), deviceID) line = pair.ChatsRevokedLine(name) } // Success is retained even if a later user-requested refresh cannot reach diff --git a/cmd/codeaf/applazy.go b/cmd/codeaf/applazy.go index 62c4427d1c..11539c587b 100644 --- a/cmd/codeaf/applazy.go +++ b/cmd/codeaf/applazy.go @@ -182,7 +182,7 @@ func (b *appBackend) lazyCandidates(run *appCrewRun, read appCrewRead, first boo if !a.lastLive.IsZero() && !now.After(a.lastLive.Add(appLazyHotWindow)) { hot[id] = true } - if a.live != nil || a.transcript == "" || recovering[id] { + if a.live != nil || a.transcript == "" || a.liveOnly() || recovering[id] { continue } if a.listening.IsZero() { diff --git a/cmd/codeaf/appquit.go b/cmd/codeaf/appquit.go index d82c6d46ae..c70b1c19c2 100644 --- a/cmd/codeaf/appquit.go +++ b/cmd/codeaf/appquit.go @@ -44,6 +44,21 @@ func (b *appBackend) markQuit(agents []*appAgent) { var stopped []appwire.Process now := b.now() for _, a := range agents { + // A PURE LIVE VIEW IS NOT THIS APP'S TO STOP OR RESUME. The chat runs on + // another paired computer and this window only watches or drives it, so + // quitting here stops nothing over there: writing its reply down for a + // carry-on, or its processes as "stopped by quit", would say something + // false, and the Interrupted mark that follows would name an agent id + // that does not exist after a restart (app_live_open.go). Today the + // Assembled check below would skip a view anyway, because dialLive + // builds its connection unassembled; that is a side effect of how the + // connection is made and not a statement about views, so the exclusion + // is made here on what the agent is. + pure := false + b.locked(func() { pure = a.liveOnly() }) + if pure { + continue + } live := b.liveOf(a) if live == nil || !live.conn.Assembled { continue diff --git a/cmd/codeaf/appquit_live_test.go b/cmd/codeaf/appquit_live_test.go new file mode 100644 index 0000000000..658ad71ec9 --- /dev/null +++ b/cmd/codeaf/appquit_live_test.go @@ -0,0 +1,228 @@ +package main + +import ( + "reflect" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/session" +) + +// The contract of these tests is what a quit writes down for the next start +// (appquit.go): the replies in the middle of their work to carry on, and the +// processes that were running as "stopped by quit". A chat THIS desktop runs is +// written down; a pure live view of a chat another computer runs is not, +// because quitting here stops nothing over there and its id means nothing +// after a restart. The state file is read back, never the backend's memory, so +// what is asserted is what a later start would find. + +// quitJobsConversation is a conversation with one process running in it, as a +// quit finds a chat whose reply started something. Embedding the interface and +// not a concrete type keeps the process pager out of its method set, so the +// quit reads the jobs from JobNotices. +type quitJobsConversation struct { + appConversation + jobs []session.JobNotice +} + +func (c *quitJobsConversation) JobNotices() ([]session.JobNotice, error) { return c.jobs, nil } + +// quitJob is a process the model started and left running. +func quitJob() session.JobNotice { + return session.JobNotice{ID: 3, Command: "sleep 600", State: session.JobRunning, Kind: session.JobKindCommand, Started: time.Date(2026, 11, 24, 9, 0, 0, 0, time.UTC)} +} + +// quitMidReply puts a's conversation where a quit finds a reply: still +// running, with a process alive in it. The running flag is the one the turn's +// stream sets while a reply is being written. +func quitMidReply(b *appBackend, a *appAgent) { + b.locked(func() { + a.live.running = true + a.live.conn.Conv = &quitJobsConversation{appConversation: a.live.conn.Conv, jobs: []session.JobNotice{quitJob()}} + }) +} + +// quitLocalChat registers a chat this process built itself, in the middle of a +// reply with a process running. +func quitLocalChat(t *testing.T, b *appBackend, id string) *appAgent { + t.Helper() + a := b.agent(id) + b.locked(func() { + a.live = &appLive{box: appwire.NewOutbox(b.emit), conn: &appConn{Conv: &fakeConversation{}, Assembled: true, Release: func() {}}} + }) + quitMidReply(b, a) + return a +} + +// quitState reads back what a quit left in the app's state file. +func quitState(t *testing.T, b *appBackend) (f appStateFile) { + t.Helper() + if err := b.state.read(func(s *appStateFile) { f = *s }); err != nil { + t.Fatal(err) + } + return f +} + +// wantNothingFor fails when the state file carries anything a later start +// would act on for id: a resume, a reply, a stopped process or an Interrupted +// mark. The mark is what interruptAfterQuit writes at the next start from the +// resume list, so it is read after that has run. +func wantNothingFor(t *testing.T, b *appBackend, id string) { + t.Helper() + f := quitState(t, b) + for _, got := range [][]string{f.ResumeAfterQuit, f.QuitReplies, f.QuitTasks} { + for _, name := range got { + if name == id { + t.Errorf("the quit wrote %q down to resume: resumes %v, replies %v, tasks %v", id, f.ResumeAfterQuit, f.QuitReplies, f.QuitTasks) + } + } + } + for _, p := range f.QuitStopped { + if p.Agent == id { + t.Errorf("the quit wrote a process of %q down as %q: %+v", id, appQuitStoppedWord, p) + } + } + b.interruptAfterQuit() + if _, marked := quitState(t, b).Interrupted[id]; marked { + t.Errorf("a restart would hold an Interrupted mark for %q, an agent that will not exist", id) + } +} + +// Q1 (a quit with a pure live view open records nothing for it): the chat +// runs on another computer, a reply is in progress there and a process runs +// there. Quitting this desktop stops neither, so no resume, no "stopped by +// quit" process and, after a restart, no Interrupted mark for the view's id. +func TestQuitGuardQ1APureLiveViewIsNeverRecordedAtQuit(t *testing.T) { + for _, tc := range []struct { + name string + assembled bool + }{ + // The view's connection is built over the live door and is not marked + // as built here (dialLive). + {"as a live view is opened", false}, + // The guard must not rest on that mark alone: a desk-held chat is + // marked built here and is recorded, so a view that ever carried the + // mark must still be left out for being a view. + {"even with its connection marked as built here", true}, + } { + t.Run(tc.name, func(t *testing.T) { + r := newLiveRig(t, true) + r.open() + a := r.b.agent(liveRigCell) + var pure bool + r.b.locked(func() { pure = a.liveOnly() }) + if !pure { + t.Fatal("the rig's view has a folder here, so it is not the pure view this contract is about") + } + if tc.assembled { + r.b.locked(func() { a.live.conn.Assembled = true }) + } else if built := r.b.liveOf(a).conn.Assembled; built { + t.Fatal("a live view's connection is built over the live door, never marked as built here") + } + quitMidReply(r.b, a) + r.b.markQuit([]*appAgent{a}) + wantNothingFor(t, r.b, liveRigCell) + }) + } +} + +// Q1 and Q2 together: a quit that walks a live view and a chat of this +// desktop's in the same pass records the chat and leaves the view out, and the +// view's running process does not borrow the chat's turn or the chat's the view's. +func TestQuitGuardQ1TheLocalChatBesideAPureLiveViewIsStillRecorded(t *testing.T) { + r := newLiveRig(t, true) + r.open() + view := r.b.agent(liveRigCell) + r.b.locked(func() { view.live.conn.Assembled = true }) + quitMidReply(r.b, view) + local := quitLocalChat(t, r.b, "local-chat") + // The view comes first, so a guard that stopped the whole walk would show. + r.b.markQuit([]*appAgent{view, local}) + f := quitState(t, r.b) + if !reflect.DeepEqual(f.ResumeAfterQuit, []string{"local-chat"}) || !reflect.DeepEqual(f.QuitReplies, []string{"local-chat"}) { + t.Fatalf("resumes %v, replies %v, want only the desktop's own chat", f.ResumeAfterQuit, f.QuitReplies) + } + if len(f.QuitStopped) != 1 || f.QuitStopped[0].Agent != "local-chat" { + t.Fatalf("stopped processes %+v, want the desktop's own chat's one", f.QuitStopped) + } + wantNothingFor(t, r.b, liveRigCell) +} + +// wantRecorded fails unless a quit wrote id down exactly as it always has: a +// reply to carry on and the running process listed as stopped by quit. +func wantRecorded(t *testing.T, b *appBackend, id string) { + t.Helper() + f := quitState(t, b) + if !reflect.DeepEqual(f.ResumeAfterQuit, []string{id}) || !reflect.DeepEqual(f.QuitReplies, []string{id}) { + t.Errorf("resumes %v, replies %v, want %q alone in both", f.ResumeAfterQuit, f.QuitReplies, id) + } + if len(f.QuitStopped) != 1 { + t.Fatalf("stopped processes %+v, want the one that was running", f.QuitStopped) + } + p := f.QuitStopped[0] + if p.Agent != id || p.State != appwire.ProcessStopped || p.Reason != appQuitStoppedWord || p.EndedAt == nil { + t.Errorf("the stopped process = %+v, want %q's, stopped with the reason %q", p, id, appQuitStoppedWord) + } +} + +// Q2 (a chat this desktop runs is recorded as before): in the middle of a +// reply with a process running, it is carried on after the restart and its +// process is listed as stopped by quit. +func TestQuitGuardQ2AChatThisDesktopRunsIsRecordedAtQuit(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + b := newFakeBackend(newAppRecorder(), nil) + t.Cleanup(func() { _ = b.Close() }) + a := quitLocalChat(t, b, "local-chat") + b.markQuit([]*appAgent{a}) + wantRecorded(t, b, "local-chat") +} + +// Q2, the desk-held host: a chat this desktop runs and another computer is +// watching through the holder door is the desktop's own, not a live view, so a +// quit records it as it records any other. +func TestQuitGuardQ2ADeskHeldChatAnotherComputerViewsIsStillRecorded(t *testing.T) { + r := newDeskHeldRig(t, true) + conn := r.open() + t.Cleanup(conn.Release) + socket, found := r.registry() + if !found { + t.Fatal("a chat the desktop opened with remote control on has no holder door") + } + if _, err := r.viewer(socket); err != nil { + t.Fatalf("another computer could not join the chat through the door: %v", err) + } + if got := deskHost.viewers(r.file); got != 1 { + t.Fatalf("one other computer is watching, the door says %d", got) + } + b := newFakeBackend(newAppRecorder(), nil) + t.Cleanup(func() { _ = b.Close() }) + a := b.agent("desk-chat") + b.locked(func() { a.live = &appLive{box: appwire.NewOutbox(b.emit), conn: conn} }) + quitMidReply(b, a) + var pure bool + b.locked(func() { pure = a.liveOnly() }) + if pure { + t.Fatal("a chat the desktop runs is not a pure live view") + } + b.markQuit([]*appAgent{a}) + wantRecorded(t, b, "desk-chat") +} + +// Q3 (remote control off changes nothing): there is no live door to open a +// view over, so every chat is this desktop's own and is recorded as before. +func TestQuitGuardQ3WithRemoteControlOffAQuitRecordsAsBefore(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + if config.RemoteControlOn() { + t.Fatal("remote control must be off for this contract") + } + b := newFakeBackend(newAppRecorder(), nil) + t.Cleanup(func() { _ = b.Close() }) + if b.ChatsLiveOffered() { + t.Fatal("with remote control off no live view can be offered") + } + a := quitLocalChat(t, b, "local-chat") + b.markQuit([]*appAgent{a}) + wantRecorded(t, b, "local-chat") +} diff --git a/cmd/codeaf/approvals.go b/cmd/codeaf/approvals.go index 3be32c5361..220e202416 100644 --- a/cmd/codeaf/approvals.go +++ b/cmd/codeaf/approvals.go @@ -16,9 +16,11 @@ import ( "github.com/Agent-Field/codeaf/internal/cellsync" "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/config" "github.com/Agent-Field/codeaf/internal/devname" "github.com/Agent-Field/codeaf/internal/directory" "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/livedoor" "github.com/Agent-Field/codeaf/internal/pair" "github.com/Agent-Field/codeaf/internal/reqsign" "github.com/Agent-Field/codeaf/internal/syncsetup" @@ -30,6 +32,9 @@ type approvalsDoor struct { dir string mailbox func(relayFlag string) (pair.Mailbox, error) approver func(pair.Mailbox) (pair.Approver, error) + // permits is this computer's book of what each paired computer may do here. + // Nil reads the book in the default state folder. + permits func() *pair.PermitBook mu sync.Mutex asking map[string]pair.Asking // by code: what Pending read, for the answer @@ -104,7 +109,7 @@ func (d *approvalsDoor) Pending(ctx context.Context, typed string) (tui3.Pending as, err := who.Look(ctx, ref) if errors.Is(err, pair.ErrLinkDecided) && approvedHere(who, ref.Code, "") == requestApprovedHere { // An approval whose reply was lost: the device is in, so this computer is shared. - if err := identity.EndSolo(d.dir); err != nil { + if err := pair.EndSoloAt(d.dir, d.book()); err != nil { return tui3.PendingDevice{}, err } notePaired(d.dir, route) @@ -147,7 +152,7 @@ func (d *approvalsDoor) Approve(ctx context.Context, p tui3.PendingDevice) error return err } } - if err := identity.EndSolo(d.dir); err != nil { + if err := pair.EndSoloAt(d.dir, d.book()); err != nil { return err } if route, err := d.mailbox(""); err == nil { @@ -276,9 +281,53 @@ func (d *approvalsDoor) Devices(ctx context.Context) ([]tui3.DeviceRow, error) { if own, named := devname.Chosen(d.dir); named { rows = withOwnName(rows, own) } - return rows, nil + return d.withPermits(id.ID(), rows), nil } +// book is the permit book this door reads and writes. +func (d *approvalsDoor) book() *pair.PermitBook { + if d.permits != nil { + return d.permits() + } + return pair.Permits() +} + +// withPermits puts what each other computer may do here on its row, so /devices +// can show and change it. WITH REMOTE CONTROL OFF IT PUTS NOTHING: the rows, +// and every line the device list draws from them, are then what they were +// before the setting existed, and the switches are absent rather than inert. +// Your own computer and a removed one have no permit to show. +func (d *approvalsDoor) withPermits(identityID string, rows []tui3.DeviceRow) []tui3.DeviceRow { + if identityID == "" || !config.RemoteControlOn() { + return rows + } + book := d.book() + for i := range rows { + if rows[i].Self || rows[i].Revoked { + continue + } + permit, _ := book.For(identityID, rows[i].ID) + rows[i].Permit = &tui3.DevicePermit{Watch: permit.Watch, Drive: permit.Drive} + } + return rows +} + +// SetPermit changes what one paired computer may do with chats on this one. A nil +// half is left as it is. It is the same write `codeaf devices permit` makes, so +// the terminal's keys and the command cannot disagree. +func (d *approvalsDoor) SetPermit(id string, watch, drive *bool) error { + if strings.TrimSpace(id) == "" { + return errors.New("choose a computer first") + } + who, err := identity.Load(d.dir) + if err != nil { + return err + } + return d.book().Set(who.ID(), id, watch, drive, "person") +} + +var _ tui3.PermitSetter = (*approvalsDoor)(nil) + // withOwnName puts this computer's own name on its own row. The directory holds // the name this computer last managed to tell it, which is the old one for a // person who renamed offline; the name kept here is the one they typed. @@ -323,7 +372,16 @@ func (d *approvalsDoor) Revoke(ctx context.Context, id string) error { if err != nil { return err } - return told(client.Revoke(ctx, id)) + if err := client.Revoke(ctx, id); err != nil { + return told(err) + } + // A REMOVED COMPUTER STOPS BEING ABLE TO WATCH AT ONCE: its open live views + // here close, its permit goes, and the last-seen copies kept of its chats go, + // the same three things `codeaf devices remove` and the app do. + livedoor.NotifyRemoved(d.dir, id) + _ = d.book().Forget(id) + forgetViewed(d.dir, id) + return nil } func (d *approvalsDoor) DeviceName(sealed string) string { diff --git a/cmd/codeaf/appsettings.go b/cmd/codeaf/appsettings.go index 8a774ba959..ecf126bd68 100644 --- a/cmd/codeaf/appsettings.go +++ b/cmd/codeaf/appsettings.go @@ -70,6 +70,13 @@ func settingsExtra(settings *appwire.Settings, file appStateFile, profile string source = "saved" } settings.KnowledgeModel = config.KnowledgeModelRowAt(profile) + on := config.RemoteControlAt(profile) + settings.RemoteControl = &on + if row, ok := config.NewSettings(config.SettingsOptions{ProfileDir: profile}).Row(config.KeyRemoteControl); ok { + if name, pinned := row.PinnedBy(); pinned { + settings.RemoteControlPinnedBy = name + } + } settings.Memory = appwire.MemorySettings{Enabled: enabled, Source: source, CostNote: config.MemoryCostNote} settings.Appearance, settings.TextSize = appwire.AppearanceSystem, appwire.TextMedium if file.Appearance != "" { @@ -102,6 +109,26 @@ func (b *appBackend) applyExtra(patch appwire.SettingsPatch, profile string) err return appEngineError(err) } } + if patch.RemoteControl != nil { + raw := "off" + if *patch.RemoteControl { + raw = "on" + } + if err := applyRow(profile, config.KeyRemoteControl, raw); err != nil { + return err + } + if !*patch.RemoteControl { + // OFF IS ABOUT PEOPLE AS WELL AS THE DOOR. The door already stops + // handing chats out on its own (it reads the setting on every + // ask), but another computer that is already looking at one of + // these chats would go on looking, and typing, for as long as it + // likes. So their views end now: what they typed is in the chat, + // and they read it as the chat closing. ON needs no such step — + // the next chat opened is offered, and the ones open stay as they + // were. + deskHost.endAllViewers() + } + } for _, row := range []struct { key string value *string @@ -324,3 +351,23 @@ func (b *appBackend) ExportSpend(from, to time.Time) (string, error) { // MemorySettings advertises the live memory switch on the app wire. func (b *appBackend) MemorySettings() {} + +// RemoteControlSettings makes the hello announce settings.remote_control: the +// desktop engine always serves the row, off or on, so the window can show the +// switch before anything is turned on. +func (b *appBackend) RemoteControlSettings() {} + +// remoteControlFree is nil when a write to the Remote control row would take +// effect, and the engine's own refusal when the environment pins it. It is +// asked before any other field of a patch lands, so a pinned row refuses the +// patch whole instead of half applying it (the day limit does the same). +func remoteControlFree(profile string) error { + row, ok := config.NewSettings(config.SettingsOptions{ProfileDir: profile}).Row(config.KeyRemoteControl) + if !ok { + return appwire.Errorf(appwire.CodeEngine, "this build has no %s setting", config.KeyRemoteControl) + } + if name, pinned := row.PinnedBy(); pinned { + return appwire.Errorf(appwire.CodeBadParams, "%s is set by %s", row.Label, name) + } + return nil +} diff --git a/cmd/codeaf/appstate.go b/cmd/codeaf/appstate.go index 9468b0b8aa..57c2898c14 100644 --- a/cmd/codeaf/appstate.go +++ b/cmd/codeaf/appstate.go @@ -481,6 +481,11 @@ func (b *appBackend) SetSettings(patch appwire.SettingsPatch) (appwire.Settings, return appwire.Settings{}, err } } + if patch.RemoteControl != nil { + if err := remoteControlFree(profile); err != nil { + return appwire.Settings{}, err + } + } if patch.WhenPlanPaused != nil { if err := b.setPlanPaused(patch.WhenPlanPaused); err != nil { return appwire.Settings{}, err diff --git a/cmd/codeaf/appsync.go b/cmd/codeaf/appsync.go index ab5232504c..740ada79aa 100644 --- a/cmd/codeaf/appsync.go +++ b/cmd/codeaf/appsync.go @@ -186,6 +186,26 @@ func (b *appBackend) located(a *appAgent, location *appwire.Location) { if old == nil && location == nil { return } + // A LIVE VIEW'S FACTS ARE THE LIVE LINK'S: the chat list says where the + // chat is held, not how this window's view of it stands, so an update + // from the list keeps what the link last said. + if a.liveRemote != nil && old != nil && old.Live != nil && location != nil && location.Live == nil && !location.Here { + kept := *location + kept.Live = old.Live + location = &kept + } + // A CHAT HELD HERE KEEPS WHAT THE ENGINE LAST SAID OF ITS KEYBOARD: the + // chat list says where the chat is held, never who is typing in it, so + // an update from the list lays the fact back over its own word. + if kb := a.heldKeyboard; kb != nil { + if location == nil { + location = &appwire.Location{Here: true, Keyboard: kb} + } else if location.Here { + kept := *location + kept.Keyboard = kb + location = &kept + } + } if reflect.DeepEqual(old, location) { return } @@ -305,7 +325,10 @@ func (b *appBackend) AcknowledgeSync(id string) error { } func appLocationRefusal(location *appwire.Location) error { - if location == nil || location.Here { + // A LIVE VIEW IS NEVER A REFUSAL: the chat is held elsewhere on purpose and + // is worked from here through the live door, which says for itself, per + // call, whether the person may type (app_live_open.go). + if location == nil || location.Here || location.Live != nil { return nil } return &appwire.Error{Code: appwire.CodeConflict, Message: location.Line, Detail: appwire.HeldElsewhere{Kind: "held_elsewhere", Holder: location.Holder}} diff --git a/cmd/codeaf/beltdoors_test.go b/cmd/codeaf/beltdoors_test.go index c4473553cc..0724aac3b8 100644 --- a/cmd/codeaf/beltdoors_test.go +++ b/cmd/codeaf/beltdoors_test.go @@ -29,7 +29,8 @@ import ( // The cap moves by exactly those seven lines; unrelated help growth still fails. // The pairing door adds its two forms and their descriptions, four lines more. // The devbox door adds its form and description, two lines more. -const helpLineCap = 123 +// The devices permit door adds its form and description, two lines more. +const helpLineCap = 125 // doorsOffThePage are the command words main.go dispatches that `codeaf --help` // deliberately does NOT name, so the check below does not demand a line for diff --git a/cmd/codeaf/chatv3.go b/cmd/codeaf/chatv3.go index f3668377d0..a5c41e9849 100644 --- a/cmd/codeaf/chatv3.go +++ b/cmd/codeaf/chatv3.go @@ -184,7 +184,7 @@ func openChatV3(name string, args []string, pickSession bool) error { // which they meant would open a conversation on a machine they did not // name. if strings.TrimSpace(*host) != "" && strings.TrimSpace(*at) != "" { - return fmt.Errorf("--host reaches a machine over ssh and --at reaches one through the sync service: name one or the other, not both") + return fmt.Errorf("--host reaches a machine over ssh and --at reaches one through the relay: name one or the other, not both") } // --org IS THE FOURTH WAY TO NAME WHERE THE CONVERSATION IS, and it refuses // what --at refuses (chatv3_org.go's check), beside the --at refusals above diff --git a/cmd/codeaf/chatv3_at.go b/cmd/codeaf/chatv3_at.go index 224ce15d0a..94b704e3e7 100644 --- a/cmd/codeaf/chatv3_at.go +++ b/cmd/codeaf/chatv3_at.go @@ -274,7 +274,7 @@ func runServe(args []string) error { flags := commandFlags("serve") takeTasks := flags.Bool(taskdoor.TakeTasksFlag, false, "take tasks from your paired computers") workspace := flags.String("workspace", "", "directory a connection works in when it does not name one; empty is the directory this command was run in") - relayAddress := flags.String("via", "", "the sync service to be reachable through; empty reads "+pair.RelayEnv+", ~/.codeaf/v3/remote/relay, then the address this machine syncs through") + relayAddress := flags.String("via", "", "the relay to be reachable through; empty reads "+pair.RelayEnv+", ~/.codeaf/v3/remote/relay, then the address this machine syncs through") renamedFlag(flags, "relay", "via") if err := parseCommandFlags(flags, args); err != nil { return err @@ -290,7 +290,7 @@ func runServe(args []string) error { if service == "" { // Only a machine whose person turned sync off and named no relay // gets here; every other machine has sync's address. - return errors.New("no sync service is set up on this machine, so there is nowhere to be reachable from — set " + pair.RelayEnv + " to your sync service") + return errors.New("no relay is set up on this machine, so there is nowhere to be reachable from — set " + pair.RelayEnv + " to your relay") } here := strings.TrimSpace(*workspace) diff --git a/cmd/codeaf/chatv3_at_test.go b/cmd/codeaf/chatv3_at_test.go index 97f59902ce..752c8176aa 100644 --- a/cmd/codeaf/chatv3_at_test.go +++ b/cmd/codeaf/chatv3_at_test.go @@ -78,7 +78,7 @@ func TestWithNoRelayBothDoorsSayWhatIsWrongAndWhatToDoInstead(t *testing.T) { t.Fatal("--at opened a connection with no relay set up") } said := err.Error() - for _, want := range []string{"no sync service is set up on this machine", "CODEAF_RELAY", "--host over ssh", "otter-lamp-42"} { + for _, want := range []string{"no relay is set up on this machine", "CODEAF_RELAY", "--host over ssh", "otter-lamp-42"} { if !strings.Contains(said, want) { t.Fatalf("--at with no relay said %q, which does not mention %q", said, want) } @@ -92,7 +92,7 @@ func TestWithNoRelayBothDoorsSayWhatIsWrongAndWhatToDoInstead(t *testing.T) { t.Fatal("codeaf serve started with no relay set up") } said = err.Error() - for _, want := range []string{"no sync service is set up on this machine", "CODEAF_RELAY", "set " + pair.RelayEnv + " to your sync service"} { + for _, want := range []string{"no relay is set up on this machine", "CODEAF_RELAY", "set " + pair.RelayEnv + " to your relay"} { if !strings.Contains(said, want) { t.Fatalf("codeaf serve with no relay said %q, which does not mention %q", said, want) } diff --git a/cmd/codeaf/chatv3_layout.go b/cmd/codeaf/chatv3_layout.go index eb1efebd5a..a1e428d263 100644 --- a/cmd/codeaf/chatv3_layout.go +++ b/cmd/codeaf/chatv3_layout.go @@ -865,6 +865,9 @@ func v3SeatPending(place session.Place, say func(string), drives *driveBook) (ex watch.Retire() } watch.OnTail = func() { sealTail(seat, drive) } + if drive != nil && err == nil { + drive.setFirstSave(func() { executor.Settle(context.Background(), seat) }) + } // A fresh seat has no foreground turn in flight. Background tasks may be // the first input; their journal writes need a tail seal even before chat. // Window attachment reuses the engine's seat rather than constructing one. diff --git a/cmd/codeaf/chatv3_live.go b/cmd/codeaf/chatv3_live.go new file mode 100644 index 0000000000..e3172195a8 --- /dev/null +++ b/cmd/codeaf/chatv3_live.go @@ -0,0 +1,729 @@ +package main + +import ( + "context" + "log" + "strings" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" + "github.com/Agent-Field/codeaf/internal/tui3" + "github.com/Agent-Field/codeaf/internal/viewcache" +) + +const ( + livePruneScope = "chatv3/live-prune" + liveEventsScope = "chatv3/live-events" +) + +// remoteControlWanted says whether this build's remote control is switched on. +func remoteControlWanted() bool { + return config.RemoteControlOn() +} + +// liveRoad is everything the terminal needs from the viewer side of one other +// computer's connection, in this package's words. +type liveRoad interface { + // Dial returns the dialler remote.Roam redials by for one chat. + Dial(chat string) remote.Dialer + // Read is the state now, answered from fields already held because it is asked on the draw path. + Read() tui3.LiveRead + // Changed is closed the next time Read's answer moves. + Changed() <-chan struct{} + // Touch tells the link a person or a running turn is active so idle detach can read it. + Touch() + // Reconnect reattaches after an idle detach, off the update loop. + Reconnect() + // Road is the word for how the bytes travel, said by the door so this package never spells it. + Road() string + // Permit is what the other computer lets this one do: may it type, and the sentence that says why not. + Permit() (drive bool, readOnly string) +} + +// olderRoad is a road that can read older pages by itself; the real road cannot and the agent pages through its own connection instead. +type olderRoad interface { + Older(ctx context.Context, chat string, before, limit int) (entries []session.DisplayEntry, base int, more bool, err error) +} + +// liveRoads finds the road to one other computer by its directory device id, +// and whether one exists. It is the one injection point: nil (the state of +// every build until the adapter lands) means no road, so remote control is +// absent. +var liveRoads func(device, name string) (liveRoad, string, bool) + +// liveDoor opens a chat held on another of this person's computers as a live +// view when that computer can be reached, and falls back to the viewer's +// last-seen copy when it is offline. +type liveDoor struct { + home string + cache *viewcache.Cache + roads func(device, name string) (liveRoad, string, bool) + clock viewcache.Clock + dial func(road liveRoad, row chatlist.Row) (tui3.Agent, remote.Welcome, error) + // roam dials a host the way remote.Roam does, and nil is remote.Roam. A test + // reads the policy the door asks for through it without a host to dial. + roam func(host string, hello remote.Hello, roaming remote.Roaming) (*remote.Client, error) +} + +func (d *liveDoor) lookupRoad(device, name string) (liveRoad, string, bool) { + if d.roads != nil { + return d.roads(device, name) + } + if liveRoads != nil { + return liveRoads(device, name) + } + return nil, "", false +} + +// Open dials a live view of row on the computer holding it, or opens the +// local last-seen copy read-only when that computer is offline. +// +// IT REFUSES WHILE REMOTE CONTROL IS OFF. The surface already does not ask +// then, and the road lookup refuses too, but the last-seen copy of an offline +// chat needs no road: without this line a caller that skipped the surface's +// check would be handed a view of another computer's chat on a setting that +// says no. +func (d *liveDoor) Open(ctx context.Context, row chatlist.Row) (tui3.Conversation, error) { + if !remoteControlWanted() { + return tui3.Conversation{}, tui3.ErrNoLiveView + } + road, name, ok := d.lookupRoad(row.DeviceID, row.Device) + host := strings.TrimSpace(name) + if host == "" { + host = strings.TrimSpace(row.Device) + } + if row.Status == chatlist.Off { + return d.openOffline(host, row) + } + if !ok || road == nil { + return tui3.Conversation{}, tui3.ErrNoLiveView + } + + var ( + baseAgent tui3.Agent + welcome remote.Welcome + link tui3.LinkSeam + taskRoom func(uint64, int) (session.TaskRecord, error) + pager func(context.Context, int, int) (remote.Page, error) + shut func() error + ) + if d.dial != nil { + var err error + baseAgent, welcome, err = d.dial(road, row) + if err != nil { + if isNotRunningError(err) { + return d.openOffline(host, row) + } + return tui3.Conversation{}, err + } + if remoteAgent, ok := baseAgent.(*remote.Agent); ok { + client := remoteAgent.Client() + seams := newHostSeams(client) + link = hostLink(seams) + taskRoom = remoteAgent.TaskRoom + pager = remoteAgent.TranscriptPage + shut = client.Close + baseAgent = countedAgent(remoteAgent) + } else if room, ok := baseAgent.(interface { + TaskRoom(uint64, int) (session.TaskRecord, error) + }); ok { + taskRoom = room.TaskRoom + } + link.Driving = liveDriving(link.Driving, road) + } else { + dialer := road.Dial(row.Cell) + if dialer == nil { + return d.openOffline(host, row) + } + // THE HOST ROUTER REWRITES THE HELLO to bind the holder's transcript and + // workspace, so the viewer sends only an unwindowed hello and lets Roam + // carry resume cursors across redials. + roam := d.roam + if roam == nil { + roam = remote.Roam + } + client, err := roam(host, remote.Hello{Window: false}, liveRoaming(dialer, host)) + if err != nil { + if isNotRunningError(err) { + return d.openOffline(host, row) + } + return tui3.Conversation{}, err + } + welcome = client.Welcome() + if shown := strings.TrimSpace(welcome.Machine); shown != "" && host == "" { + host = shown + } + if host != "" { + client.SetDisplayName(host) + } + seams := newHostSeams(client) + link = hostLink(seams) + link.Driving = liveDriving(link.Driving, road) + remoteAgent := client.Agent() + taskRoom = remoteAgent.TaskRoom + pager = remoteAgent.TranscriptPage + baseAgent = countedAgent(remoteAgent) + shut = client.Close + } + + agent := &liveAgent{ + Agent: baseAgent, + road: road, + pager: pager, + cache: d.cache, + host: host, + device: row.DeviceID, + cell: row.Cell, + title: row.Title, + workspace: welcome.Workspace, + shut: shut, + } + return tui3.Conversation{ + Agent: agent, + SessionFile: welcome.SessionFile, + Workspace: welcome.Workspace, + Resumed: welcome.Resumed, + Notice: hostEntryNotice(welcome), + Link: &link, + TaskRoom: taskRoom, + Live: &tui3.LiveSeam{ + Host: host, + Device: row.DeviceID, + Cell: row.Cell, + Road: road.Road(), + Row: row, + Read: road.Read, + Touch: road.Touch, + Reconnect: road.Reconnect, + Changed: road.Changed, + }, + }, nil +} + +func (d *liveDoor) openOffline(name string, row chatlist.Row) (tui3.Conversation, error) { + if d.cache == nil { + return tui3.Conversation{}, tui3.ErrNoLiveView + } + snapshot, ok := d.cache.Load(row.DeviceID, row.Cell) + if !ok { + return tui3.Conversation{}, tui3.ErrNoLiveView + } + host := strings.TrimSpace(name) + if host == "" { + host = strings.TrimSpace(snapshot.HostName) + } + if host == "" { + host = strings.TrimSpace(row.Device) + } + seenAt := snapshot.SeenAt + agent := &viewcacheAgent{snapshot: snapshot, host: host} + link := tui3.LinkSeam{ + SendRefusal: func() string { return chatlist.LiveNotSentOffline(host) }, + } + return tui3.Conversation{ + Agent: agent, + Workspace: snapshot.Workspace, + Resumed: true, + Link: &link, + Live: &tui3.LiveSeam{ + Host: host, + Device: row.DeviceID, + Cell: row.Cell, + Row: row, + Read: func() tui3.LiveRead { + return tui3.LiveRead{Kind: tui3.LiveCopy, SeenAt: seenAt} + }, + }, + }, nil +} + +func isNotRunningError(err error) bool { + if err == nil { + return false + } + msg := strings.ToLower(err.Error()) + return strings.Contains(msg, "not running") || strings.Contains(msg, "not-running") +} + +// liveDriving combines the remote client's keyboard arbitration with the road's +// watch/type permit so a watch-only viewer sees why typing is closed and a +// drive-capable viewer sees which other computer holds the keyboard. +func liveDriving(base func() tui3.Driving, road liveRoad) func() tui3.Driving { + return func() tui3.Driving { + driving := tui3.Driving{Yours: true} + if base != nil { + driving = base() + } + if !driving.Yours && driving.Holder == "" { + driving.Holder = driving.Machine + } + if road != nil { + if drive, readOnly := road.Permit(); !drive { + driving.ReadOnly = readOnly + } else { + driving.ReadOnly = "" + } + } + return driving + } +} + +// liveRoamWindow is how long a live view keeps trying to reach its host after +// the link drops: a laptop that comes back from sleep should find its view +// again, so it is far longer than the minute a one-off remote door keeps. +const liveRoamWindow = 30 * time.Minute + +// liveRoaming is the policy a live view redials by, and THE FOUR SWITCHES IN IT +// ARE LAWS, not tuning. SpreadReturns is the fourth: a live view is dialled +// through a relay that can drop every viewer in one instant, so its first retry +// is spread over six seconds (V22), which no ssh or local road is. ResendUnanswered is what keeps a message typed just +// before the link dropped from being lost: the client resends it once, with the +// id it carries, and the host answers a repeat without running it twice. MaxLine +// bounds one inbound line to what the live door itself allows, so a hostile +// peer cannot make the viewer buffer without end. OnGap says when the host's +// replay no longer held every event the viewer missed. Leaving any of them out +// turns the failure it guards into a silent one. +func liveRoaming(dial remote.Dialer, host string) remote.Roaming { + return remote.Roaming{ + Dial: dial, + Window: liveRoamWindow, + MaxLine: livedoor.MaxLine, + ResendUnanswered: true, + SpreadReturns: true, + OnGap: liveGapNote(host), + } +} + +// liveGapNote records that the host's replay ring had already dropped events +// the viewer had not seen. The client moves its cursor past them and goes on +// with the retained events on its own, and the words that were dropped are in the +// host's transcript, which scrolling up reads, so the one thing left to do here +// is to leave a line that says it happened. +func liveGapNote(host string) func(remote.Gap) { + return func(gap remote.Gap) { + log.Printf("live view of %s: its replay no longer held events %d to %d of stream %d; the transcript has them", host, gap.Have+1, gap.First-1, gap.Stream) + } +} + +// liveAgent wraps a live remote agent with older-history paging through the +// road, quiet-beat viewer caching, and local-only client teardown so leaving a +// live view never stops the chat on the computer running it. +type liveAgent struct { + tui3.Agent + road liveRoad + pager func(ctx context.Context, before, limit int) (remote.Page, error) + cache *viewcache.Cache + host string + device string + cell string + title string + workspace string + shut func() error + shutOnce sync.Once + shutErr error + + mu sync.Mutex + done chan struct{} + base int + turns int + savedLen int + lastEntries []session.DisplayEntry +} + +var _ tui3.OlderReader = (*liveAgent)(nil) + +// Older fetches a page of entries before the absolute index through the +// agent's own connection (or an olderRoad fallback) and updates TranscriptBase +// to the absolute index of the first entry returned. +func (a *liveAgent) Older(ctx context.Context, before, limit int) ([]session.DisplayEntry, bool, error) { + if a.pager != nil { + page, err := a.pager(ctx, before, limit) + if err != nil { + return nil, false, err + } + a.setBase(page.Base) + return page.Entries, page.More, nil + } + if road, ok := a.road.(olderRoad); ok { + entries, base, more, err := road.Older(ctx, a.cell, before, limit) + if err != nil { + return nil, false, err + } + a.setBase(base) + return entries, more, nil + } + return nil, false, nil +} + +// TranscriptBase returns the absolute transcript index of the first entry held. +func (a *liveAgent) TranscriptBase() int { + a.mu.Lock() + defer a.mu.Unlock() + return a.base +} + +func (a *liveAgent) setBase(base int) { + a.mu.Lock() + defer a.mu.Unlock() + a.base = base +} + +func (a *liveAgent) beginTurn() { + a.mu.Lock() + defer a.mu.Unlock() + a.turns++ +} + +func (a *liveAgent) finishTurn() bool { + a.mu.Lock() + defer a.mu.Unlock() + if a.turns > 0 { + a.turns-- + } + return a.turns == 0 +} + +func (a *liveAgent) noteEntries(entries []session.DisplayEntry) (grew, idle bool) { + a.mu.Lock() + defer a.mu.Unlock() + if len(entries) > 0 { + a.lastEntries = append([]session.DisplayEntry(nil), entries...) + } + idle = a.turns == 0 + if idle && len(entries) > a.savedLen { + a.savedLen = len(entries) + grew = true + } + return grew, idle +} + +func (a *liveAgent) rememberSaved(entries []session.DisplayEntry) { + a.mu.Lock() + defer a.mu.Unlock() + if len(entries) > 0 { + a.lastEntries = append([]session.DisplayEntry(nil), entries...) + } + if len(entries) > a.savedLen { + a.savedLen = len(entries) + } +} + +func (a *liveAgent) heldEntries() []session.DisplayEntry { + a.mu.Lock() + defer a.mu.Unlock() + return append([]session.DisplayEntry(nil), a.lastEntries...) +} + +func (a *liveAgent) snapshot(entries []session.DisplayEntry) viewcache.Snapshot { + title := strings.TrimSpace(a.Agent.Title()) + if title == "" { + title = a.title + } + base := a.TranscriptBase() + return viewcache.Snapshot{ + Host: a.device, + HostName: a.host, + Chat: a.cell, + Title: title, + Model: a.Agent.Model(), + Workspace: a.workspace, + Base: base, + Total: base + len(entries), + Entries: append([]session.DisplayEntry(nil), entries...), + } +} + +func (a *liveAgent) saveQuiet(entries []session.DisplayEntry) { + if a.cache == nil { + return + } + _ = a.cache.Save(a.device, a.cell, a.snapshot(entries)) +} + +func (a *liveAgent) saveAfterTurn() { + if !a.finishTurn() || a.cache == nil { + return + } + entries := a.Agent.Transcript() + a.rememberSaved(entries) + if len(entries) == 0 { + entries = a.heldEntries() + } + a.saveQuiet(entries) +} + +func (a *liveAgent) saveNow() { + if a.cache == nil { + return + } + entries := a.Agent.Transcript() + a.rememberSaved(entries) + if len(entries) == 0 { + entries = a.heldEntries() + } + _ = a.cache.SaveNow(a.device, a.cell, a.snapshot(entries)) +} + +// closing is closed once this view lets go of its connection, so a forwarder +// that is waiting on a reader that has gone away stops instead of parking for +// the life of the process. +func (a *liveAgent) closing() chan struct{} { + a.mu.Lock() + defer a.mu.Unlock() + if a.done == nil { + a.done = make(chan struct{}) + } + return a.done +} + +func (a *liveAgent) watchEvents(src <-chan session.Event) <-chan session.Event { + if src == nil { + return nil + } + a.beginTurn() + out := make(chan session.Event) + done := a.closing() + guard.Go(liveEventsScope, func() { + settled := false + defer func() { + if !settled { + a.saveAfterTurn() + } + close(out) + }() + for ev := range src { + if ev.Kind == session.EventTurnDone && !settled { + settled = true + a.saveAfterTurn() + } + select { + case out <- ev: + case <-done: + return + } + } + }) + return out +} + +// Submit runs a turn on the remote host and saves the viewer cache once the +// turn settles, never per streaming delta. +func (a *liveAgent) Submit(ctx context.Context, text string) (<-chan session.Event, error) { + events, err := a.Agent.Submit(ctx, text) + if err != nil { + return nil, err + } + return a.watchEvents(events), nil +} + +// SubmitImage runs an image turn on the remote host and saves the viewer cache +// once the turn settles. +func (a *liveAgent) SubmitImage(ctx context.Context, text string, images []session.Image) (<-chan session.Event, error) { + events, err := a.Agent.SubmitImage(ctx, text, images) + if err != nil { + return nil, err + } + return a.watchEvents(events), nil +} + +// FollowUp queues a follow-up turn and saves the viewer cache when it settles. +func (a *liveAgent) FollowUp(text string) (<-chan session.Event, error) { + events, err := a.Agent.FollowUp(text) + if err != nil { + return nil, err + } + return a.watchEvents(events), nil +} + +// Transcript reads the conversation so far and updates the viewer cache when +// the transcript has grown on a quiet beat with no turn running. +func (a *liveAgent) Transcript() []session.DisplayEntry { + entries := a.Agent.Transcript() + if grew, _ := a.noteEntries(entries); grew { + a.saveQuiet(entries) + } + return entries +} + +// AttachReplay joins an in-flight turn when the underlying agent supports it, +// wrapping the event stream so the viewer cache updates when the turn ends. +func (a *liveAgent) AttachReplay() ([]session.DisplayEntry, <-chan session.Event, func()) { + if door, ok := a.Agent.(interface { + AttachReplay() ([]session.DisplayEntry, <-chan session.Event, func()) + }); ok { + entries, events, stop := door.AttachReplay() + if events != nil { + a.rememberSaved(entries) + return entries, a.watchEvents(events), stop + } + if grew, _ := a.noteEntries(entries); grew { + a.saveQuiet(entries) + } + return entries, nil, stop + } + return a.Transcript(), nil, func() {} +} + +// Attach joins an in-flight turn's stream when the underlying agent supports it. +func (a *liveAgent) Attach() (<-chan session.Event, bool, func()) { + if door, ok := a.Agent.(interface { + Attach() (<-chan session.Event, bool, func()) + }); ok { + events, running, stop := door.Attach() + if !running || events == nil { + return events, running, stop + } + return a.watchEvents(events), true, stop + } + return nil, false, func() {} +} + +// WorkOutlivesExit reports that a live conversation keeps running on its host +// computer after this viewer leaves. +func (a *liveAgent) WorkOutlivesExit() bool { return true } + +func (a *liveAgent) closeClient() error { + a.shutOnce.Do(func() { + close(a.closing()) + if a.shut != nil { + a.shutErr = a.shut() + } + }) + return a.shutErr +} + +// Detach saves the last-seen copy immediately and closes only the local Roam +// client so the chat continues undisturbed on the other computer. +func (a *liveAgent) Detach() error { + a.saveNow() + return a.closeClient() +} + +// Close saves the last-seen copy immediately and closes only the local Roam +// client; a viewer never ends the chat on the other computer. +func (a *liveAgent) Close() error { + a.saveNow() + return a.closeClient() +} + +// errLiveCopy is the refusal returned when a person tries to submit a message +// into a read-only offline copy of another computer's chat. +type errLiveCopy struct { + host string +} + +func (e errLiveCopy) Error() string { + return chatlist.LiveNotSentOffline(e.host) +} + +// viewcacheAgent serves a last-seen snapshot read-only when the computer that +// holds the chat is offline. +type viewcacheAgent struct { + snapshot viewcache.Snapshot + host string +} + +var _ tui3.Agent = (*viewcacheAgent)(nil) + +func (v *viewcacheAgent) Submit(context.Context, string) (<-chan session.Event, error) { + return nil, errLiveCopy{host: v.host} +} + +func (v *viewcacheAgent) SubmitImage(context.Context, string, []session.Image) (<-chan session.Event, error) { + return nil, errLiveCopy{host: v.host} +} + +func (v *viewcacheAgent) FollowUp(string) (<-chan session.Event, error) { + return nil, errLiveCopy{host: v.host} +} + +func (v *viewcacheAgent) Interrupt() {} +func (v *viewcacheAgent) InterruptFor(session.StopDoor) {} +func (v *viewcacheAgent) Compact(context.Context) error { return nil } +func (v *viewcacheAgent) Close() error { return nil } +func (v *viewcacheAgent) Detach() error { return nil } +func (v *viewcacheAgent) WorkOutlivesExit() bool { return true } +func (v *viewcacheAgent) Model() string { return v.snapshot.Model } +func (v *viewcacheAgent) SetModel(string) {} +func (v *viewcacheAgent) SetContextWindow(int) {} +func (v *viewcacheAgent) ReasoningFor(string) string { return "" } +func (v *viewcacheAgent) SetReasoningFor(string, string) {} +func (v *viewcacheAgent) ResolveConsent(uint64, bool) {} +func (v *viewcacheAgent) ResolveConsentRemember(uint64, bool, session.ConsentScope) {} +func (v *viewcacheAgent) ResolveHarness(uint64, bool, string) {} +func (v *viewcacheAgent) ResolveConnect(string, bool) {} +func (v *viewcacheAgent) ResolveConnectKey(string, string) {} +func (v *viewcacheAgent) NoteConnected(string, string) {} +func (v *viewcacheAgent) Title() string { return v.snapshot.Title } +func (v *viewcacheAgent) Usage() session.Usage { return session.Usage{} } +func (v *viewcacheAgent) ContextTokens() int { return 0 } +func (v *viewcacheAgent) EarlierHistory() session.EarlierHistory { return session.EarlierHistory{} } + +func (v *viewcacheAgent) Transcript() []session.DisplayEntry { + return append([]session.DisplayEntry(nil), v.snapshot.Entries...) +} + +func (v *viewcacheAgent) AttachReplay() ([]session.DisplayEntry, <-chan session.Event, func()) { + ch := make(chan session.Event) + close(ch) + return v.Transcript(), ch, func() {} +} + +// wireLive attaches the live-view opener to Options when a road lookup is +// installed and the window is not itself a hosted session, WHETHER OR NOT +// remote control is switched on. The setting is not a start-up fact: a person +// turns it on in /settings, or with CODEAF_REMOTE_CONTROL, in a window that is +// already open, and that window's next Enter on a held chat has to open it live. +// So the surface is handed the setting as a live read (Options.RemoteControl) +// and asks it each time, and the door refuses with tui3.ErrNoLiveView while it +// is off. With it off the window offers exactly what a window with no opener +// offers. +func wireLive(o *tui3.Options, home string) { + if o == nil || o.Host != "" || liveRoads == nil { + return + } + if o.RemoteControl == nil { + o.RemoteControl = remoteControlWanted + } + cache := viewcache.Open(home) + // THE LAST-SEEN COPIES ARE TRIMMED ONLY WHEN REMOTE CONTROL IS ON AT START, + // as before: with it off nothing here touches the disk, and a window switched + // on later trims at its next start, which is soon enough for a cap that bounds + // one small file per chat. + if remoteControlWanted() { + guard.Go(livePruneScope, cache.Prune) + } + if o.OpenLive == nil { + door := &liveDoor{ + home: home, + cache: cache, + roads: liveRoads, + } + o.OpenLive = door.Open + } +} + +// forgetViewed removes every last-seen copy kept for one computer when that +// computer is removed from the person's devices. +func forgetViewed(home, device string) { + if strings.TrimSpace(home) == "" || strings.TrimSpace(device) == "" { + return + } + viewcache.Open(home).Forget(device) +} + +// forgetViewedChatEverywhere removes the last-seen copy of one chat kept for +// every computer, because the chat now runs on this one. The window that moved +// it does not know which computer the copy was last seen on. +func forgetViewedChatEverywhere(home, chat string) { + if strings.TrimSpace(home) == "" || strings.TrimSpace(chat) == "" { + return + } + viewcache.Open(home).ForgetChatEverywhere(chat) +} diff --git a/cmd/codeaf/chatv3_live_road.go b/cmd/codeaf/chatv3_live_road.go new file mode 100644 index 0000000000..c53f61ce26 --- /dev/null +++ b/cmd/codeaf/chatv3_live_road.go @@ -0,0 +1,226 @@ +package main + +import ( + "sync" + "sync/atomic" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/syncsetup" + "github.com/Agent-Field/codeaf/internal/tui3" +) + +const liveTouchScope = "chatv3/live-touch" + +// syncLiveRoads returns the function wireLive installs as liveRoads: the road +// to one other computer of this person's, made on first use and kept for the +// process. +func syncLiveRoads(s *syncsetup.Sync) func(device, name string) (liveRoad, string, bool) { + var ( + mu sync.Mutex + roads = make(map[string]*syncRoad) + ) + return func(device, name string) (liveRoad, string, bool) { + if s == nil || !config.RemoteControlOn() || device == "" || device == s.Device.ID() { + return nil, "", false + } + key := device + "\x00" + name + mu.Lock() + defer mu.Unlock() + if road, ok := roads[key]; ok { + return road, name, true + } + road := &syncRoad{ + host: name, + changed: make(chan struct{}), + } + road.bind(s.LiveLink(device, name, nil, road.onState)) + roads[key] = road + return road, name, true + } +} + +// syncRoad adapts one multiplexed livedoor.Link to the surface's liveRoad +// seam, holding the latest reported state in memory so the draw path never +// locks or polls the link. +type syncRoad struct { + link *livedoor.Link + host string + touch func() + + mu sync.Mutex + state livedoor.State + permit pair.Permit + changed chan struct{} + + touching atomic.Bool +} + +var _ liveRoad = (*syncRoad)(nil) + +func newSyncRoad(link *livedoor.Link, host string) *syncRoad { + r := &syncRoad{ + host: host, + changed: make(chan struct{}), + } + r.bind(link) + return r +} + +func (r *syncRoad) bind(link *livedoor.Link) { + var ( + st livedoor.State + touch func() + ) + if link != nil { + st = link.State() + touch = link.Touch + } + r.attach(link, touch, st) +} + +// attach holds a link and the state it started in. The lock is released by a defer +// so a panic absorbed further up cannot leave the draw path waiting on it. +func (r *syncRoad) attach(link *livedoor.Link, touch func(), st livedoor.State) { + r.mu.Lock() + defer r.mu.Unlock() + r.link = link + r.touch = touch + r.state = st + if st.Kind == livedoor.Live || st.Kind == livedoor.WatchOnly { + r.permit = st.Permit + } +} + +func (r *syncRoad) onState(st livedoor.State) { + if prev := r.record(st); prev != nil { + close(prev) + } +} + +// record holds the newest state and answers the channel that was closed over by it, +// which the caller closes outside the lock. +func (r *syncRoad) record(st livedoor.State) (prev chan struct{}) { + r.mu.Lock() + defer r.mu.Unlock() + r.state = st + if st.Kind == livedoor.Live || st.Kind == livedoor.WatchOnly { + r.permit = st.Permit + } + prev = r.changed + r.changed = make(chan struct{}) + return prev +} + +// current is the state held now. +func (r *syncRoad) current() livedoor.State { + r.mu.Lock() + defer r.mu.Unlock() + return r.state +} + +// Read is what the door says about the view on every draw. The ROAD rides along +// with it, read from the link's own state each time, so that a swap between the +// relay and the direct road shows on the next frame and the seam's static word +// is only ever the first paint. +func (r *syncRoad) Read() tui3.LiveRead { + st := r.current() + read := tui3.LiveRead{Kind: tui3.LiveOn, Road: st.Road} + switch st.Kind { + case livedoor.Live, livedoor.WatchOnly: + read.Kind = tui3.LiveOn + case livedoor.Connecting, livedoor.Reconnecting: + read.Kind = tui3.LiveReconnecting + case livedoor.WentOffline: + read.Kind = tui3.LiveWentOffline + case livedoor.Idle: + read.Kind = tui3.LiveIdle + case livedoor.Revoked: + read.Kind = tui3.LiveRevoked + read.Reason = st.Reason + case livedoor.StateBudget: + read.Kind = tui3.LiveBudget + } + return read +} + +func (r *syncRoad) Changed() <-chan struct{} { + r.mu.Lock() + defer r.mu.Unlock() + return r.changed +} + +// toucher says whether the link is idle and what touches it. +func (r *syncRoad) toucher() (idle bool, touch func()) { + r.mu.Lock() + defer r.mu.Unlock() + touch = r.touch + if touch == nil && r.link != nil { + touch = r.link.Touch + } + return r.state.Kind == livedoor.Idle, touch +} + +func (r *syncRoad) Touch() { + idle, touch := r.toucher() + if idle || touch == nil { + return + } + if !r.touching.CompareAndSwap(false, true) { + return + } + guard.Go(liveTouchScope, func() { + defer r.touching.Store(false) + touch() + }) +} + +func (r *syncRoad) Reconnect() { + if r.link != nil { + r.link.Touch() + } +} + +func (r *syncRoad) Road() string { + r.mu.Lock() + defer r.mu.Unlock() + return r.state.Road +} + +// allowed is what the other computer last said this one may do, and its name. +func (r *syncRoad) allowed() (pair.Permit, string) { + r.mu.Lock() + defer r.mu.Unlock() + return r.permit, r.host +} + +func (r *syncRoad) Permit() (drive bool, readOnly string) { + p, host := r.allowed() + if p == (pair.Permit{}) { + return false, "" + } + if p.Drive { + return true, "" + } + if p.Watch { + return false, chatlist.LiveWatchOnly(host) + } + return false, chatlist.LiveNotAllowedHere(host) +} + +func (r *syncRoad) Dial(chat string) remote.Dialer { + if r.link == nil { + return nil + } + return remote.Dialer(r.link.Opener(chat)) +} + +func (r *syncRoad) Close() { + if r.link != nil { + r.link.Close() + } +} diff --git a/cmd/codeaf/chatv3_live_road_test.go b/cmd/codeaf/chatv3_live_road_test.go new file mode 100644 index 0000000000..75795a9696 --- /dev/null +++ b/cmd/codeaf/chatv3_live_road_test.go @@ -0,0 +1,311 @@ +package main + +import ( + "context" + "errors" + "io" + "sync/atomic" + "testing" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" + "github.com/Agent-Field/codeaf/internal/syncsetup" + "github.com/Agent-Field/codeaf/internal/tui3" +) + +func newTestLiveLink() *livedoor.Link { + return livedoor.NewLink(livedoor.LinkConfig{ + Dial: func(context.Context) (io.ReadWriteCloser, error) { + return nil, errors.New("test link never dials") + }, + }) +} + +// V1/V14: syncLiveRoads answers no road when remote control is off, for the empty device, and for this computer's own id; it answers a road (same pointer) twice for the same device and name and a different road for a new name. +func TestSyncLiveRoadsCachesOneRoadPerDeviceAndNameOnlyWhenRemoteControlIsOn(t *testing.T) { + homeDir := t.TempDir() + t.Setenv("CODEAF_HOME", homeDir) + + id, err := identity.Ensure(homeDir) + if err != nil { + t.Fatalf("ensure identity: %v", err) + } + dev, err := identity.Device(homeDir) + if err != nil { + t.Fatalf("ensure device: %v", err) + } + s := &syncsetup.Sync{ + Home: homeDir, + Identity: id, + Device: dev, + } + roads := syncLiveRoads(s) + + // Remote control off: never returns a road. + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + if road, name, ok := roads("dev_peer", "Desktop"); ok || road != nil || name != "" { + t.Fatalf("roads with remote control off = (%v, %q, %v), want (nil, \"\", false)", road, name, ok) + } + + // Remote control on: empty device and this computer's own device id return no road. + t.Setenv("CODEAF_REMOTE_CONTROL", "1") + if road, name, ok := roads("", "Desktop"); ok || road != nil || name != "" { + t.Fatalf("roads for empty device = (%v, %q, %v), want (nil, \"\", false)", road, name, ok) + } + if road, name, ok := roads(dev.ID(), "This Computer"); ok || road != nil || name != "" { + t.Fatalf("roads for own device id = (%v, %q, %v), want (nil, \"\", false)", road, name, ok) + } + + // Same device and name returns the exact same road pointer twice. + first, name1, ok1 := roads("dev_peer", "Desktop") + if !ok1 || first == nil || name1 != "Desktop" { + t.Fatalf("first roads(dev_peer, Desktop) = (%v, %q, %v), want non-nil road for Desktop", first, name1, ok1) + } + t.Cleanup(first.(*syncRoad).Close) + + second, name2, ok2 := roads("dev_peer", "Desktop") + if !ok2 || second != first || name2 != "Desktop" { + t.Fatalf("second roads(dev_peer, Desktop) = (%p, %q, %v), want (%p, \"Desktop\", true)", second, name2, ok2, first) + } + + // A new name for the same device makes a fresh road. + renamed, name3, ok3 := roads("dev_peer", "Studio") + if !ok3 || renamed == nil || renamed == first || name3 != "Studio" { + t.Fatalf("roads(dev_peer, Studio) = (%p, %q, %v), want distinct non-nil road for Studio (first=%p)", renamed, name3, ok3, first) + } + t.Cleanup(renamed.(*syncRoad).Close) +} + +// V7: the road reads tui3.LiveWentOffline after the link reports livedoor.WentOffline, LiveReconnecting after Reconnecting, LiveIdle after Idle, LiveRevoked with the reason after Revoked, LiveBudget after StateBudget, LiveOn after Live and after WatchOnly; Changed()'s channel is closed by each change and the next call hands back a fresh open one. +func TestSyncRoadMapsLinkStatesAndClosesChangedOnEveryTransition(t *testing.T) { + link := newTestLiveLink() + road := newSyncRoad(link, "Desktop") + t.Cleanup(road.Close) + + if got := road.Read(); got.Kind != tui3.LiveReconnecting { + t.Fatalf("initial Read() = %+v, want LiveReconnecting", got) + } + + steps := []struct { + state livedoor.State + want tui3.LiveRead + }{ + { + state: livedoor.State{Kind: livedoor.WentOffline}, + want: tui3.LiveRead{Kind: tui3.LiveWentOffline}, + }, + { + state: livedoor.State{Kind: livedoor.Reconnecting}, + want: tui3.LiveRead{Kind: tui3.LiveReconnecting}, + }, + { + state: livedoor.State{Kind: livedoor.Idle}, + want: tui3.LiveRead{Kind: tui3.LiveIdle}, + }, + { + state: livedoor.State{Kind: livedoor.Revoked, Reason: "removed"}, + want: tui3.LiveRead{Kind: tui3.LiveRevoked, Reason: "removed"}, + }, + { + state: livedoor.State{Kind: livedoor.StateBudget}, + want: tui3.LiveRead{Kind: tui3.LiveBudget}, + }, + { + state: livedoor.State{Kind: livedoor.Live}, + want: tui3.LiveRead{Kind: tui3.LiveOn}, + }, + { + state: livedoor.State{Kind: livedoor.WatchOnly}, + want: tui3.LiveRead{Kind: tui3.LiveOn}, + }, + } + + for i, step := range steps { + prev := road.Changed() + select { + case <-prev: + t.Fatalf("step %d (%v): Changed() channel was already closed before transition", i, step.state.Kind) + default: + } + + road.onState(step.state) + + select { + case <-prev: + default: + t.Fatalf("step %d (%v): Changed() channel was not closed by onState", i, step.state.Kind) + } + + next := road.Changed() + if next == prev { + t.Fatalf("step %d (%v): Changed() returned the same channel after onState", i, step.state.Kind) + } + select { + case <-next: + t.Fatalf("step %d (%v): fresh Changed() channel is already closed", i, step.state.Kind) + default: + } + + if got := road.Read(); got != step.want { + t.Fatalf("step %d (%v): Read() = %+v, want %+v", i, step.state.Kind, got, step.want) + } + } +} + +// V11: after WatchOnly with Permit{Watch: true}, Permit() is (false, chatlist.LiveWatchOnly(host)); after Live with Permit{Watch: true, Drive: true} it is (true, ""); after a later Reconnecting (which carries no permit) it keeps the last known answer. +func TestSyncRoadRemembersTheLastKnownPermitAcrossReconnects(t *testing.T) { + const host = "Desktop" + link := newTestLiveLink() + road := newSyncRoad(link, host) + t.Cleanup(road.Close) + + // Before any Live or WatchOnly state, the permit is the zero value. + if drive, readOnly := road.Permit(); drive || readOnly != "" { + t.Fatalf("initial Permit() = (%v, %q), want (false, \"\")", drive, readOnly) + } + + // WatchOnly with Permit{Watch: true} reports watch-only for host. + road.onState(livedoor.State{ + Kind: livedoor.WatchOnly, + Permit: pair.Permit{Watch: true}, + }) + wantWatchOnly := chatlist.LiveWatchOnly(host) + if drive, readOnly := road.Permit(); drive || readOnly != wantWatchOnly { + t.Fatalf("Permit() after WatchOnly = (%v, %q), want (false, %q)", drive, readOnly, wantWatchOnly) + } + + // A later Reconnecting state carries no permit and keeps the watch-only answer. + road.onState(livedoor.State{Kind: livedoor.Reconnecting}) + if drive, readOnly := road.Permit(); drive || readOnly != wantWatchOnly { + t.Fatalf("Permit() during Reconnecting after WatchOnly = (%v, %q), want (false, %q)", drive, readOnly, wantWatchOnly) + } + + // Live with Permit{Watch: true, Drive: true} allows driving. + road.onState(livedoor.State{ + Kind: livedoor.Live, + Permit: pair.Permit{Watch: true, Drive: true}, + }) + if drive, readOnly := road.Permit(); !drive || readOnly != "" { + t.Fatalf("Permit() after Live = (%v, %q), want (true, \"\")", drive, readOnly) + } + + // A later Reconnecting state carries no permit and keeps the drive-permitted answer. + road.onState(livedoor.State{Kind: livedoor.Reconnecting}) + if drive, readOnly := road.Permit(); !drive || readOnly != "" { + t.Fatalf("Permit() during Reconnecting after Live = (%v, %q), want (true, \"\")", drive, readOnly) + } +} + +// V24: Touch() returns before link.Touch finishes: with the held state Idle, Touch() does not call the link at all; with it Live, exactly one link.Touch call happens even after ten Touch() calls issued while the first is in flight. +func TestSyncRoadCoalescesInFlightTouchesAndSkipsTouchWhileIdle(t *testing.T) { + link := newTestLiveLink() + road := newSyncRoad(link, "Desktop") + t.Cleanup(road.Close) + + var calls atomic.Int32 + entered := make(chan struct{}) + release := make(chan struct{}) + finished := make(chan struct{}) + road.touch = func() { + if calls.Add(1) == 1 { + close(entered) + <-release + close(finished) + } + } + + // While Idle, Touch() is a no-op because Reconnect() is the door out of idle. + road.onState(livedoor.State{Kind: livedoor.Idle}) + for i := 0; i < 5; i++ { + road.Touch() + } + if got := calls.Load(); got != 0 { + t.Fatalf("link.Touch calls while Idle = %d, want 0", got) + } + + // While Live, ten Touch() calls while the first is in flight produce one link.Touch call. + road.onState(livedoor.State{Kind: livedoor.Live}) + road.Touch() + <-entered + for i := 0; i < 9; i++ { + road.Touch() + } + if got := calls.Load(); got != 1 { + t.Fatalf("link.Touch calls while first touch in flight = %d, want 1", got) + } + close(release) + <-finished + if got := calls.Load(); got != 1 { + t.Fatalf("link.Touch calls after first touch finished = %d, want 1", got) + } +} + +// V4: scrolling up on a live chat pages older entries through the agent's own connection when a pager is present and never calls the road. +func TestALiveAgentPagesOlderEntriesThroughItsOwnConnection(t *testing.T) { + road := newFakeLiveRoad() + wantEntries := []session.DisplayEntry{ + {Role: "user", Text: "older question"}, + {Role: "assistant", Text: "older answer", Answer: true}, + } + var gotBefore, gotLimit int + agent := &liveAgent{ + Agent: &fakeLivePeerAgent{}, + road: road, + cell: "cell-paged", + pager: func(_ context.Context, before, limit int) (remote.Page, error) { + gotBefore = before + gotLimit = limit + return remote.Page{ + Entries: wantEntries, + Base: 158, + More: true, + }, nil + }, + } + + entries, more, err := agent.Older(context.Background(), 160, 2) + if err != nil { + t.Fatalf("Older: %v", err) + } + if gotBefore != 160 || gotLimit != 2 { + t.Fatalf("pager called with (before=%d, limit=%d), want (160, 2)", gotBefore, gotLimit) + } + if !more || len(entries) != 2 || entries[0].Text != wantEntries[0].Text || entries[1].Text != wantEntries[1].Text { + t.Fatalf("Older() = (%+v, more=%v), want (%+v, true)", entries, more, wantEntries) + } + if got := agent.TranscriptBase(); got != 158 { + t.Fatalf("TranscriptBase() = %d, want 158", got) + } + if len(road.olderCalls) != 0 { + t.Fatalf("road.Older was called %d times when pager was set, want 0", len(road.olderCalls)) + } +} + +// V30, V41: the road the view reads is the road its link reports, on every draw, +// and a flip of the road with the same kind of state still wakes the surface so +// the next frame shows it; a road the link has not named reads as nothing. +func TestSyncRoadReadsTheRoadTheLinkReportsAndWakesTheSurfaceOnAFlip(t *testing.T) { + link := newTestLiveLink() + road := newSyncRoad(link, "Desktop") + t.Cleanup(road.Close) + + if got := road.Read().Road; got != "" { + t.Fatalf("before the link says anything the road reads %q, want nothing", got) + } + for _, step := range []string{"relay", "direct", "relay", "direct"} { + woke := road.Changed() + road.onState(livedoor.State{Kind: livedoor.Live, Road: step}) + select { + case <-woke: + default: + t.Fatalf("a flip to %q did not wake the surface", step) + } + if got := road.Read(); got.Road != step || got.Kind != tui3.LiveOn { + t.Fatalf("after a flip to %q the view reads %+v", step, got) + } + } +} diff --git a/cmd/codeaf/chatv3_live_test.go b/cmd/codeaf/chatv3_live_test.go new file mode 100644 index 0000000000..635203b3bb --- /dev/null +++ b/cmd/codeaf/chatv3_live_test.go @@ -0,0 +1,905 @@ +package main + +import ( + "context" + "errors" + "io" + "os" + "path/filepath" + "sync" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" + "github.com/Agent-Field/codeaf/internal/tui3" + "github.com/Agent-Field/codeaf/internal/viewcache" +) + +type fakeLiveClock struct { + mu sync.Mutex + now time.Time +} + +func newFakeLiveClock(t0 time.Time) *fakeLiveClock { + return &fakeLiveClock{now: t0} +} + +func (c *fakeLiveClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *fakeLiveClock) Advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = c.now.Add(d) +} + +type fakeOlderCall struct { + chat string + before int + limit int +} + +type fakeLiveRoad struct { + mu sync.Mutex + road string + drive bool + readOnly string + read tui3.LiveRead + changed chan struct{} + touched int + reconnected int + olderCalls []fakeOlderCall + olderEntries []session.DisplayEntry + olderBase int + olderMore bool + olderErr error + dialFn func(chat string) remote.Dialer +} + +func newFakeLiveRoad() *fakeLiveRoad { + return &fakeLiveRoad{ + road: "relay", + drive: true, + changed: make(chan struct{}), + } +} + +func (r *fakeLiveRoad) Dial(chat string) remote.Dialer { + r.mu.Lock() + fn := r.dialFn + r.mu.Unlock() + if fn != nil { + return fn(chat) + } + return nil +} + +func (r *fakeLiveRoad) Read() tui3.LiveRead { + r.mu.Lock() + defer r.mu.Unlock() + return r.read +} + +func (r *fakeLiveRoad) Changed() <-chan struct{} { + r.mu.Lock() + defer r.mu.Unlock() + return r.changed +} + +func (r *fakeLiveRoad) Touch() { + r.mu.Lock() + defer r.mu.Unlock() + r.touched++ +} + +func (r *fakeLiveRoad) touches() int { + r.mu.Lock() + defer r.mu.Unlock() + return r.touched +} + +func (r *fakeLiveRoad) Reconnect() { + r.mu.Lock() + defer r.mu.Unlock() + r.reconnected++ +} + +func (r *fakeLiveRoad) Road() string { + r.mu.Lock() + defer r.mu.Unlock() + return r.road +} + +func (r *fakeLiveRoad) Permit() (bool, string) { + r.mu.Lock() + defer r.mu.Unlock() + return r.drive, r.readOnly +} + +func (r *fakeLiveRoad) Older(_ context.Context, chat string, before, limit int) ([]session.DisplayEntry, int, bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.olderCalls = append(r.olderCalls, fakeOlderCall{chat: chat, before: before, limit: limit}) + return append([]session.DisplayEntry(nil), r.olderEntries...), r.olderBase, r.olderMore, r.olderErr +} + +type fakeLivePeerAgent struct { + quietAgent + mu sync.Mutex + model string + title string + entries []session.DisplayEntry + submitFn func(text string) (<-chan session.Event, error) + closes int + detaches int + interrupts int +} + +func (a *fakeLivePeerAgent) Model() string { + a.mu.Lock() + defer a.mu.Unlock() + if a.model != "" { + return a.model + } + return "model/live" +} + +func (a *fakeLivePeerAgent) Title() string { + a.mu.Lock() + defer a.mu.Unlock() + return a.title +} + +func (a *fakeLivePeerAgent) Transcript() []session.DisplayEntry { + a.mu.Lock() + defer a.mu.Unlock() + return append([]session.DisplayEntry(nil), a.entries...) +} + +func (a *fakeLivePeerAgent) setEntries(entries ...session.DisplayEntry) { + a.mu.Lock() + defer a.mu.Unlock() + a.entries = append([]session.DisplayEntry(nil), entries...) +} + +func (a *fakeLivePeerAgent) Submit(ctx context.Context, text string) (<-chan session.Event, error) { + a.mu.Lock() + fn := a.submitFn + a.mu.Unlock() + if fn != nil { + return fn(text) + } + return a.quietAgent.Submit(ctx, text) +} + +func (a *fakeLivePeerAgent) Close() error { + a.mu.Lock() + defer a.mu.Unlock() + a.closes++ + return nil +} + +func (a *fakeLivePeerAgent) Detach() error { + a.mu.Lock() + defer a.mu.Unlock() + a.detaches++ + return nil +} + +func (a *fakeLivePeerAgent) Interrupt() { + a.mu.Lock() + defer a.mu.Unlock() + a.interrupts++ +} + +func (a *fakeLivePeerAgent) InterruptFor(session.StopDoor) { + a.mu.Lock() + defer a.mu.Unlock() + a.interrupts++ +} + +func (a *fakeLivePeerAgent) counts() (closes, detaches, interrupts int) { + a.mu.Lock() + defer a.mu.Unlock() + return a.closes, a.detaches, a.interrupts +} + +// switchRemoteControlOn is the setting the door refuses without, the way a person +// switches it on from outside the window: the variable, which wins over the +// persisted row. +func switchRemoteControlOn(t *testing.T) { + t.Helper() + t.Setenv("CODEAF_REMOTE_CONTROL", "1") +} + +// V14: `codeaf chat --at` and `--host`, `codeaf serve` behave exactly as before, and remote control is off unless explicitly switched on. +func TestRemoteControlIsOffUnlessSwitchedOn(t *testing.T) { + t.Setenv("CODEAF_HOME", t.TempDir()) + t.Setenv("CODEAF_REMOTE_CONTROL", "") + _ = os.Unsetenv("CODEAF_REMOTE_CONTROL") + if remoteControlWanted() { + t.Fatal("remoteControlWanted() = true when CODEAF_REMOTE_CONTROL is unset") + } + for _, off := range []string{"", "0", "off", "OFF", "false", "no", "unexpected"} { + t.Setenv("CODEAF_REMOTE_CONTROL", off) + if remoteControlWanted() { + t.Fatalf("remoteControlWanted() = true for %q, want false", off) + } + } + for _, on := range []string{"1", "on", "ON", "true", "TRUE", "yes", " 1 "} { + t.Setenv("CODEAF_REMOTE_CONTROL", on) + if !remoteControlWanted() { + t.Fatalf("remoteControlWanted() = false for %q, want true", on) + } + } +} + +// V14, as the 2026-11-24 hand test corrected it: wireLive leaves Options.OpenLive nil only when no road is installed or on a hosted window. Remote control being off is NOT a reason to leave it nil, because the setting is turned on in a window that is already open (see TestAWindowStartedWithRemoteControlOffOpensLiveOnceItIsSwitchedOn). +func TestWireLiveLeavesOpenLiveNilWithoutARoadOrOnAHostedWindowAndWiresItWhateverTheSettingSays(t *testing.T) { + prevRoads := liveRoads + t.Cleanup(func() { liveRoads = prevRoads }) + t.Setenv("CODEAF_HOME", t.TempDir()) + t.Setenv("CODEAF_PROFILE_DIR", t.TempDir()) + + road := newFakeLiveRoad() + lookup := func(device, _ string) (liveRoad, string, bool) { + return road, "Desktop", true + } + + // Absent 1: no road adapter is installed, with remote control on. + t.Setenv("CODEAF_REMOTE_CONTROL", "1") + liveRoads = nil + var noRoadOpts tui3.Options + wireLive(&noRoadOpts, t.TempDir()) + if noRoadOpts.OpenLive != nil { + t.Fatal("wireLive wired OpenLive with liveRoads == nil") + } + + // Absent 2: the window is itself a hosted session, with remote control on. + liveRoads = lookup + hostedOpts := tui3.Options{Host: "devbox"} + wireLive(&hostedOpts, t.TempDir()) + if hostedOpts.OpenLive != nil || hostedOpts.RemoteControl != nil { + t.Fatal("wireLive wired a live opener on a hosted window") + } + + // Present, on: remote control is on, a road lookup is installed, and Host is empty. + var liveOpts tui3.Options + wireLive(&liveOpts, t.TempDir()) + if liveOpts.OpenLive == nil || liveOpts.RemoteControl == nil || !liveOpts.RemoteControl() { + t.Fatal("wireLive did not offer live views with remote control on and a road") + } + + // Present, off: the same wiring, and the live read says no. + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + var offOpts tui3.Options + wireLive(&offOpts, t.TempDir()) + if offOpts.OpenLive == nil || offOpts.RemoteControl == nil { + t.Fatal("wireLive left the opener unwired because remote control was off at start, so switching it on would need a restart") + } + if offOpts.RemoteControl() { + t.Fatal("the live read says remote control is on while it is off") + } +} + +// C1, C3: a window wired while remote control was off follows the setting from then on. The row /settings writes turns it on with no new wiring, and the environment variable, when set to a value, still wins over the row in both directions. +func TestAWindowStartedWithRemoteControlOffOpensLiveOnceItIsSwitchedOn(t *testing.T) { + prevRoads := liveRoads + t.Cleanup(func() { liveRoads = prevRoads }) + profile := t.TempDir() + t.Setenv("CODEAF_HOME", t.TempDir()) + t.Setenv("CODEAF_PROFILE_DIR", profile) + t.Setenv("CODEAF_REMOTE_CONTROL", "") + _ = os.Unsetenv("CODEAF_REMOTE_CONTROL") + liveRoads = func(string, string) (liveRoad, string, bool) { return newFakeLiveRoad(), "Desktop", true } + + var opts tui3.Options + wireLive(&opts, t.TempDir()) + if opts.OpenLive == nil || opts.RemoteControl == nil { + t.Fatal("the window was not wired for live views while remote control was off") + } + if opts.RemoteControl() { + t.Fatal("remote control reads on in a fresh profile") + } + + // What /settings does: the row is written, nothing else. + if err := applyRow(profile, config.KeyRemoteControl, "on"); err != nil { + t.Fatal(err) + } + if !opts.RemoteControl() { + t.Fatal("the window still reads remote control as off after the row was switched on") + } + if err := applyRow(profile, config.KeyRemoteControl, "off"); err != nil { + t.Fatal(err) + } + if opts.RemoteControl() { + t.Fatal("the window still reads remote control as on after the row was switched off") + } + + // C3: a set variable wins over the row, live, in both directions. The row is + // written first in each case, because a set variable makes the row read only. + t.Setenv("CODEAF_REMOTE_CONTROL", "1") + if !opts.RemoteControl() { + t.Fatal("CODEAF_REMOTE_CONTROL=1 did not win over an off row") + } + _ = os.Unsetenv("CODEAF_REMOTE_CONTROL") + if err := applyRow(profile, config.KeyRemoteControl, "on"); err != nil { + t.Fatal(err) + } + t.Setenv("CODEAF_REMOTE_CONTROL", "0") + if opts.RemoteControl() { + t.Fatal("CODEAF_REMOTE_CONTROL=0 did not win over an on row") + } +} + +// C2: while remote control is off the door refuses with the surface's own "nothing to open" answer, even for an offline chat whose last-seen copy it holds and which needs no road, and it opens that same chat once it is on. +func TestTheLiveDoorRefusesWhileRemoteControlIsOffAndOpensWhenItIsOn(t *testing.T) { + t.Setenv("CODEAF_PROFILE_DIR", t.TempDir()) + t.Setenv("CODEAF_REMOTE_CONTROL", "") + _ = os.Unsetenv("CODEAF_REMOTE_CONTROL") + home := t.TempDir() + cache := viewcache.Open(home) + if err := cache.SaveNow("dev-desktop", "chat-1", viewcache.Snapshot{ + Title: "Port the picker", + Entries: []session.DisplayEntry{{Role: "user", Text: "hello"}}, + }); err != nil { + t.Fatal(err) + } + road := newFakeLiveRoad() + door := &liveDoor{ + home: home, + cache: cache, + roads: func(string, string) (liveRoad, string, bool) { return road, "Desktop", true }, + } + row := chatlist.Row{Cell: "chat-1", Title: "Port the picker", Device: "Desktop", DeviceID: "dev-desktop", Status: chatlist.Off} + + if _, err := door.Open(context.Background(), row); !errors.Is(err, tui3.ErrNoLiveView) { + t.Fatalf("Open with remote control off = %v, want tui3.ErrNoLiveView", err) + } + t.Setenv("CODEAF_REMOTE_CONTROL", "1") + conv, err := door.Open(context.Background(), row) + if err != nil { + t.Fatalf("Open with remote control on: %v", err) + } + if conv.Agent == nil { + t.Fatal("Open with remote control on returned no agent") + } +} + +// Housekeeping decided on purpose: the last-seen copies are trimmed at start only when remote control is on then. With it off, wiring the opener must touch nothing on disk. +func TestWireLiveTrimsTheLastSeenCopiesOnlyWhenRemoteControlIsOnAtStart(t *testing.T) { + prevRoads := liveRoads + t.Cleanup(func() { liveRoads = prevRoads }) + t.Setenv("CODEAF_PROFILE_DIR", t.TempDir()) + liveRoads = func(string, string) (liveRoad, string, bool) { return newFakeLiveRoad(), "Desktop", true } + + // A temporary file a crashed write left behind, an hour old, is what Prune removes. + stray := func(home string) string { + dir := filepath.Join(home, "v3", "viewed", "dev-desktop") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, "stray.tmp") + if err := os.WriteFile(path, []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } + old := time.Now().Add(-time.Hour) + if err := os.Chtimes(path, old, old); err != nil { + t.Fatal(err) + } + return path + } + + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + offHome := t.TempDir() + offPath := stray(offHome) + var offOpts tui3.Options + wireLive(&offOpts, offHome) + time.Sleep(300 * time.Millisecond) + if _, err := os.Stat(offPath); err != nil { + t.Fatalf("wiring the opener with remote control off trimmed the copies: %v", err) + } + + t.Setenv("CODEAF_REMOTE_CONTROL", "1") + onHome := t.TempDir() + onPath := stray(onHome) + var onOpts tui3.Options + wireLive(&onOpts, onHome) + deadline := time.Now().Add(5 * time.Second) + for { + if _, err := os.Stat(onPath); os.IsNotExist(err) { + break + } + if time.Now().After(deadline) { + t.Fatal("wiring the opener with remote control on never trimmed the copies") + } + time.Sleep(20 * time.Millisecond) + } +} + +// V24: a viewer idle or backgrounded for 10 minutes detaches; a keypress or a running turn keeps the live link active through the surface seam alone, with no timer in cmd/codeaf. +func TestAKeypressOrARunningTurnKeepsTheLiveLinkActive(t *testing.T) { + road := newFakeLiveRoad() + peer := &fakeLivePeerAgent{} + turnCh := make(chan session.Event, 4) + peer.submitFn = func(string) (<-chan session.Event, error) { + return turnCh, nil + } + + switchRemoteControlOn(t) + door := &liveDoor{ + home: t.TempDir(), + cache: viewcache.Open(t.TempDir()), + roads: func(device, _ string) (liveRoad, string, bool) { + return road, "Desktop", device == "dev-desktop" + }, + dial: func(liveRoad, chatlist.Row) (tui3.Agent, remote.Welcome, error) { + return peer, remote.Welcome{Workspace: "/work/app", SessionFile: "/work/app/chat.jsonl"}, nil + }, + } + + row := chatlist.Row{DeviceID: "dev-desktop", Device: "Desktop", Cell: "cell-1", Status: chatlist.Running} + conv, err := door.Open(context.Background(), row) + if err != nil { + t.Fatalf("open live conversation: %v", err) + } + if conv.Live == nil || conv.Live.Touch == nil { + t.Fatal("live conversation has no Touch seam") + } + if got := road.touches(); got != 0 { + t.Fatalf("road was touched %d times on open without a call, want 0", got) + } + + // A keypress touches the seam once per call. + conv.Live.Touch() + if got := road.touches(); got != 1 { + t.Fatalf("touches after one seam Touch = %d, want 1", got) + } + + // Starting a running turn on the agent does not touch the road on its own; + // activity while a turn runs reaches the road only through the surface seam. + stream, err := conv.Agent.Submit(context.Background(), "keep working") + if err != nil { + t.Fatalf("submit turn: %v", err) + } + turnCh <- session.Event{Kind: session.EventTextDelta, Text: "partial"} + if ev := <-stream; ev.Text != "partial" { + t.Fatalf("stream event = %+v, want partial delta", ev) + } + if got := road.touches(); got != 1 { + t.Fatalf("running turn touched the road without the surface seam: got %d, want 1", got) + } + conv.Live.Touch() + if got := road.touches(); got != 2 { + t.Fatalf("touches after surface turn Touch = %d, want 2", got) + } + close(turnCh) + for range stream { + } + if got := road.touches(); got != 2 { + t.Fatalf("touches after turn finished = %d, want 2", got) + } +} + +// V27: an offline host with relay storage off opens the viewer's own last-seen copy read-only with a dated banner and sends nothing. +func TestAnOfflineComputerOpensTheLastSeenCopyAndSendsNothing(t *testing.T) { + home := t.TempDir() + clk := newFakeLiveClock(time.Date(2026, 11, 23, 14, 2, 0, 0, time.UTC)) + cache := viewcache.OpenWith(home, clk) + road := newFakeLiveRoad() + road.dialFn = func(string) remote.Dialer { + return func() (io.ReadWriteCloser, error) { + return nil, errors.New("Desktop is not running this chat right now.") + } + } + + switchRemoteControlOn(t) + door := &liveDoor{ + home: home, + cache: cache, + clock: clk, + roads: func(device, _ string) (liveRoad, string, bool) { + return road, "Desktop", device == "dev-desktop" + }, + } + + row := chatlist.Row{DeviceID: "dev-desktop", Device: "Desktop", Cell: "cell-offline", Status: chatlist.Running}.Quiet() + if _, err := door.Open(context.Background(), row); !errors.Is(err, tui3.ErrNoLiveView) { + t.Fatalf("offline computer without snapshot returned %v, want ErrNoLiveView", err) + } + + wantEntries := []session.DisplayEntry{ + {Role: "user", Text: "check the build"}, + {Role: "assistant", Text: "all packages compile cleanly", Answer: true}, + } + seenAt := clk.Now() + if err := cache.SaveNow("dev-desktop", "cell-offline", viewcache.Snapshot{ + Host: "dev-desktop", + HostName: "Desktop", + Chat: "cell-offline", + Title: "Build check", + Model: "model/offline", + Workspace: "/work/build", + SeenAt: seenAt, + Entries: wantEntries, + }); err != nil { + t.Fatalf("save snapshot: %v", err) + } + + conv, err := door.Open(context.Background(), row) + if err != nil { + t.Fatalf("open offline conversation with snapshot: %v", err) + } + if conv.Live == nil || conv.Live.Read == nil { + t.Fatal("offline conversation is missing Live.Read") + } + if got := conv.Live.Read(); got.Kind != tui3.LiveCopy || !got.SeenAt.Equal(seenAt) { + t.Fatalf("Live.Read() = %+v, want Kind=LiveCopy SeenAt=%v", got, seenAt) + } + if got := conv.Agent.Transcript(); len(got) != len(wantEntries) || got[0].Text != wantEntries[0].Text || got[1].Text != wantEntries[1].Text { + t.Fatalf("Transcript() = %+v, want %+v", got, wantEntries) + } + if got := conv.Agent.Model(); got != "model/offline" { + t.Fatalf("Model() = %q, want model/offline", got) + } + wantRefusal := chatlist.LiveNotSentOffline("Desktop") + if _, err := conv.Agent.Submit(context.Background(), "try sending"); err == nil || err.Error() != wantRefusal { + t.Fatalf("Submit() error = %v, want %q", err, wantRefusal) + } + if _, err := conv.Agent.SubmitImage(context.Background(), "try image", nil); err == nil || err.Error() != wantRefusal { + t.Fatalf("SubmitImage() error = %v, want %q", err, wantRefusal) + } + if conv.Link == nil || conv.Link.SendRefusal == nil || conv.Link.SendRefusal() != wantRefusal { + t.Fatalf("Link.SendRefusal() = %v, want %q", conv.Link, wantRefusal) + } +} + +// V27: the viewer's last-seen copy is saved on the quiet beat after a turn ends and on Detach, at most once per viewcache.WriteEvery and never per streaming delta. +func TestTheLiveCopyIsSavedAfterATurnAndOnDetachNeverPerDelta(t *testing.T) { + home := t.TempDir() + t0 := time.Date(2026, 11, 23, 15, 0, 0, 0, time.UTC) + clk := newFakeLiveClock(t0) + cache := viewcache.OpenWith(home, clk) + road := newFakeLiveRoad() + peer := &fakeLivePeerAgent{title: "Cache pacing", model: "model/paced"} + + var currentTurn chan session.Event + peer.submitFn = func(string) (<-chan session.Event, error) { + currentTurn = make(chan session.Event, 16) + return currentTurn, nil + } + + switchRemoteControlOn(t) + door := &liveDoor{ + home: home, + cache: cache, + clock: clk, + roads: func(device, _ string) (liveRoad, string, bool) { + return road, "Desktop", device == "dev-desktop" + }, + dial: func(liveRoad, chatlist.Row) (tui3.Agent, remote.Welcome, error) { + return peer, remote.Welcome{Workspace: "/work/paced", SessionFile: "/work/paced/chat.jsonl"}, nil + }, + } + + row := chatlist.Row{DeviceID: "dev-desktop", Device: "Desktop", Cell: "cell-paced", Status: chatlist.Running} + conv, err := door.Open(context.Background(), row) + if err != nil { + t.Fatalf("open live conversation: %v", err) + } + + // Turn 1: stream many deltas; no snapshot may be written before the turn ends. + stream1, err := conv.Agent.Submit(context.Background(), "turn one") + if err != nil { + t.Fatalf("submit turn 1: %v", err) + } + peer.setEntries( + session.DisplayEntry{Role: "user", Text: "turn one"}, + session.DisplayEntry{Role: "assistant", Text: "reply one", Answer: true}, + ) + for i := 0; i < 10; i++ { + currentTurn <- session.Event{Kind: session.EventTextDelta, Text: "delta"} + <-stream1 + if _, ok := cache.Load("dev-desktop", "cell-paced"); ok { + t.Fatalf("cache wrote on delta %d while turn 1 was still running", i) + } + } + currentTurn <- session.Event{Kind: session.EventTurnDone} + close(currentTurn) + for range stream1 { + } + + snap1, ok := cache.Load("dev-desktop", "cell-paced") + if !ok { + t.Fatal("cache did not save after turn 1 ended") + } + if len(snap1.Entries) != 2 || !snap1.SeenAt.Equal(t0) { + t.Fatalf("snapshot after turn 1 = %+v, want 2 entries at %v", snap1, t0) + } + + // Turn 2 ends before viewcache.WriteEvery has elapsed: throttled, no disk write. + clk.Advance(viewcache.WriteEvery / 2) + stream2, err := conv.Agent.Submit(context.Background(), "turn two") + if err != nil { + t.Fatalf("submit turn 2: %v", err) + } + peer.setEntries( + session.DisplayEntry{Role: "user", Text: "turn one"}, + session.DisplayEntry{Role: "assistant", Text: "reply one", Answer: true}, + session.DisplayEntry{Role: "user", Text: "turn two"}, + session.DisplayEntry{Role: "assistant", Text: "reply two", Answer: true}, + ) + for i := 0; i < 8; i++ { + currentTurn <- session.Event{Kind: session.EventTextDelta, Text: "delta"} + <-stream2 + } + currentTurn <- session.Event{Kind: session.EventTurnDone} + close(currentTurn) + for range stream2 { + } + + snap2, ok := cache.Load("dev-desktop", "cell-paced") + if !ok || len(snap2.Entries) != 2 || !snap2.SeenAt.Equal(t0) { + t.Fatalf("cache wrote inside WriteEvery window: got %+v, want turn 1 snapshot at %v", snap2, t0) + } + + // Detach writes immediately via SaveNow even inside the WriteEvery window. + clk.Advance(100 * time.Millisecond) + detachAt := clk.Now() + detacher, ok := conv.Agent.(interface{ Detach() error }) + if !ok { + t.Fatal("liveAgent does not implement Detach()") + } + if err := detacher.Detach(); err != nil { + t.Fatalf("Detach: %v", err) + } + snap3, ok := cache.Load("dev-desktop", "cell-paced") + if !ok || len(snap3.Entries) != 4 || !snap3.SeenAt.Equal(detachAt) { + t.Fatalf("snapshot after Detach = %+v, want 4 entries at %v", snap3, detachAt) + } +} + +// V1: closing or detaching a live conversation closes only the local Roam client and never asks the other computer to end its chat. +func TestClosingALiveConversationNeverEndsTheChatOnTheOtherComputer(t *testing.T) { + peer := &fakeLivePeerAgent{} + var releaseCalls int + var mu sync.Mutex + hostSession := remote.NewSession(&remote.Engine{ + Agent: peer, + Workspace: "/srv/desktop/app", + SessionFile: "/srv/desktop/app/chat.jsonl", + ReleaseOnLeave: func(remote.WrappedAgent) bool { + mu.Lock() + defer mu.Unlock() + releaseCalls++ + return true + }, + }, true) + + road := newFakeLiveRoad() + road.dialFn = func(string) remote.Dialer { + return func() (io.ReadWriteCloser, error) { + surface, engine := remote.Pipe() + guard.Go("test/live-host-serve", func() { + _ = remote.ServeAttach(engine, engine, remote.AttachOptions{ + Open: func(remote.Hello) (*remote.Session, error) { + return hostSession, nil + }, + }) + _ = engine.Close() + }) + return surface, nil + } + } + + switchRemoteControlOn(t) + door := &liveDoor{ + home: t.TempDir(), + cache: viewcache.Open(t.TempDir()), + roads: func(device, _ string) (liveRoad, string, bool) { + return road, "Desktop", device == "dev-desktop" + }, + } + row := chatlist.Row{DeviceID: "dev-desktop", Device: "Desktop", Cell: "cell-keep", Status: chatlist.Running} + + // Close the first live view. + conv1, err := door.Open(context.Background(), row) + if err != nil { + t.Fatalf("open first live conversation: %v", err) + } + if err := conv1.Agent.Close(); err != nil { + t.Fatalf("Close live conversation: %v", err) + } + + // Open a second live view of the same chat and Detach it. + conv2, err := door.Open(context.Background(), row) + if err != nil { + t.Fatalf("open second live conversation: %v", err) + } + detacher, ok := conv2.Agent.(interface{ Detach() error }) + if !ok { + t.Fatal("liveAgent does not implement Detach()") + } + if err := detacher.Detach(); err != nil { + t.Fatalf("Detach live conversation: %v", err) + } + + closes, detaches, interrupts := peer.counts() + mu.Lock() + releases := releaseCalls + mu.Unlock() + if closes != 0 || detaches != 0 || interrupts != 0 || releases != 0 { + t.Fatalf("other computer saw closes=%d detaches=%d interrupts=%d releases=%d, want all 0", closes, detaches, interrupts, releases) + } +} + +// V4: scrolling up on a live chat pages older entries from the host through the road and updates TranscriptBase. +func TestALiveAgentPagesOlderEntriesThroughTheRoad(t *testing.T) { + road := newFakeLiveRoad() + peer := &fakeLivePeerAgent{} + switchRemoteControlOn(t) + door := &liveDoor{ + home: t.TempDir(), + cache: viewcache.Open(t.TempDir()), + roads: func(device, _ string) (liveRoad, string, bool) { + return road, "Desktop", device == "dev-desktop" + }, + dial: func(liveRoad, chatlist.Row) (tui3.Agent, remote.Welcome, error) { + return peer, remote.Welcome{Workspace: "/work/app", SessionFile: "/work/app/chat.jsonl"}, nil + }, + } + + row := chatlist.Row{DeviceID: "dev-desktop", Device: "Desktop", Cell: "cell-older", Status: chatlist.Running} + conv, err := door.Open(context.Background(), row) + if err != nil { + t.Fatalf("open live conversation: %v", err) + } + older, ok := conv.Agent.(tui3.OlderReader) + if !ok { + t.Fatal("live conversation agent does not satisfy tui3.OlderReader") + } + if got := older.TranscriptBase(); got != 0 { + t.Fatalf("initial TranscriptBase() = %d, want 0", got) + } + + road.olderEntries = []session.DisplayEntry{ + {Role: "user", Text: "page one user"}, + {Role: "assistant", Text: "page one reply", Answer: true}, + } + road.olderBase = 120 + road.olderMore = true + + entries, more, err := older.Older(context.Background(), 160, 40) + if err != nil { + t.Fatalf("first Older: %v", err) + } + if !more || len(entries) != 2 || entries[0].Text != "page one user" { + t.Fatalf("first Older = (%+v, more=%v), want 2 entries and more=true", entries, more) + } + if got := older.TranscriptBase(); got != 120 { + t.Fatalf("TranscriptBase() after first page = %d, want 120", got) + } + if len(road.olderCalls) != 1 || road.olderCalls[0] != (fakeOlderCall{chat: "cell-older", before: 160, limit: 40}) { + t.Fatalf("olderCalls = %+v, want [{chat:cell-older before:160 limit:40}]", road.olderCalls) + } + + road.olderEntries = []session.DisplayEntry{ + {Role: "user", Text: "earliest user"}, + } + road.olderBase = 0 + road.olderMore = false + + entries, more, err = older.Older(context.Background(), 120, 120) + if err != nil { + t.Fatalf("second Older: %v", err) + } + if more || len(entries) != 1 || entries[0].Text != "earliest user" { + t.Fatalf("second Older = (%+v, more=%v), want 1 entry and more=false", entries, more) + } + if got := older.TranscriptBase(); got != 0 { + t.Fatalf("TranscriptBase() after reaching the start = %d, want 0", got) + } +} + +// V27: moving a chat here forgets its cached copy, and removing a computer forgets that computer's entire cache folder. +func TestMovingAChatHereForgetsItsLastSeenCopy(t *testing.T) { + home := t.TempDir() + cache := viewcache.Open(home) + for _, cell := range []string{"cell-moved", "cell-remaining"} { + if err := cache.SaveNow("dev-desktop", cell, viewcache.Snapshot{ + Host: "dev-desktop", + HostName: "Desktop", + Chat: cell, + Entries: []session.DisplayEntry{{Role: "user", Text: cell}}, + }); err != nil { + t.Fatalf("save %s: %v", cell, err) + } + } + + forgetViewedChatEverywhere(home, "cell-moved") + if _, ok := cache.Load("dev-desktop", "cell-moved"); ok { + t.Fatal("forgetViewedChatEverywhere left cell-moved in the viewer cache") + } + if _, ok := cache.Load("dev-desktop", "cell-remaining"); !ok { + t.Fatal("forgetViewedChatEverywhere removed another chat's copy") + } + + // The window that moved the chat does not know which computer the copy was + // last seen on, so a second computer's copy of the same chat goes too. + if err := cache.SaveNow("dev-laptop", "cell-moved", viewcache.Snapshot{Host: "dev-laptop", Chat: "cell-moved", Entries: []session.DisplayEntry{{Role: "user", Text: "x"}}}); err != nil { + t.Fatalf("save second computer's copy: %v", err) + } + forgetViewedChatEverywhere(home, "cell-moved") + if _, ok := cache.Load("dev-laptop", "cell-moved"); ok { + t.Fatal("forgetViewedChatEverywhere left another computer's copy of the moved chat") + } + // A takeover built without a home (every test's literal) forgets nothing and does not fail. + takeover{}.movedHere("cell-remaining") + if _, ok := cache.Load("dev-desktop", "cell-remaining"); !ok { + t.Fatal("a takeover with no home removed a copy") + } + + forgetViewed(home, "dev-desktop") + if _, ok := cache.Load("dev-desktop", "cell-remaining"); ok { + t.Fatal("forgetViewed left cell-remaining in the viewer cache") + } + hostDir := filepath.Join(home, "v3", "viewed", "dev-desktop") + if _, err := os.Stat(hostDir); !os.IsNotExist(err) { + t.Fatalf("forgetViewed left host folder %s on disk (err=%v)", hostDir, err) + } +} + +// V13 of the phase 2 contract, a phase 1 completion: a message typed just before +// the link dropped is sent again once, and not lost. The client does that only +// when its policy says ResendUnanswered, and nothing but this door sets the +// policy of a live view, so the test reads what the door asks the client to do. +func TestTheLiveRoamingTurnsOnResendUnansweredTheLineBoundAndTheGapHandler(t *testing.T) { + road := newFakeLiveRoad() + dialer := remote.Dialer(func() (io.ReadWriteCloser, error) { return nil, errors.New("no host in this test") }) + road.dialFn = func(string) remote.Dialer { return dialer } + var asked remote.Roaming + stop := errors.New("stop here: the policy is all this test reads") + switchRemoteControlOn(t) + door := &liveDoor{ + home: t.TempDir(), + roads: func(device, name string) (liveRoad, string, bool) { return road, "desktop", true }, + roam: func(host string, hello remote.Hello, roaming remote.Roaming) (*remote.Client, error) { + asked = roaming + if hello.Window { + t.Errorf("the viewer sent a windowed hello, which the host's router would have to rewrite") + } + return nil, stop + }, + } + _, err := door.Open(t.Context(), chatlist.Row{Cell: "cell-1", DeviceID: "dev_desktop", Device: "desktop", Status: chatlist.Running}) + if !errors.Is(err, stop) { + t.Fatalf("Open = %v, want the error the test's dial returned", err) + } + if asked.Dial == nil { + t.Errorf("the live view asks to redial by no dialler at all") + } + if !asked.ResendUnanswered { + t.Errorf("a message typed just before the link drops is not resent after the redial: ResendUnanswered is off") + } + if asked.MaxLine != livedoor.MaxLine { + t.Errorf("the viewer reads lines of at most %d bytes, want the live door's own %d", asked.MaxLine, livedoor.MaxLine) + } + if !asked.SpreadReturns { + t.Errorf("a live view is dialled through a relay, so its returns must be spread (V22): SpreadReturns is off") + } + if asked.Window != 30*time.Minute { + t.Errorf("the live view keeps trying for %v after a drop, want 30 minutes for a laptop that comes back from sleep", asked.Window) + } + if asked.OnGap == nil { + t.Fatalf("a replay that lost events goes unnoticed: OnGap is nil") + } + asked.OnGap(remote.Gap{Stream: 3, Have: 10, First: 40}) +} diff --git a/cmd/codeaf/chatv3_permit.go b/cmd/codeaf/chatv3_permit.go new file mode 100644 index 0000000000..05bd99e3d9 --- /dev/null +++ b/cmd/codeaf/chatv3_permit.go @@ -0,0 +1,195 @@ +package main + +import ( + "context" + "slices" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/tui3" +) + +// permitAskEvery is how often Home may ask the permit book again whether the +// one-time question is due. The answer changes rarely (when this computer first +// reads its roster, or when the person answers), so a slow read is enough, and +// it keeps the update loop from ever waiting on a file. +const permitAskEvery = 30 * time.Second + +// permitAsker is the terminal's [tui3.PermitAsker]: the one question Home asks, +// once, of a person who paired computers before remote control existed, whether +// those computers may now also type into chats here. +// +// IT ANSWERS FROM MEMORY. Home asks on every build of its panel, which is the +// update loop, so [permitAsker.AskOnce] returns what the last background read +// found and starts the next read in the background when one is due. The read is +// the permit book and the device list, both off the loop. +type permitAsker struct { + // who is this computer's account id, "" when it has none yet. + who func() string + devices func(context.Context) ([]tui3.DeviceRow, error) + book func() *pair.PermitBook + now func() time.Time + // spawn starts background work. It is guard.Go outside tests. + spawn func(name string, fn func()) + + mu sync.Mutex + identity string + names, ids []string + ask bool + answered bool + refreshing bool + checkedAt time.Time +} + +// newPermitAsker returns the asker over this computer's own door, or nil when +// there is no door. REMOTE CONTROL IS ASKED EACH TIME, never at start: a person +// turns it on in /settings in a window that is already open, and the one +// question about older pairings has to come with it, not at the next launch. +// With it off the asker says there is nothing to ask and does nothing else, so +// Home is exactly what it was before the setting existed. +func newPermitAsker(door *approvalsDoor) tui3.PermitAsker { + if door == nil { + return nil + } + return whenRemoteControlIsOn{asker: newDoorPermitAsker(door), on: config.RemoteControlOn} +} + +// whenRemoteControlIsOn asks the question only while remote control is on. It +// is a wrapper and not a check inside the asker so that, with the setting off, +// no roster is read, no book is opened and no background work is started. +type whenRemoteControlIsOn struct { + asker tui3.PermitAsker + on func() bool +} + +func (w whenRemoteControlIsOn) AskOnce() ([]string, bool) { + if !w.on() { + return nil, false + } + return w.asker.AskOnce() +} + +func (w whenRemoteControlIsOn) Answer(allow bool) error { return w.asker.Answer(allow) } + +var _ tui3.PermitAsker = whenRemoteControlIsOn{} + +func newDoorPermitAsker(door *approvalsDoor) *permitAsker { + dir := door.dir + return &permitAsker{ + who: func() string { + id, err := identity.Load(dir) + if err != nil { + return "" + } + return id.ID() + }, + devices: door.Devices, book: door.book, now: time.Now, spawn: guard.Go, + } +} + +// AskOnce says whether Home should ask now and about which computers. +func (p *permitAsker) AskOnce() ([]string, bool) { + names, ask, due := p.snapshot() + if due { + p.spawn("chatv3/permit-ask", p.refresh) + } + return names, ask +} + +// snapshot is what the asker holds now, and whether a fresh reading is due, in +// which case it also marks one as under way so that only one is started. +func (p *permitAsker) snapshot() (names []string, ask, due bool) { + p.mu.Lock() + defer p.mu.Unlock() + due = !p.answered && !p.refreshing && (p.checkedAt.IsZero() || p.now().Sub(p.checkedAt) >= permitAskEvery) + if due { + p.refreshing = true + } + return slices.Clone(p.names), p.ask, due +} + +// refresh reads the book and the roster once and keeps what they say. +func (p *permitAsker) refresh() { + ctx, cancel := context.WithTimeout(context.Background(), approveStep) + defer cancel() + names, ids, ask, who := p.read(ctx) + p.mu.Lock() + defer p.mu.Unlock() + p.refreshing = false + p.checkedAt = p.now() + if p.answered { + return + } + p.identity, p.names, p.ids, p.ask = who, names, ids, ask +} + +// read says whether the one-time question is due and about whom. It is due when +// the book holds a legacy snapshot nobody has answered for and at least one of +// those computers is still on the roster. +func (p *permitAsker) read(ctx context.Context) (names, ids []string, ask bool, who string) { + who = p.who() + if who == "" { + return nil, nil, false, "" + } + book := p.book() + if !book.NeedsAsk(who) { + return nil, nil, false, who + } + rows, err := p.devices(ctx) + if err != nil { + return nil, nil, false, who + } + for _, row := range rows { + if row.Self || row.Revoked || row.ID == "" { + continue + } + if _, class := book.For(who, row.ID); class != pair.ClassLegacy { + continue + } + ids = append(ids, row.ID) + names = append(names, row.Name) + } + return names, ids, len(ids) > 0, who +} + +// Answer records the person's decision and ends the question: true lets the +// older computers type, false keeps them watching. The surface calls it on the +// update loop, so the memory changes at once and the book is written in the +// background; if that write fails the question comes back, because a decision +// that was not kept is a decision not made, and the safe state, watching only, +// is what stands until then. +func (p *permitAsker) Answer(allow bool) error { + who, ids := p.settle() + if who == "" { + return nil + } + p.spawn("chatv3/permit-answer", func() { + if err := p.book().Asked(who, allow, ids); err != nil { + p.reopen() + } + }) + return nil +} + +// settle ends the question in memory and answers who was asked and about which +// computers. +func (p *permitAsker) settle() (who string, ids []string) { + p.mu.Lock() + defer p.mu.Unlock() + who, ids = p.identity, slices.Clone(p.ids) + p.answered, p.ask, p.names, p.ids = true, false, nil, nil + return who, ids +} + +// reopen brings the question back, because the decision was not written down. +func (p *permitAsker) reopen() { + p.mu.Lock() + defer p.mu.Unlock() + p.answered, p.checkedAt = false, time.Time{} +} + +var _ tui3.PermitAsker = (*permitAsker)(nil) diff --git a/cmd/codeaf/chatv3_permit_test.go b/cmd/codeaf/chatv3_permit_test.go new file mode 100644 index 0000000000..22cd8f8ff7 --- /dev/null +++ b/cmd/codeaf/chatv3_permit_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "context" + "errors" + "os" + "path/filepath" + "reflect" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/tui3" +) + +const permitTestIdentity = "id_account" + +// permitBookWithLegacy is a host book whose snapshot names two older pairings +// (this computer and "dev_old"); "dev_new" paired after it, so it stands outside +// the snapshot. +func permitBookWithLegacy(t *testing.T) *pair.PermitBook { + t.Helper() + book := pair.PermitsAt(filepath.Join(t.TempDir(), "permits.json")) + if err := book.SnapshotLegacy(permitTestIdentity, []string{"dev_self", "dev_old", "dev_gone"}); err != nil { + t.Fatalf("snapshot: %v", err) + } + return book +} + +func permitRoster() []tui3.DeviceRow { + return []tui3.DeviceRow{ + {ID: "dev_self", Name: "this mac", Self: true}, + {ID: "dev_old", Name: "tower"}, + {ID: "dev_new", Name: "desk"}, + {ID: "dev_gone", Name: "attic", Revoked: true}, + } +} + +// permitAskerOver builds an asker whose background work waits to be run by the +// test, so a test decides exactly when the read and the write happen. +func permitAskerOver(book *pair.PermitBook, rows []tui3.DeviceRow, clock func() time.Time) (*permitAsker, *[]func()) { + var queued []func() + return &permitAsker{ + who: func() string { return permitTestIdentity }, + devices: func(context.Context) ([]tui3.DeviceRow, error) { return rows, nil }, + book: func() *pair.PermitBook { return book }, + now: clock, + spawn: func(_ string, fn func()) { queued = append(queued, fn) }, + }, &queued +} + +func runQueued(queued *[]func()) { + work := *queued + *queued = nil + for _, fn := range work { + fn() + } +} + +// V25: Home never waits for the answer. The first ask returns "not due" at +// once and starts exactly one background read; asking again while that read is +// out starts no second one. +func TestHomeAsksTheBookInTheBackgroundAndNeverWaitsForIt(t *testing.T) { + asker, queued := permitAskerOver(permitBookWithLegacy(t), permitRoster(), time.Now) + if names, ask := asker.AskOnce(); ask || len(names) != 0 { + t.Fatalf("the first ask answered (%v, %t) before anything was read", names, ask) + } + if len(*queued) != 1 { + t.Fatalf("the first ask started %d reads, want 1", len(*queued)) + } + asker.AskOnce() + asker.AskOnce() + if len(*queued) != 1 { + t.Fatalf("asking while a read was out started %d reads, want still 1", len(*queued)) + } +} + +// V25: once read, Home asks about the older computers by name, and only those: +// not this computer, not one removed, not one paired after remote control. +func TestTheQuestionNamesOnlyTheOlderComputersStillOnTheRoster(t *testing.T) { + asker, queued := permitAskerOver(permitBookWithLegacy(t), permitRoster(), time.Now) + asker.AskOnce() + runQueued(queued) + names, ask := asker.AskOnce() + if !ask || !reflect.DeepEqual(names, []string{"tower"}) { + t.Fatalf("after the read Home asks (%v, %t), want (tower, true)", names, ask) + } +} + +// V25: answering yes lets the older computers type and never asks again; the +// book keeps the decision. +func TestAnsweringYesLetsTheOlderComputersTypeAndEndsTheQuestion(t *testing.T) { + book := permitBookWithLegacy(t) + asker, queued := permitAskerOver(book, permitRoster(), time.Now) + asker.AskOnce() + runQueued(queued) + if err := asker.Answer(true); err != nil { + t.Fatalf("answer: %v", err) + } + if names, ask := asker.AskOnce(); ask || len(names) != 0 { + t.Fatalf("Home still asks (%v, %t) the moment after the answer", names, ask) + } + runQueued(queued) + if got, _ := book.For(permitTestIdentity, "dev_old"); !got.Drive || !got.Watch { + t.Fatalf("an older computer after yes may %+v, want watch and type", got) + } + if got, _ := book.For(permitTestIdentity, "dev_gone"); got.Drive { + t.Fatal("yes gave typing to a computer that was not on the roster") + } + if book.NeedsAsk(permitTestIdentity) { + t.Fatal("the book would ask again after an answer") + } +} + +// V25 / V11: answering no keeps the older computers watching only, and ends the +// question just the same. +func TestAnsweringNoKeepsTheOlderComputersWatchingAndEndsTheQuestion(t *testing.T) { + book := permitBookWithLegacy(t) + asker, queued := permitAskerOver(book, permitRoster(), time.Now) + asker.AskOnce() + runQueued(queued) + if err := asker.Answer(false); err != nil { + t.Fatalf("answer: %v", err) + } + runQueued(queued) + got, class := book.For(permitTestIdentity, "dev_old") + if got.Drive || class != pair.ClassLegacy { + t.Fatalf("an older computer after no may %+v (%v), want watch only and still older", got, class) + } + if book.NeedsAsk(permitTestIdentity) { + t.Fatal("the book would ask again after no") + } +} + +// V25: a decision that could not be written does not end the question; Home +// asks again, and the older computers keep watching only until it is. +func TestAnAnswerThatCouldNotBeKeptBringsTheQuestionBack(t *testing.T) { + // A book at a path whose parent is a file cannot be written. + blocker := filepath.Join(t.TempDir(), "blocker") + if err := os.WriteFile(blocker, nil, 0o600); err != nil { + t.Fatal(err) + } + broken := pair.PermitsAt(filepath.Join(blocker, "permits.json")) + clock := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) + asker, queued := permitAskerOver(broken, permitRoster(), func() time.Time { return clock }) + asker.mu.Lock() + asker.ask, asker.names, asker.ids, asker.identity = true, []string{"tower"}, []string{"dev_old"}, permitTestIdentity + asker.checkedAt = clock + asker.mu.Unlock() + if err := asker.Answer(true); err != nil { + t.Fatalf("answer: %v", err) + } + runQueued(queued) + clock = clock.Add(permitAskEvery) + asker.AskOnce() + if len(*queued) != 1 { + t.Fatalf("after a failed write the next ask started %d reads, want 1 so the question can come back", len(*queued)) + } +} + +// V25: with nothing to ask about (no snapshot, or no older computer left on the +// roster) Home is never asked. +func TestHomeIsNotAskedWhenNoOlderComputerIsLeft(t *testing.T) { + onlyNew := []tui3.DeviceRow{{ID: "dev_self", Name: "this mac", Self: true}, {ID: "dev_new", Name: "desk"}} + asker, queued := permitAskerOver(permitBookWithLegacy(t), onlyNew, time.Now) + asker.AskOnce() + runQueued(queued) + if names, ask := asker.AskOnce(); ask || len(names) != 0 { + t.Fatalf("Home asks (%v, %t) with no older computer on the roster", names, ask) + } + empty := pair.PermitsAt(filepath.Join(t.TempDir(), "permits.json")) + asker, queued = permitAskerOver(empty, permitRoster(), time.Now) + asker.AskOnce() + runQueued(queued) + if _, ask := asker.AskOnce(); ask { + t.Fatal("Home asks with no legacy snapshot in the book") + } +} + +// V25: a roster that cannot be read asks nothing now and is tried again later. +func TestAnUnreadableRosterAsksNothingNow(t *testing.T) { + asker, queued := permitAskerOver(permitBookWithLegacy(t), nil, time.Now) + asker.devices = func(context.Context) ([]tui3.DeviceRow, error) { return nil, errors.New("directory did not answer") } + asker.AskOnce() + runQueued(queued) + if _, ask := asker.AskOnce(); ask { + t.Fatal("Home asked from a roster it could not read") + } +} + +// V14, as the 2026-11-24 hand test corrected it: remote control is switched on in +// a window that is already open, so the asker is there whatever the setting says +// at start, and it asks only while the setting is on. Off, it says there is +// nothing to ask and starts no work, which is Home exactly as it was. +func TestTheOneTimeQuestionFollowsRemoteControlWhileTheWindowIsOpen(t *testing.T) { + profile := t.TempDir() + t.Setenv("CODEAF_HOME", t.TempDir()) + t.Setenv("CODEAF_PROFILE_DIR", profile) + t.Setenv("CODEAF_REMOTE_CONTROL", "") + _ = os.Unsetenv("CODEAF_REMOTE_CONTROL") + if got := newPermitAsker(nil); got != nil { + t.Fatalf("newPermitAsker with no door = %T, want nil", got) + } + + // The real wrapper over a real door, with the book's work queued by the test. + got := newPermitAsker(newApprovalsDoor(t.TempDir())) + gate, ok := got.(whenRemoteControlIsOn) + if !ok { + t.Fatalf("newPermitAsker answered %T, want the asker that follows the setting", got) + } + if gate.on() { + t.Fatal("the gate reads remote control as on in a fresh profile") + } + if err := applyRow(profile, config.KeyRemoteControl, "on"); err != nil { + t.Fatal(err) + } + if !gate.on() { + t.Fatal("the gate still reads remote control as off after /settings switched it on") + } + + // What the gate does with each answer. + asker, queued := permitAskerOver(permitBookWithLegacy(t), permitRoster(), time.Now) + on := false + gated := whenRemoteControlIsOn{asker: asker, on: func() bool { return on }} + if names, ask := gated.AskOnce(); ask || len(names) != 0 || len(*queued) != 0 { + t.Fatalf("with remote control off the asker answered (%v, %t) and queued %d reads, want nothing", names, ask, len(*queued)) + } + on = true + gated.AskOnce() + runQueued(queued) + if names, ask := gated.AskOnce(); !ask || !reflect.DeepEqual(names, []string{"tower"}) { + t.Fatalf("after switching remote control on the asker answered (%v, %t), want (tower, true)", names, ask) + } + on = false + if _, ask := gated.AskOnce(); ask { + t.Fatal("the asker kept asking after remote control was switched off") + } +} + +// V14 / V11: the device list carries each other computer's permit only with +// remote control on; with it off the rows are as they always were. +func TestTheDeviceListCarriesPermitsOnlyWithRemoteControlOn(t *testing.T) { + t.Setenv("CODEAF_HOME", t.TempDir()) + book := permitBookWithLegacy(t) + door := &approvalsDoor{permits: func() *pair.PermitBook { return book }} + + t.Setenv("CODEAF_REMOTE_CONTROL", "") + for _, row := range door.withPermits(permitTestIdentity, permitRoster()) { + if row.Permit != nil { + t.Fatalf("row %s carried a permit with remote control off", row.ID) + } + } + + t.Setenv("CODEAF_REMOTE_CONTROL", "1") + got := map[string]*tui3.DevicePermit{} + for _, row := range door.withPermits(permitTestIdentity, permitRoster()) { + got[row.ID] = row.Permit + } + if got["dev_self"] != nil || got["dev_gone"] != nil { + t.Fatalf("this computer or a removed one carried a permit: %+v %+v", got["dev_self"], got["dev_gone"]) + } + if p := got["dev_old"]; p == nil || !p.Watch || p.Drive { + t.Fatalf("an older pairing reads %+v, want watch on and type off", p) + } + if p := got["dev_new"]; p == nil || !p.Watch || !p.Drive { + t.Fatalf("a pairing made after reads %+v, want watch and type on", p) + } +} + +// V11: the switches on /devices write the host's own book and change only the +// half they name. +func TestTheDevicesKeysWriteTheHostsBookAndChangeOnlyTheNamedHalf(t *testing.T) { + book := pair.PermitsAt(filepath.Join(t.TempDir(), "permits.json")) + dir := t.TempDir() + who, err := identity.Ensure(dir) + if err != nil { + t.Fatalf("identity: %v", err) + } + door := &approvalsDoor{dir: dir, permits: func() *pair.PermitBook { return book }} + off, on := false, true + + if err := door.SetPermit("dev_new", nil, &off); err != nil { + t.Fatalf("type off: %v", err) + } + if got, class := book.For(who.ID(), "dev_new"); !got.Watch || got.Drive || class != pair.ClassExplicit { + t.Fatalf("after type off a computer may %+v (%v), want watch only, set here", got, class) + } + if err := door.SetPermit("dev_new", &on, &on); err != nil { + t.Fatalf("both on: %v", err) + } + if got, _ := book.For(who.ID(), "dev_new"); !got.Watch || !got.Drive { + t.Fatalf("after both on a computer may %+v", got) + } + if err := door.SetPermit("dev_new", &off, nil); err != nil { + t.Fatalf("watch off: %v", err) + } + if got, _ := book.For(who.ID(), "dev_new"); got.Watch || !got.Drive { + t.Fatalf("watch off changed the other half too: %+v", got) + } + if err := door.SetPermit("", &on, nil); err == nil { + t.Fatal("SetPermit accepted an empty computer") + } + var _ tui3.PermitSetter = door +} diff --git a/cmd/codeaf/chatv3_surface.go b/cmd/codeaf/chatv3_surface.go index 8435d4140e..d4ac8836a1 100644 --- a/cmd/codeaf/chatv3_surface.go +++ b/cmd/codeaf/chatv3_surface.go @@ -157,7 +157,12 @@ func runSurface(ctx context.Context, options tui3.Options) error { <-copiesDone }() options.Pairing = chatPairDoor{} - options.Approvals = newApprovalsDoor(home.Dir()) + door := newApprovalsDoor(home.Dir()) + options.Approvals = door + // THE ONE-TIME QUESTION ABOUT OLDER PAIRINGS is asked only while remote + // control is on, and the asker reads that setting each time, so turning + // it on in this window brings the question with it. + options.PermitAsk = newPermitAsker(door) } options.UpdateRunning = revision options.UpdateCurl = curl diff --git a/cmd/codeaf/cluster_deadline_test.go b/cmd/codeaf/cluster_deadline_test.go index 0f400960b9..71f8f46daa 100644 --- a/cmd/codeaf/cluster_deadline_test.go +++ b/cmd/codeaf/cluster_deadline_test.go @@ -21,7 +21,7 @@ func TestClusterStatusDistinguishesDeadlinesFromUnreachableNetworks(t *testing.T cause error want string }{ - {"deadline", context.DeadlineExceeded, "the sync service at http://relay.invalid did not answer in time — try again"}, + {"deadline", context.DeadlineExceeded, "the relay at http://relay.invalid did not answer in time — try again"}, {"refused", syscall.ECONNREFUSED, syncwords.Unreachable("http://relay.invalid")}, {"route", syscall.ENETUNREACH, syncwords.Unreachable("http://relay.invalid")}, {"dns", &net.DNSError{Err: "no such host", Name: "relay.invalid", IsNotFound: true}, syncwords.Unreachable("http://relay.invalid")}, diff --git a/cmd/codeaf/copied_pingpong_test.go b/cmd/codeaf/copied_pingpong_test.go index cce076468d..629e3bfb5b 100644 --- a/cmd/codeaf/copied_pingpong_test.go +++ b/cmd/codeaf/copied_pingpong_test.go @@ -80,12 +80,12 @@ func (h *copiedPingPong) surfaceTake(s *syncsetup.Sync, taker takeover, root, do <-screen.ready if door == "home" { h.wait("Home continuation offer", func() bool { - return strings.Contains(screen.String(), "Continue "+from+"'s latest chat here?") + return strings.Contains(screen.String(), "Move "+from+"'s latest chat here?") }) _, _ = io.WriteString(typed, "\x1bc") } else { _, _ = io.WriteString(typed, "continue this copied chat\r") - h.wait("copied chat card", func() bool { return strings.Contains(screen.String(), "Continue this chat here?") }) + h.wait("copied chat card", func() bool { return strings.Contains(screen.String(), "Move this chat here?") }) _, _ = io.WriteString(typed, "1\r") } var got copiedTakeResult @@ -100,7 +100,7 @@ waiting: case got = <-result: break waiting case <-tick.C: - if !confirmed && strings.Contains(screen.String(), "Continue this chat here?") { + if !confirmed && strings.Contains(screen.String(), "Move this chat here?") { confirmed = true _, _ = io.WriteString(typed, "1\r") } diff --git a/cmd/codeaf/devices.go b/cmd/codeaf/devices.go index c49878e0da..58806cfca2 100644 --- a/cmd/codeaf/devices.go +++ b/cmd/codeaf/devices.go @@ -31,6 +31,7 @@ import ( "github.com/Agent-Field/codeaf/internal/directory" "github.com/Agent-Field/codeaf/internal/home" "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/livedoor" "github.com/Agent-Field/codeaf/internal/pair" "github.com/Agent-Field/codeaf/internal/syncsetup" "github.com/Agent-Field/codeaf/internal/syncwords" @@ -79,10 +80,12 @@ func runDevices(args []string) error { return stopDevice(kinds, args[1:]) case len(args) > 0 && args[0] == "rename": return runDevicesRename(args[1:]) + case len(args) > 0 && args[0] == "permit": + return runDevicesPermit(kinds, args[1:]) case askedForHelp(args): return commandHelp("devices") case len(args) > 0: - return fmt.Errorf("usage: codeaf devices [revoke [--all] | rename ]") + return fmt.Errorf("usage: codeaf devices [revoke [--all] | rename | permit [--watch on|off] [--drive on|off]]") } if !cell.Available() { paired, err := pair.DeviceBook().Devices() @@ -220,6 +223,66 @@ func stopDevice(kinds []deviceKind, args []string) error { return err } +func runDevicesPermit(kinds []deviceKind, args []string) error { + flags := commandFlags("devices permit") + watchRaw := flags.String("watch", "", "allow or stop watching this computer's running chats (on or off)") + driveRaw := flags.String("drive", "", "allow or stop typing into this computer's running chats (on or off)") + if err := parseCommandFlags(flags, reorder(flags, args)); err != nil { + return err + } + if flags.NArg() != 1 { + return errors.New("usage: codeaf devices permit [--watch on|off] [--drive on|off] — `codeaf devices` lists the names") + } + var watch, drive *bool + if strings.TrimSpace(*watchRaw) != "" { + v, err := parsePermitToggle("--watch", *watchRaw) + if err != nil { + return err + } + watch = &v + } + if strings.TrimSpace(*driveRaw) != "" { + v, err := parsePermitToggle("--drive", *driveRaw) + if err != nil { + return err + } + drive = &v + } + line, err := permitDevice(kinds, flags.Arg(0), watch, drive) + if err != nil { + return err + } + _, err = fmt.Fprintln(os.Stdout, line) + return err +} + +func parsePermitToggle(flagName, raw string) (bool, error) { + switch strings.ToLower(strings.TrimSpace(raw)) { + case "on": + return true, nil + case "off": + return false, nil + default: + return false, fmt.Errorf("%s takes on or off", flagName) + } +} + +func permitDevice(kinds []deviceKind, name string, watch, drive *bool) (string, error) { + name = strings.TrimSpace(name) + if name == "" { + return "", errors.New("usage: codeaf devices permit [--watch on|off] [--drive on|off] — `codeaf devices` lists the names") + } + for _, k := range kinds { + if c, ok := k.(chatsKind); ok { + return c.permit(name, watch, drive) + } + } + if err := checkRevokeRosters(kinds); err != nil { + return "", err + } + return "", unknownDevice(name) +} + // stopByName finds the one kind that has the name and stops it there. With // --all it stops every device of that name, in every kind that has one. func stopByName(kinds []deviceKind, name string, all bool) (string, error) { @@ -399,10 +462,11 @@ func countCalled[T any](items []T, name string, label func(T) string) int { // their identity in the relay's directory. Nothing is cached, so a listing and a // stop each see the directory as it is now. type chatsKind struct { - dir directory.Client - key []byte // opens the sealed names - self string // this computer's device id - relay string // named when the relay cannot be reached + dir directory.Client + key []byte // opens the sealed names + self string // this computer's device id + relay string // named when the relay cannot be reached + identity string // identity id for this computer's permit book } // openChatsKind is the kind for this machine, and false when it has none: sync @@ -416,7 +480,9 @@ func openChatsKind() (chatsKind, bool) { if err != nil || !ok { return chatsKind{}, false } - return chatsKindOf(s.Dir, s.Identity.CellKey(), s.Device.ID(), s.Relay), true + c := chatsKindOf(s.Dir, s.Identity.CellKey(), s.Device.ID(), s.Relay) + c.identity = s.Identity.ID() + return c, true } func chatsKindOf(dir directory.Client, cellKey []byte, self, relay string) chatsKind { @@ -559,9 +625,62 @@ func (c chatsKind) revoke(row chatsRow) (string, error) { if err := c.dir.Revoke(ctx, row.id); err != nil { return "", c.explain(err) } + livedoor.NotifyRemoved(home.Dir(), row.id) + _ = pair.Permits().Forget(row.id) + forgetViewed(home.Dir(), row.id) return pair.ChatsRevokedLine(row.Name), nil } +func (c chatsKind) identityID() string { + if c.identity != "" { + return c.identity + } + if id, err := identity.Load(home.Dir()); err == nil && id.ID() != "" { + return id.ID() + } + return "local" +} + +func (c chatsKind) permit(name string, watch, drive *bool) (string, error) { + rows, err := c.called(name) + switch { + case err != nil: + return "", err + case len(rows) > 1: + return "", ambiguousChatDevices(name, rows) + case len(rows) == 0: + return "", unknownDevice(name) + } + row := rows[0] + id := c.identityID() + book := pair.Permits() + if watch != nil || drive != nil { + if err := book.Set(id, row.id, watch, drive, "person"); err != nil { + return "", err + } + } + p, class := book.For(id, row.id) + return fmt.Sprintf("%s: watch %s, type %s (%s)", row.Name, permitWord(p.Watch), permitWord(p.Drive), permitClassWord(class)), nil +} + +func permitWord(on bool) string { + if on { + return "on" + } + return "off" +} + +func permitClassWord(class pair.PermitClass) string { + switch class { + case pair.ClassExplicit: + return "set here" + case pair.ClassNew: + return "new" + default: + return "legacy" + } +} + // explain turns the directory's errors into the sentence a person reads. func (c chatsKind) explain(err error) error { switch { diff --git a/cmd/codeaf/devices_test.go b/cmd/codeaf/devices_test.go index b4e3f3d5e1..43e27551cb 100644 --- a/cmd/codeaf/devices_test.go +++ b/cmd/codeaf/devices_test.go @@ -212,3 +212,107 @@ func TestChatsTableOfOnlyThisComputerOffersPairing(t *testing.T) { t.Fatalf("a lone computer drew %q (%v), want this device and the pairing next step", table, err) } } + +func TestDevicesPermitShowsAndEditsOnlyThisComputersOwnBook(t *testing.T) { + homeDir := t.TempDir() + t.Setenv("CODEAF_HOME", homeDir) + chats, dir := chatsWith(t, "laptop") + chats.identity = "id_test" + kinds := []deviceKind{chats} + + // Stamp a legacy baseline so an unrecorded peer defaults to watch on, drive off. + book := pair.Permits() + if _, class := book.For("id_test", otherComputer); class != pair.ClassLegacy { + t.Fatalf("initial class = %v, want %v", class, pair.ClassLegacy) + } + + beforeList, err := dir.List(devicesCtx) + if err != nil { + t.Fatal(err) + } + + said, err := captureStdout(t, func() error { return runDevicesPermit(kinds, []string{"laptop"}) }) + if err != nil { + t.Fatalf("permit laptop: %v", err) + } + if !strings.Contains(said, "laptop: watch on, type off") { + t.Fatalf("permit laptop = %q, want watch on, type off", said) + } + + said, err = captureStdout(t, func() error { return runDevicesPermit(kinds, []string{"laptop", "--drive", "on"}) }) + if err != nil { + t.Fatalf("permit laptop --drive on: %v", err) + } + if !strings.Contains(said, "laptop: watch on, type on") { + t.Fatalf("permit laptop --drive on = %q, want watch on, type on", said) + } + if p, class := pair.Permits().For("id_test", otherComputer); !p.Watch || !p.Drive || class != pair.ClassExplicit || p.By != "person" { + t.Fatalf("Permits().For = (%+v, %v), want Watch=true Drive=true ClassExplicit By=person", p, class) + } + + said, err = captureStdout(t, func() error { return runDevicesPermit(kinds, []string{"laptop", "--watch", "off"}) }) + if err != nil { + t.Fatalf("permit laptop --watch off: %v", err) + } + if !strings.Contains(said, "laptop: watch off") { + t.Fatalf("permit laptop --watch off = %q, want watch off", said) + } + + said, err = captureStdout(t, func() error { return runDevicesPermit(kinds, []string{"laptop", "--drive", "on"}) }) + if err != nil { + t.Fatalf("permit laptop --drive on after watch off: %v", err) + } + if !strings.Contains(said, "laptop: watch off, type on") { + t.Fatalf("permit laptop --drive on after watch off = %q, want watch off, type on", said) + } + if p, _ := pair.Permits().For("id_test", otherComputer); p.Watch || !p.Drive { + t.Fatalf("Permits().For after --watch off then --drive on = %+v, want Watch=false Drive=true", p) + } + + // Directory record was never modified. + afterList, err := dir.List(devicesCtx) + if err != nil { + t.Fatal(err) + } + if afterList.Version != beforeList.Version || afterList.Devices[otherComputer].Revoked != beforeList.Devices[otherComputer].Revoked || afterList.Devices[otherComputer].Name != beforeList.Devices[otherComputer].Name { + t.Fatalf("directory record changed: before=%+v after=%+v", beforeList, afterList) + } + + // An unknown name is refused with revoke's exact sentence. + _, err = captureStdout(t, func() error { return runDevicesPermit(kinds, []string{"ghost"}) }) + wantErr := unknownDevice("ghost").Error() + if err == nil || err.Error() != wantErr { + t.Fatalf("permit ghost err = %v, want %q", err, wantErr) + } +} + +func TestDevicesHelpListsPermitAndFitsEightyColumns(t *testing.T) { + for _, topic := range []string{"devices", "devices permit"} { + text := usageForCommand(topic) + if !strings.Contains(text, "codeaf devices permit [--watch on|off] [--drive on|off]") { + t.Fatalf("usageForCommand(%q) missing permit line:\n%s", topic, text) + } + for _, line := range strings.Split(text, "\n") { + if len(line) > 80 { + t.Fatalf("usageForCommand(%q) line exceeds 80 columns (%d): %q", topic, len(line), line) + } + } + } + var buf bytes.Buffer + oldOut := usageOut + usageOut = &buf + defer func() { usageOut = oldOut }() + err := runDevicesPermit(nil, []string{"--help"}) + if err != exitHelped { + t.Fatalf("devices permit --help: %v", err) + } + helpOut := buf.String() + if !strings.Contains(helpOut, "--watch") || !strings.Contains(helpOut, "--drive") { + t.Fatalf("devices permit --help missing flags:\n%s", helpOut) + } + for _, line := range strings.Split(helpOut, "\n") { + if len(line) > 80 { + t.Fatalf("devices permit --help line exceeds 80 columns (%d): %q", len(line), line) + } + } +} diff --git a/cmd/codeaf/directroad_install.go b/cmd/codeaf/directroad_install.go new file mode 100644 index 0000000000..08d8165656 --- /dev/null +++ b/cmd/codeaf/directroad_install.go @@ -0,0 +1,28 @@ +package main + +import ( + "context" + "io" + + "github.com/Agent-Field/codeaf/internal/directroad" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/syncsetup" +) + +// THE DIRECT ROAD IS HANDED TO THE SYNC PACKAGE HERE AND NOWHERE ELSE. Its +// implementation is a WebRTC data channel, and importing it from syncsetup would +// put a peer-to-peer library into every package that links the door. The program +// is the one place that wants it, so this is where the two meet, the same way the +// live door is handed its engine host in livedoor_doors.go. Remote control being +// off, or CODEAF_REMOTE_ROAD=relay, still leaves this installed and unused: +// syncsetup decides per door, and builds nothing in either case. +func init() { + syncsetup.SetDirectRoad(syncsetup.DirectRoad{ + NewHost: func(stun []string) syncsetup.DirectRoadHost { + return directroad.New(directroad.Config{STUN: stun}) + }, + Offer: func(ctx context.Context, stun []string, s livedoor.Signaller, deliver <-chan []byte) (io.ReadWriteCloser, error) { + return directroad.Offer(ctx, directroad.Config{STUN: stun}, s, deliver) + }, + }) +} diff --git a/cmd/codeaf/directroad_install_test.go b/cmd/codeaf/directroad_install_test.go new file mode 100644 index 0000000000..5c2331b317 --- /dev/null +++ b/cmd/codeaf/directroad_install_test.go @@ -0,0 +1,19 @@ +package main + +import ( + "testing" + + "github.com/Agent-Field/codeaf/internal/syncsetup" +) + +// TestTheProgramInstallsTheDirectRoad pins the seam the direct road needs: the +// sync package cannot import the peer-to-peer implementation without putting it +// into every package that links the door, so the program hands it over at start. +// Without the call in directroad_install.go no computer ever offers or answers a +// direct connection, remote control still works over the relay, and no other +// test in the program would notice. +func TestTheProgramInstallsTheDirectRoad(t *testing.T) { + if !syncsetup.DirectRoadInstalled() { + t.Fatal("the program started without handing the sync package the direct road") + } +} diff --git a/cmd/codeaf/displaced_watch_test.go b/cmd/codeaf/displaced_watch_test.go index 498932d71d..7f64b370d2 100644 --- a/cmd/codeaf/displaced_watch_test.go +++ b/cmd/codeaf/displaced_watch_test.go @@ -65,7 +65,7 @@ func TestHostedWatchDisplacedWindowAsksBeforeHeartbeat(t *testing.T) { defer deadline.Stop() frames := time.NewTicker(time.Millisecond) defer frames.Stop() - for !strings.Contains(screen.String(), "continued this chat. This copy is read-only and may be behind") { + for !strings.Contains(screen.String(), "moved this chat. This copy is read-only and may be behind") { select { case <-frames.C: case <-deadline.C: @@ -79,9 +79,9 @@ func TestHostedWatchDisplacedWindowAsksBeforeHeartbeat(t *testing.T) { t.Fatal(err) } h.wait("continue card or unexpected completion", func() bool { - return strings.Contains(screen.String(), "Continue this chat here?") || h.modelCalls.Load() != 0 + return strings.Contains(screen.String(), "Move this chat here?") || h.modelCalls.Load() != 0 }) - if h.modelCalls.Load() != 0 || !strings.Contains(screen.String(), "Continue this chat here?") { + if h.modelCalls.Load() != 0 || !strings.Contains(screen.String(), "Move this chat here?") { t.Fatalf("Enter after the displaced notice ran %d model completions instead of asking", h.modelCalls.Load()) } h.mu.Lock() @@ -145,7 +145,7 @@ func takeLiveChatFromHome(t *testing.T, h *hostedMoveRig) (cell.Cell, error) { if _, err := io.WriteString(typed, "\r"); err != nil { return cell.Cell{}, err } - h.wait("Home continue card", func() bool { return strings.Contains(screen.String(), "Continue this chat here?") }) + h.wait("Home continue card", func() bool { return strings.Contains(screen.String(), "Move this chat here?") }) if _, err := io.WriteString(typed, "1\r"); err != nil { return cell.Cell{}, err } diff --git a/cmd/codeaf/early_record_door_test.go b/cmd/codeaf/early_record_door_test.go new file mode 100644 index 0000000000..23b383d03b --- /dev/null +++ b/cmd/codeaf/early_record_door_test.go @@ -0,0 +1,273 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/cellstore" + "github.com/Agent-Field/codeaf/internal/home" + "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/session" + "github.com/Agent-Field/codeaf/internal/syncsetup" +) + +// These tests drive a new chat's first turn through the door the terminal +// uses: the real agent, its journal, the seal watch, the live drive, the sync +// drive, a relay and a second computer reading the list. They exist because the +// early record (remote control on: a chat is on the other computers' Home when +// its first turn STARTS) passed every test that sealed a startup head by hand +// and still did nothing in the product. A chat opened with /new has no head when +// its first turn starts, so the early record had nothing to stand on and the +// row appeared when the turn ended. + +// firstTurnRun opens a new chat, sends its first message, holds the model's +// reply, and says what the other computer saw while it was held. remote is the +// value of CODEAF_REMOTE_CONTROL, passThrough makes the relay behave like the +// hosted default with relay storage off. +type firstTurnRun struct { + t *testing.T + sender *syncsetup.Sync // this computer's sync + other *syncsetup.Sync // the other computer's sync, whose Home is read + cell string + hold chan struct{} + entered chan struct{} + frames atomic.Int64 + events <-chan session.Event + agent *session.Agent +} + +func newFirstTurnRun(t *testing.T, remote string, passThrough bool) *firstTurnRun { + t.Helper() + cfg, c := doorChat(t) + id, err := identity.Ensure(home.Dir()) + if err != nil { + t.Fatal(err) + } + t.Setenv("CODEAF_REMOTE_CONTROL", remote) + run := &firstTurnRun{t: t, cell: c.ID, hold: make(chan struct{})} + entered := make(chan struct{}, 1) + model := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var req struct { + Tools []json.RawMessage `json:"tools"` + Stream bool `json:"stream"` + } + _ = json.NewDecoder(r.Body).Decode(&req) + if len(req.Tools) > 0 { + select { + case entered <- struct{}{}: + default: + } + select { + case <-run.hold: + case <-r.Context().Done(): + return + } + } + if req.Stream { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"done\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n") + } else { + fmt.Fprint(w, `{"choices":[{"message":{"role":"assistant","content":"done"},"finish_reason":"stop"}]}`) + } + })) + t.Cleanup(model.Close) + + var wrap []func(http.Handler) http.Handler + if passThrough { + // The hosted relay refuses an object while storage is off. + wrap = append(wrap, func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/v1/store/frames") { + run.frames.Add(1) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"error":"storage_off"}`)) + return + } + next.ServeHTTP(w, r) + }) + }) + } + s, _, _ := heldChatRelay(t, c.ID, wrap...) + run.sender = s + + // The other computer of the same person, known to the directory. + homeB := t.TempDir() + if _, err := identity.Adopt(homeB, id, false); err != nil { + t.Fatal(err) + } + other, ok, err := syncsetup.Open(homeB) + if err != nil || !ok { + t.Fatalf("open the other computer = %v, %v", ok, err) + } + run.other = other + if err := syncsetup.PutOwnDevice(t.Context(), other.Dir, other.Identity, other.Device, "other"); err != nil { + t.Fatal(err) + } + if err := syncsetup.PutOwnDevice(t.Context(), s.Dir, s.Identity, s.Device, "this"); err != nil { + t.Fatal(err) + } + if passThrough { + if err := syncsetup.SaveStorage(home.Dir(), s.Relay, s.Identity.ID(), "off"); err != nil { + t.Fatal(err) + } + // Reading the roster is how a computer learns it has company. + if _, err := s.Dir.List(t.Context()); err != nil { + t.Fatal(err) + } + if !s.OthersPaired() || !s.LiveTransfer() { + t.Fatal("the fixture did not make blind pass-through the road") + } + } + + cfg.Workspace, cfg.SessionFile = cfg.Place.Workspace, cfg.Place.Transcript() + cfg.Model, cfg.APIKey, cfg.BaseURL, cfg.OneModel = "test/model", "fixture", model.URL, true + agent, _, _, err := openV3Agent(cfg, cfg.Place.Workspace, session.New) + if err != nil { + t.Fatalf("open the new chat: %v", err) + } + t.Cleanup(func() { closeV3Agent(agent) }) + // Registered after the agent's, so it runs first: a held turn cannot close. + t.Cleanup(run.release) + run.agent = agent + if head, err := cellstore.Head(c); err != nil || head != nil { + t.Fatalf("a chat opened with /new has a head before anybody spoke (%v, %v)", head, err) + } + run.entered = entered + return run +} + +func (r *firstTurnRun) release() { + select { + case <-r.hold: + default: + close(r.hold) + } +} + +// send is the person's first message, and waits until the model has it, which +// is when the turn is running. +func (r *firstTurnRun) send() { + r.t.Helper() + events, err := r.agent.Submit(r.t.Context(), "hello there") + if err != nil { + r.t.Fatal(err) + } + r.events = events + go func() { + for range events { + } + }() + select { + case <-r.entered: + case <-time.After(30 * time.Second): + r.t.Fatal("the model never received the first message") + } +} + +// listed is the other computer's list, as its Home reads it now. +func (r *firstTurnRun) listed() (found, working bool, title string) { + r.t.Helper() + rows, err := r.other.Rows(r.t.Context()) + if err != nil { + return false, false, "" + } + for _, row := range rows { + if row.Cell == r.cell { + return true, row.Working, row.Title + } + } + return false, false, "" +} + +func (r *firstTurnRun) within(d time.Duration, ok func() bool) bool { + deadline := time.Now().Add(d) + for time.Now().Before(deadline) { + if ok() { + return true + } + time.Sleep(50 * time.Millisecond) + } + return ok() +} + +// C1: remote control on. A new chat whose first turn is still running is on the +// other computer's list as working, within seconds of the turn starting. +func TestANewChatsFirstTurnIsOnTheOtherComputersHomeWhileItRuns(t *testing.T) { + for name, passThrough := range map[string]bool{"relay storage on": false, "blind pass-through": true} { + t.Run(name, func(t *testing.T) { + run := newFirstTurnRun(t, "1", passThrough) + run.send() + began := time.Now() + if !run.within(20*time.Second, func() bool { found, working, _ := run.listed(); return found && working }) { + found, working, title := run.listed() + t.Fatalf("the first turn is still running and the other computer lists found=%v working=%v title=%q", found, working, title) + } + // The contract is "within a few seconds of the turn starting". That + // holds on the hosted default, where the sync drive starts in about a + // second. With relay storage on, the drive's startup also syncs the + // vault before the first save can be made, and a message sent the + // instant the chat opens waits for it (12.6 s measured once on this + // fixture), so that road is held only to the turn still running. + limit := 8 * time.Second + if !passThrough { + limit = 20 * time.Second + } + took := time.Since(began) + t.Logf("the working row reached the other computer %v after the turn started", took.Round(10*time.Millisecond)) + if took > limit { + t.Fatalf("the row took %v to reach the other computer while the turn ran; want under %v", took, limit) + } + if passThrough { + // C4: the record carries no title and no folder, and the relay holds no object. + view, err := run.other.Dir.Cell(t.Context(), run.cell) + if err != nil { + t.Fatal(err) + } + if view.Cell.Title != "" || view.Cell.Folder != "" { + t.Fatalf("the early record carries a title %q or a folder %q", view.Cell.Title, view.Cell.Folder) + } + if n := run.frames.Load(); n != 0 { + t.Fatalf("the relay was sent %d objects while blind pass-through was the road", n) + } + } + run.release() + if !run.within(20*time.Second, func() bool { found, working, _ := run.listed(); return found && !working }) { + t.Fatal("the row never stopped saying the chat is working after the turn ended") + } + }) + } +} + +// C2: a chat nobody typed in appears on no other computer, however long it is +// open, with remote control on. +func TestANewChatNobodyTypedInIsOnNoOtherComputersHome(t *testing.T) { + run := newFirstTurnRun(t, "1", false) + // Past the trailing seal (cellstore.TailQuiet), which is when a startup save + // would have been made. + time.Sleep(cellstore.TailQuiet + 2*time.Second) + if found, _, _ := run.listed(); found { + t.Fatal("a chat nobody typed in is on the other computer's list") + } +} + +// C3: with remote control off the row appears when the first turn is sealed, +// which is when it ended, and not before. +func TestWithRemoteControlOffANewChatsRowWaitsForItsFirstTurnToEnd(t *testing.T) { + run := newFirstTurnRun(t, "0", false) + run.send() + time.Sleep(4 * time.Second) + if found, _, _ := run.listed(); found { + t.Fatal("with remote control off the other computer lists a chat whose first turn is still running") + } + run.release() + if !run.within(30*time.Second, func() bool { found, _, _ := run.listed(); return found }) { + t.Fatal("the chat never reached the other computer after its first turn ended") + } +} diff --git a/cmd/codeaf/engine.go b/cmd/codeaf/engine.go index 3af55bef73..7bc3fa4c59 100644 --- a/cmd/codeaf/engine.go +++ b/cmd/codeaf/engine.go @@ -1296,6 +1296,7 @@ func assembleEngine(hello remote.Hello, workspace, sessionFlag, launchDir string ClientTools: clientTools, TeamsPaired: teamPaired, SyncService: chatSyncService(), + DeltaWindow: remote.DeltaWindowFor(config.RemoteControlOn()), ReleaseOnLeave: func(current remote.WrappedAgent) bool { built, ok := current.(*session.Agent) if !ok { diff --git a/cmd/codeaf/factory_foreman.go b/cmd/codeaf/factory_foreman.go index c5cbee8e40..c2ec25839f 100644 --- a/cmd/codeaf/factory_foreman.go +++ b/cmd/codeaf/factory_foreman.go @@ -66,7 +66,7 @@ const foremanEarlierTitle = "Factory manager (earlier)" // and the manual quote the same words. It is kept free of the characters a // journal line escapes (angle brackets, double quotes), so the conversation's // file holds it as written and can be searched for it. -const foremanOpening = "You are the foreman of this factory, its factory-wide manager. Every job, its state, its step and its pull request come through factory_floor: read it before you answer what is running, what waits, what is queued, what shipped or how many jobs a repository has, and never answer those from memory. A message from the person may start with blocks the app writes. One tagged afi-now is the app's present state: the time, the factory's counts, what waits on the person ('Waiting on you' is the person, never you), what is running, what was made today and what was noticed lately. One tagged app-places says where things are in the app, for when the person asks where to find or do something. They are the app's, not the person's words, and were true when the message was sent: answer from them what they say, read factory_floor for what they do not, and never quote them back. Anything else the person asks, answer as any assistant would, with your other tools. Each job's row says what the job waits on and what it accepts from the person now; ask needs_you for the jobs that wait on the person, the one that has waited longest first. Start a job or set its priority with factory_floor only when the person asks for it here, naming the job by its ref. When the person asks you to act on a job (approve it, answer its question, merge it, mark its pull request ready, approve or decline what it would post, give it a task), press that one action for them with press; it is refused unless their own message in this turn asked for it and the job accepts it now. Before you approve what a job would post or change, show the person exactly what it is. When the person has words for one job's main agent, pass them on with tell and relay what it answers. That turn is not the person speaking in the job's own conversation, so outside Auto the job's main agent cannot push, approve, mark ready or merge on it: never promise that it will. Propose what to take on by selecting jobs. Never stop or drop a job, and never press, ship, merge or post on your own judgment. Name jobs by their ref." +const foremanOpening = "You are the foreman of this factory, its factory-wide manager. Every job, its state, its step and its pull request come through factory_floor: read it before you answer what is running, what waits, what is queued, what shipped or how many jobs a repository has, and never answer those from memory. A message from the person may start with blocks the app writes. One tagged afi-now is the app's present state: the time, the factory's counts, what waits on the person ('Waiting on you' is the person, never you), what is running, what was made today and what was noticed lately. One tagged app-places says where things are in the app, for when the person asks where to find or do something. They are the app's, not the person's words, and were true when the message was sent: answer from them what they say, read factory_floor for what they do not, and never quote them back. Anything else the person asks, answer as any assistant would, with your other tools. Each job's row says what the job waits on and what it accepts from the person now; ask needs_you for the jobs that wait on the person, the one that has waited longest first. Start a job or set its priority with factory_floor only when the person asks for it here, naming the job by its ref. When the person asks you to act on a job (approve it, answer its question, merge it, mark its pull request ready, approve or decline what it would post, give it a task), press that one action for them with press; it is refused unless their own message in this turn asked for it and the job accepts it now. Before you approve what a job would post or change, show the person exactly what it is. When the person has words for one job's main agent, pass them on with tell and report what it answers. That turn is not the person speaking in the job's own conversation, so outside Auto the job's main agent cannot push, approve, mark ready or merge on it: never promise that it will. Propose what to take on by selecting jobs. Never stop or drop a job, and never press, ship, merge or post on your own judgment. Name jobs by their ref." // floorDoor is `factory_floor`'s door over the store, or nil. // diff --git a/cmd/codeaf/factory_foreman_press.go b/cmd/codeaf/factory_foreman_press.go index d702925f77..511edc1fc0 100644 --- a/cmd/codeaf/factory_foreman_press.go +++ b/cmd/codeaf/factory_foreman_press.go @@ -209,7 +209,7 @@ func (d seamFloorDoor) Tell(ctx context.Context, id int, words, said string) (st if answer = strings.TrimSpace(answer); answer == "" { return fmt.Sprintf("The words were passed to %s's main agent. It finished its turn and said nothing: read %s again for what it did. %s", ref, ref, mode), nil } - return fmt.Sprintf("The words were passed to %s's main agent, which answered: %s\n\nRelay that to the person in your own plain words. %s", ref, answer, mode), nil + return fmt.Sprintf("The words were passed to %s's main agent, which answered: %s\n\nTell the person that in your own plain words. %s", ref, answer, mode), nil } // Press presses one action job id offers its person, as the person. diff --git a/cmd/codeaf/factory_foreman_press_test.go b/cmd/codeaf/factory_foreman_press_test.go index 003ef8c981..1e29a5c205 100644 --- a/cmd/codeaf/factory_foreman_press_test.go +++ b/cmd/codeaf/factory_foreman_press_test.go @@ -592,7 +592,7 @@ func TestTheFactoryManagersBriefSaysWhatItMayDoForThePerson(t *testing.T) { "ask needs_you for the jobs that wait on the person", "press that one action for them with press; it is refused unless their own message in this turn asked for it and the job accepts it now", "Before you approve what a job would post or change, show the person exactly what it is", - "pass them on with tell and relay what it answers", + "pass them on with tell and report what it answers", "outside Auto the job's main agent cannot push, approve, mark ready or merge on it: never promise that it will", "Never stop or drop a job, and never press, ship, merge or post on your own judgment", } { diff --git a/cmd/codeaf/hosted_takeback_test.go b/cmd/codeaf/hosted_takeback_test.go index fb9353e0e2..80d792ff2a 100644 --- a/cmd/codeaf/hosted_takeback_test.go +++ b/cmd/codeaf/hosted_takeback_test.go @@ -278,7 +278,7 @@ func TestHostedDisplacedWindowAsksBeforeSending(t *testing.T) { if _, err := io.WriteString(typed, "Add 1 to your last answer. Just the number.\r"); err != nil { t.Fatal(err) } - h.wait("continue card", func() bool { return strings.Contains(screen.String(), "Continue this chat here?") }) + h.wait("continue card", func() bool { return strings.Contains(screen.String(), "Move this chat here?") }) if h.modelCalls.Load() != 0 { t.Fatalf("displaced Enter made %d model calls", h.modelCalls.Load()) } @@ -338,7 +338,7 @@ func TestHostedTakeBackReachesAcquireWithoutSharedUploadsOrReleaseDelay(t *testi if _, err := io.WriteString(typed, "take back this chat\r"); err != nil { t.Fatal(err) } - h.wait("take-back card", func() bool { return strings.Contains(screen.String(), "Continue this chat here?") }) + h.wait("take-back card", func() bool { return strings.Contains(screen.String(), "Move this chat here?") }) h.mu.Lock() h.requests = nil h.acquires, h.resumes = nil, nil @@ -562,7 +562,7 @@ func TestKilledComputerTakesBackFromHomeAndLocalCard(t *testing.T) { // The question and its continue chord must be visible in the same offer. h.wait("Home continuation offer", func() bool { text := screen.String() - return strings.Contains(text, "Continue other computer's latest chat here?") && (strings.Contains(text, "alt+c") || strings.Contains(text, "opt+c")) + return strings.Contains(text, "Move other computer's latest chat here?") && (strings.Contains(text, "alt+c") || strings.Contains(text, "opt+c")) }) if _, err := io.WriteString(typed, "\x1bc"); err != nil { t.Fatal(err) @@ -572,7 +572,7 @@ func TestKilledComputerTakesBackFromHomeAndLocalCard(t *testing.T) { t.Fatal(err) } h.wait("card naming the current holder", func() bool { - return strings.Contains(screen.String(), "Continue this chat here?") && strings.Contains(screen.String(), "other computer") + return strings.Contains(screen.String(), "Move this chat here?") && strings.Contains(screen.String(), "other computer") }) if _, err := io.WriteString(typed, "1\r"); err != nil { t.Fatal(err) diff --git a/cmd/codeaf/identity_rotate.go b/cmd/codeaf/identity_rotate.go index 1f436fa137..3ecd3fabde 100644 --- a/cmd/codeaf/identity_rotate.go +++ b/cmd/codeaf/identity_rotate.go @@ -152,7 +152,7 @@ func planText(p rotate.Plan) string { fmt.Fprintf(&b, ", %d of them not on this computer (%s to fetch first)", p.Missing, rotationMegabytes(p.DownBytes)) } if p.StorageOff { - b.WriteString(".\nsync storage is off; your chats stay on this computer.\n") + b.WriteString(".\nrelay storage is off; your chats stay on this computer.\n") if p.DownBytes > 0 { fmt.Fprintf(&b, "allow about %s to fetch the missing chats.\n", minutes(p.Wait)) } diff --git a/cmd/codeaf/idle_handoff_contract_test.go b/cmd/codeaf/idle_handoff_contract_test.go index c6e047bde5..22e0dd1d0c 100644 --- a/cmd/codeaf/idle_handoff_contract_test.go +++ b/cmd/codeaf/idle_handoff_contract_test.go @@ -218,7 +218,7 @@ func TestIdleRelease_C2_C7_AppRunningAndQueuedWorkKeepTheLiveHold(t *testing.T) t.Cleanup(func() { e2Quit(t, peer) }) row := outageChatRow(t, peer, f.agent.ID, func(row appwire.ChatRow) bool { return row.Seen.Fence == before.Cell.Lease.Fence }) if row.CanOpen || !row.CanTake || row.Here { - t.Fatalf("C7 running chat lost its explicit Continue here choice: %+v", row) + t.Fatalf("C7 running chat lost its explicit Move here choice: %+v", row) } after, err := f.own.Dir.Cell(t.Context(), f.agent.ID) if err != nil || after.Cell.Lease.Device != before.Cell.Lease.Device || after.Cell.Lease.Fence != before.Cell.Lease.Fence { diff --git a/cmd/codeaf/idle_r10_surface_lock_test.go b/cmd/codeaf/idle_r10_surface_lock_test.go index f0436b8b9e..ea9cfc1f1e 100644 --- a/cmd/codeaf/idle_r10_surface_lock_test.go +++ b/cmd/codeaf/idle_r10_surface_lock_test.go @@ -12,7 +12,7 @@ import ( ) func TestIdleRelease_R10_RetryableRefusalIsNotHeldElsewhere(t *testing.T) { - err := appEngineError(&executor.WorkRefusal{Line: "couldn't confirm taking this chat back from the sync service; try again", Retryable: true}) + err := appEngineError(&executor.WorkRefusal{Line: "couldn't confirm taking this chat back from the relay; try again", Retryable: true}) var wire *appwire.Error if !errors.As(err, &wire) || wire.Code != appwire.CodeUnreachable || wire.Detail != nil { t.Fatalf("uncertain take-back offered a move: %+v", err) diff --git a/cmd/codeaf/idle_r10_terminal_test.go b/cmd/codeaf/idle_r10_terminal_test.go index ff4e8b0a17..54456b241a 100644 --- a/cmd/codeaf/idle_r10_terminal_test.go +++ b/cmd/codeaf/idle_r10_terminal_test.go @@ -192,7 +192,7 @@ func r10TerminalSequence(t *testing.T, rounds int, loseReply bool) { if model && users == 1 && answered { return } - if !retried && strings.Contains(screen.String()[min(frame, len(screen.String())):], "couldn't confirm taking this chat back from the sync service; try again") { + if !retried && strings.Contains(screen.String()[min(frame, len(screen.String())):], "couldn't confirm taking this chat back from the relay; try again") { if users != 0 { t.Fatal("uncertain take-back recorded the draft before admission") } @@ -267,7 +267,7 @@ func r10TerminalSequence(t *testing.T, rounds int, loseReply bool) { if raw, err := os.ReadFile(filepath.Join(h.work, "node_modules/x/index.js")); err != nil || string(raw) != "kept" { t.Fatalf("ignored install=%q error=%v", raw, err) } - for _, forbidden := range []string{"Continue this chat here?", "submit failed: This chat is available to continue here.", "Moved here", "Set this machine up like"} { + for _, forbidden := range []string{"Move this chat here?", "submit failed: This chat is available to move here.", "Moved here", "Set this machine up like"} { if strings.Contains(screen.String(), forbidden) { t.Fatalf("terminal showed %q", forbidden) } diff --git a/cmd/codeaf/idle_r6_offline_test.go b/cmd/codeaf/idle_r6_offline_test.go index 391c6015ab..f897711827 100644 --- a/cmd/codeaf/idle_r6_offline_test.go +++ b/cmd/codeaf/idle_r6_offline_test.go @@ -42,7 +42,7 @@ func TestIdleRelease_R6_ReleasedWindowOfflineSendSaysWhy(t *testing.T) { const words = "answer these kept words when sync returns" _, err = f.b.Send(f.agent.ID, words, "") var wire *appwire.Error - const want = "the sync service is not answering, so this chat cannot be taken back yet; your words are still in the box" + const want = "the relay is not answering, so this chat cannot be taken back yet; your words are still in the box" if !errors.As(err, &wire) || wire.Code != appwire.CodeUnreachable || wire.Message != want { t.Fatalf("released offline send = %v; want one unreachable refusal: %q", err, want) } diff --git a/cmd/codeaf/idle_r6_rows_test.go b/cmd/codeaf/idle_r6_rows_test.go index e8838e4029..a1f3d53b82 100644 --- a/cmd/codeaf/idle_r6_rows_test.go +++ b/cmd/codeaf/idle_r6_rows_test.go @@ -84,7 +84,7 @@ func TestIdleOpen_R6_LapsedWhileWorkingKeepsTheCard(t *testing.T) { t.Fatalf("fixture must lapse while working: %+v", before) } if row.CanOpen || !row.CanTake || row.Here || row.Status != "off" { - t.Fatalf("app lapsed working row must keep Continue here: %+v", row) + t.Fatalf("app lapsed working row must keep Move here: %+v", row) } if before.Cell.Head != after.Cell.Head || before.Cell.Lease != after.Cell.Lease { t.Fatal("listing a lapsed chat took it") diff --git a/cmd/codeaf/idle_terminal_regression_test.go b/cmd/codeaf/idle_terminal_regression_test.go index 041c2a88bb..58c4375cb9 100644 --- a/cmd/codeaf/idle_terminal_regression_test.go +++ b/cmd/codeaf/idle_terminal_regression_test.go @@ -183,7 +183,7 @@ func idleRealTerminal(t *testing.T, settings bool) { if raw, e := os.ReadFile(ignored); e != nil || string(raw) != "local-install" { t.Fatalf("D1 install=%q err=%v", raw, e) } - for _, line := range []string{"Moved here", "Set this machine up like", "Continue this chat here?", "submit failed: This chat is available to continue here."} { + for _, line := range []string{"Moved here", "Set this machine up like", "Move this chat here?", "submit failed: This chat is available to move here."} { if strings.Contains(screen.String(), line) { t.Fatalf("D1 showed %q", line) } diff --git a/cmd/codeaf/l4_cluster_test.go b/cmd/codeaf/l4_cluster_test.go index 3aec2eae32..60df35abcc 100644 --- a/cmd/codeaf/l4_cluster_test.go +++ b/cmd/codeaf/l4_cluster_test.go @@ -19,7 +19,7 @@ func (l4Cluster) LeadCluster(context.Context, uint64) (cs.LeadershipReceipt, err return cs.LeadershipReceipt{Node: 1}, nil } func (l4Cluster) ClusterNames(context.Context, clusterctl.Status) map[uint64]string { - return map[uint64]string{1: "laptop-a", 2: "desk-b", 3: "the sync service", 4: "box-c", 5: ""} + return map[uint64]string{1: "laptop-a", 2: "desk-b", 3: "the relay", 4: "box-c", 5: ""} } // L4-M14a, L4-M14b, L4-M14d: ordinary status and leadership use names; verbose keeps debugging details. diff --git a/cmd/codeaf/l4_final_save_test.go b/cmd/codeaf/l4_final_save_test.go index 55e658fc87..a283cd2ef8 100644 --- a/cmd/codeaf/l4_final_save_test.go +++ b/cmd/codeaf/l4_final_save_test.go @@ -47,7 +47,7 @@ func TestL4QuitSaveWords(t *testing.T) { finishing, ok bool want string }{ - {syncwords.UploadFailure(context.DeadlineExceeded), false, true, "saved here; it reaches your other devices when the sync service at 127.0.0.1:8901 answers"}, + {syncwords.UploadFailure(context.DeadlineExceeded), false, true, "saved here; it reaches your other devices when the relay at 127.0.0.1:8901 answers"}, {nil, true, false, "saving on this computer has not finished; its written turns stay here"}, {errors.New("disk full"), false, false, "codeaf could not save this chat"}, } { @@ -72,7 +72,7 @@ func TestL4QuitWaitCanBeCanceled(t *testing.T) { t.Fatal("unanswered upload not retained locally") } line, ok := finalSaveWords(syncwords.UploadFailure(context.DeadlineExceeded), finalSavingFinishing(), "http://127.0.0.1:8901") - if !ok || line != "saved here; it reaches your other devices when the sync service at 127.0.0.1:8901 answers" { + if !ok || line != "saved here; it reaches your other devices when the relay at 127.0.0.1:8901 answers" { t.Fatalf("%v %q", ok, line) } finalSaving.Lock() @@ -253,7 +253,7 @@ func TestL4InterruptedFinalSavingUsesLocalReceipt(t *testing.T) { } want := "saving on this computer has not finished; its written turns stay here\n" if safe { - want = "saved here; it reaches your other devices when the sync service at 127.0.0.1:8901 answers\n" + want = "saved here; it reaches your other devices when the relay at 127.0.0.1:8901 answers\n" } if string(raw) != want { t.Fatalf("receipt=%q", raw) diff --git a/cmd/codeaf/l4_progress_test.go b/cmd/codeaf/l4_progress_test.go index 783c3afe78..4b2211b702 100644 --- a/cmd/codeaf/l4_progress_test.go +++ b/cmd/codeaf/l4_progress_test.go @@ -25,7 +25,7 @@ func TestL4CommandProgress(t *testing.T) { <-out.wrote } stop() - if terminal && out.String() != "asking the sync service at 127.0.0.1:8901…\n" { + if terminal && out.String() != "asking the relay at 127.0.0.1:8901…\n" { t.Fatal(out.String()) } if !terminal && out.Len() != 0 { diff --git a/cmd/codeaf/l4fix_compat_test.go b/cmd/codeaf/l4fix_compat_test.go index 7441ca6905..69537c2ea1 100644 --- a/cmd/codeaf/l4fix_compat_test.go +++ b/cmd/codeaf/l4fix_compat_test.go @@ -114,7 +114,7 @@ func TestL4FixTwoChatQuitReceipt(t *testing.T) { t.Fatal("a successful detach poisoned the idle chat's upload receipt") } raw, _ := os.ReadFile(out.Name()) - if strings.TrimSpace(string(raw)) != "saved here; it reaches your other devices when the sync service at 127.0.0.1:8901 answers" { + if strings.TrimSpace(string(raw)) != "saved here; it reaches your other devices when the relay at 127.0.0.1:8901 answers" { t.Fatalf("receipt=%s", raw) } } diff --git a/cmd/codeaf/livedoor_doors.go b/cmd/codeaf/livedoor_doors.go new file mode 100644 index 0000000000..b4a2dfb6e9 --- /dev/null +++ b/cmd/codeaf/livedoor_doors.go @@ -0,0 +1,27 @@ +package main + +import ( + "github.com/Agent-Field/codeaf/internal/enginehost" + "github.com/Agent-Field/codeaf/internal/livedoor" +) + +// THE LIVE DOOR REACHES AN ENGINE HOST THROUGH THE SAME TWO CALLS EVERY OTHER +// DOOR USES. The live door is started from the sync package, and the engine-host +// package imports the sync package, so the live door cannot import the engine +// host itself. This is the one place the two meet: the program hands the resolver +// the engine host's own inspect and dial, so a chat held by a daemon is found by +// exactly the rule that decides which daemon holds a workspace, including the +// pid an older host does not state and the socket path rules. Nothing else here +// can start a host; both calls only ask or connect. +func init() { + livedoor.SetDaemonDoors(livedoor.DaemonDoors{ + Inspect: func(workspace string) (livedoor.Holder, error) { + held, err := enginehost.Inspect(workspace) + if err != nil { + return livedoor.Holder{}, err + } + return livedoor.Holder{Self: held.Self, Answered: held.Answered}, nil + }, + Dial: enginehost.Dial, + }) +} diff --git a/cmd/codeaf/livedoor_doors_test.go b/cmd/codeaf/livedoor_doors_test.go new file mode 100644 index 0000000000..f4f0f9d2c9 --- /dev/null +++ b/cmd/codeaf/livedoor_doors_test.go @@ -0,0 +1,19 @@ +package main + +import ( + "testing" + + "github.com/Agent-Field/codeaf/internal/livedoor" +) + +// TestTheProgramWiresTheLiveDoorToTheEngineHost pins the road contract V1 needs +// when the chat is held by a daemon. Another computer can open such a chat only +// if the resolver was handed the engine host's own inspect and dial, and the +// live door package cannot import the engine host to do that itself. Without +// the call in livedoor_doors.go the resolver answers "nothing is holding" for +// every chat a daemon holds, and no other test in the program would notice. +func TestTheProgramWiresTheLiveDoorToTheEngineHost(t *testing.T) { + if !livedoor.DaemonDoorsInstalled() { + t.Fatal("the program started without handing the live door the engine host's inspect and dial") + } +} diff --git a/cmd/codeaf/main.go b/cmd/codeaf/main.go index df2b9a5940..e4ed113c7a 100644 --- a/cmd/codeaf/main.go +++ b/cmd/codeaf/main.go @@ -654,6 +654,8 @@ Housekeeping — changes state on disk or on the network list your devices and the ones that can use this machine codeaf devices revoke [--all] | rename remove one (cannot undo what a device holds), or name this one + codeaf devices permit [--watch on|off] [--drive on|off] + show or change whether a paired computer may watch or type here codeaf factory [serve|add|name|steps|convert|token|revoke|revoke-sessions] codeaf attach | codeaf detach | codeaf runner join a team factory: host it (` + factoryDefaultListen + `), use it, or run its jobs here @@ -777,16 +779,16 @@ A variable that pins a ` + "`/settings`" + ` row wins over that row. CODEAF_PREAUTHORIZE_SPEND 1 spends past the day's limit without stopping a headless run to ask - CODEAF_SYNC_URL sync service for your chats; off disables syncing + CODEAF_SYNC_URL relay for your chats; off disables syncing CODEAF_MOVE_FILES_FIRST=1 wait for all workspace files before opening a moved chat CODEAF_PASSTHROUGH off (also 0, false, no) turns blind pass-through off: - while hosted sync storage is off, a chat then stays on + while hosted relay storage is off, a chat then stays on the computer that has it instead of passing straight - through the sync service to a paired computer that is + through the relay to a paired computer that is also running codeaf (default on) - CODEAF_RELAY sync service override for pairing and remote connections + CODEAF_RELAY relay override for pairing and remote connections CODEAF_HOME the whole state root — journal, workspace, CAS, craft, profiles, catalog, skills (default ~/.codeaf). Move it to run a disposable store that touches nothing of yours. diff --git a/cmd/codeaf/pair.go b/cmd/codeaf/pair.go index 2180ade236..b8eac37749 100644 --- a/cmd/codeaf/pair.go +++ b/cmd/codeaf/pair.go @@ -160,7 +160,7 @@ func (d pairDoor) run(ctx context.Context, args []string) error { fmt.Fprintln(usageOut, reason) } flags := commandFlags("pair") - via := flags.String("via", "", "the sync service to pair through; empty is the one this device already uses") + via := flags.String("via", "", "the relay to pair through; empty is the one this device already uses") renamedFlag(flags, "relay", "via") code := flags.Bool("code", false, "show a code such as "+pair.ExampleChatCode+" that shares this device's chats, instead of asking to join") replace := flags.Bool("replace", false, "when typing a code, replace this device's own chats with the shared ones") diff --git a/cmd/codeaf/pair_deadline_test.go b/cmd/codeaf/pair_deadline_test.go index 295798cc80..475d5e7eee 100644 --- a/cmd/codeaf/pair_deadline_test.go +++ b/cmd/codeaf/pair_deadline_test.go @@ -57,7 +57,7 @@ func TestPairDoorExplainsARequestDeadline(t *testing.T) { } } err := door.run(ctx, args) - want := "the sync service at " + server.URL + " did not answer in time — try again" + want := "the relay at " + server.URL + " did not answer in time — try again" if err == nil || err.Error() != want { t.Fatalf("pairing deadline=%v; want %q", err, want) } diff --git a/cmd/codeaf/pair_terminal.go b/cmd/codeaf/pair_terminal.go index 85f886daec..eb487db914 100644 --- a/cmd/codeaf/pair_terminal.go +++ b/cmd/codeaf/pair_terminal.go @@ -139,6 +139,7 @@ func (s offerScreen) Show(_ *pair.Code, lines string) { s.stopProgress(); fmt.Fp func (s offerScreen) Burned() { s.say(pair.BurnLine) } func (s offerScreen) Ask(ctx context.Context, label, words string) bool { + s.say(pair.PairedControlLine(label)) return s.confirm(ctx, pair.AskChatsLine(label, words)) } diff --git a/cmd/codeaf/pair_test.go b/cmd/codeaf/pair_test.go index aea3126608..144baa195f 100644 --- a/cmd/codeaf/pair_test.go +++ b/cmd/codeaf/pair_test.go @@ -275,6 +275,9 @@ func TestDevicesAfterACodePairingShowsBothComputers(t *testing.T) { if asked := shown.out.waitFor(t, `"laptop" wants your chats\. Same three words on that screen: ([a-z ]+)\? y / n `); asked == nil { t.Fatal("the sharing screen never asked") } + if !strings.Contains(shown.out.String(), pair.PairedControlLine("laptop")) { + t.Fatalf("offer screen lacks %q:\n%s", pair.PairedControlLine("laptop"), shown.out.String()) + } if _, err := io.WriteString(shown.typed, "y\n"); err != nil { t.Fatal(err) } @@ -397,3 +400,21 @@ func TestServeApproverIsAbsentWithoutATerminal(t *testing.T) { t.Fatal("a machine with no terminal was given someone to ask") } } + +func TestAppPairQuestionsSayTheNewDeviceCanControlChats(t *testing.T) { + for _, tc := range []struct { + name string + label string + got string + }{ + {name: "code", label: "laptop", got: appPairWords("laptop", "amber cedar moon")}, + {name: "link", label: "laptop (Linux)", got: appPairCheck("laptop (Linux)", "4821")}, + } { + t.Run(tc.name, func(t *testing.T) { + want := pair.PairedControlLine(tc.label) + if !strings.Contains(tc.got, want) { + t.Fatalf("question %q lacks %q", tc.got, want) + } + }) + } +} diff --git a/cmd/codeaf/pairlink.go b/cmd/codeaf/pairlink.go index a5acb22c8d..99379218cf 100644 --- a/cmd/codeaf/pairlink.go +++ b/cmd/codeaf/pairlink.go @@ -197,7 +197,7 @@ func (d pairDoor) approve(ctx context.Context, relay, typed string) error { asking, err := who.Look(ctx, ref) if errors.Is(err, pair.ErrLinkDecided) && approvedHere(who, ref.Code, "") == requestApprovedHere { // An approval whose reply was lost: the device is in, so this computer is shared. - if err := identity.EndSolo(d.joining(false).Home); err != nil { + if err := pair.EndSoloAt(d.joining(false).Home, pair.Permits()); err != nil { return err } d.recordOwnDeviceOrSay(ctx, route) @@ -208,6 +208,7 @@ func (d pairDoor) approve(ctx context.Context, relay, typed string) error { return err } d.term.say(pair.WantsToJoinLine(asking.Name, asking.Platform)) + d.term.say(pair.PairedControlLine(asking.Name)) if !d.term.approveLink(ctx, pair.CheckQuestion(asking.Check)) { return d.decline(ctx, who, asking) } @@ -220,7 +221,7 @@ func (d pairDoor) approve(ctx context.Context, relay, typed string) error { return err } } - if err := identity.EndSolo(d.joining(false).Home); err != nil { + if err := pair.EndSoloAt(d.joining(false).Home, pair.Permits()); err != nil { return err } d.recordOwnDeviceOrSay(ctx, route) diff --git a/cmd/codeaf/pairlink_test.go b/cmd/codeaf/pairlink_test.go index a8a7d3110f..eb33cf4df7 100644 --- a/cmd/codeaf/pairlink_test.go +++ b/cmd/codeaf/pairlink_test.go @@ -51,7 +51,7 @@ func TestPairByLinkEndToEnd(t *testing.T) { t.Fatal(err) } // The asking computer names its own operating system, so on a Mac it says Mac. - want := pair.WantsToJoinLine("laptop", runtime.GOOS) + "\n" + pair.CheckQuestion(check) + "\n" + pairApproveKeys + want := pair.WantsToJoinLine("laptop", runtime.GOOS) + "\n" + pair.PairedControlLine("laptop") + "\n" + pair.CheckQuestion(check) + "\n" + pairApproveKeys if !strings.HasPrefix(out.String(), want) || !strings.Contains(out.String(), pair.ApprovedLine("laptop")) { t.Fatalf("the approving terminal printed:\n%s\nwant it to start:\n%s", out.String(), want) } diff --git a/cmd/codeaf/pairroute.go b/cmd/codeaf/pairroute.go index 4835ffbb82..8e56d450f1 100644 --- a/cmd/codeaf/pairroute.go +++ b/cmd/codeaf/pairroute.go @@ -102,7 +102,7 @@ func pairGrantAt(dir string, route pair.Mailbox) (pair.Grant, error) { if err := syncsetup.SaveRelayURL(dir, syncsetup.Named(route.URL)); err != nil { return fmt.Errorf("could not keep the pairing relay address, so nothing was sent: %w", err) } - if err := identity.EndSolo(dir); err != nil { + if err := pair.EndSoloAt(dir, pair.Permits()); err != nil { return fmt.Errorf("could not record that this computer now shares its chats, so nothing was sent: %w", err) } return nil diff --git a/cmd/codeaf/quit_handoff_test.go b/cmd/codeaf/quit_handoff_test.go index c32f94d88f..0cef9e1fde 100644 --- a/cmd/codeaf/quit_handoff_test.go +++ b/cmd/codeaf/quit_handoff_test.go @@ -244,7 +244,7 @@ func runHostedQuitContract(t *testing.T, relayDown bool) { t.Fatal(err) } line, err := io.ReadAll(out) - if err != nil || !strings.Contains(string(line), "saved here; it reaches your other devices when the sync service at ") || strings.Contains(string(line), transcript) || strings.Contains(string(line), "could not save") { + if err != nil || !strings.Contains(string(line), "saved here; it reaches your other devices when the relay at ") || strings.Contains(string(line), transcript) || strings.Contains(string(line), "could not save") { t.Fatalf("offline quit report=%q err=%v", line, err) } return diff --git a/cmd/codeaf/quit_tail_test.go b/cmd/codeaf/quit_tail_test.go index a4e3467125..684cdb51ee 100644 --- a/cmd/codeaf/quit_tail_test.go +++ b/cmd/codeaf/quit_tail_test.go @@ -543,7 +543,7 @@ func TestL4HostedTakeBackNeverBranchesBookkeepingOnlyTurns(t *testing.T) { func assertBookkeepingTakeBack(t *testing.T, h *hostedTailChat, g *tailPublishGate) { t.Helper() output := h.quitAfter(g, 0) - if !strings.Contains(output, "saved here; it reaches your other devices when the sync service at ") || strings.Contains(output, "could not save") { + if !strings.Contains(output, "saved here; it reaches your other devices when the relay at ") || strings.Contains(output, "could not save") { raw, _ := os.ReadFile(session.Place{Dir: h.c.Root}.Transcript()) t.Fatalf("offline fixture did not retain local work: %q\n%s", output, raw) } @@ -596,7 +596,7 @@ func TestL4HostedLocalSaveRetriesUploadOnNextStartWhileStillHolding(t *testing.T return err == nil && strings.Contains(string(raw), `"title":"a saved conversation title"`) }) output := h.quitAfter(g, 0) - if !strings.Contains(output, "saved here; it reaches your other devices when the sync service at ") || strings.Contains(output, "could not save") { + if !strings.Contains(output, "saved here; it reaches your other devices when the relay at ") || strings.Contains(output, "could not save") { t.Errorf("an upload-only failure lost its local-save receipt: %q", output) } if _, fence, err := h.a.SendLease(h.c.ID); err != nil || fence == 0 { diff --git a/cmd/codeaf/quit_wait_test.go b/cmd/codeaf/quit_wait_test.go index 7d86d97486..31447801a0 100644 --- a/cmd/codeaf/quit_wait_test.go +++ b/cmd/codeaf/quit_wait_test.go @@ -46,7 +46,7 @@ func TestQuitWaitReportsStillFinishingAtTheSavingCeiling(t *testing.T) { if err != nil { t.Fatal(err) } - if strings.Count(string(raw), "saved here; it reaches your other devices when the sync service at") != 1 || strings.Contains(string(raw), "could not save") { + if strings.Count(string(raw), "saved here; it reaches your other devices when the relay at") != 1 || strings.Contains(string(raw), "could not save") { t.Fatalf("long wait=%q", raw) } finalSaving.Lock() diff --git a/cmd/codeaf/storage_off_lifetime_test.go b/cmd/codeaf/storage_off_lifetime_test.go index 005ba8b3e8..27f5a52d9c 100644 --- a/cmd/codeaf/storage_off_lifetime_test.go +++ b/cmd/codeaf/storage_off_lifetime_test.go @@ -283,7 +283,7 @@ func TestStorageOffContinuedChatSendsAfterItsOwnEmptyHeadHoldExpires(t *testing. t.Fatal(err) } waitStorageOffBoundary(t, "locally saved "+marker, func() bool { - if strings.Contains(screen.Plain(), "Continue this chat here?") { + if strings.Contains(screen.Plain(), "Move this chat here?") { t.Fatal("own empty-head chat asked to continue again") } raw, _ := os.ReadFile(cfg.SessionFile) @@ -319,7 +319,7 @@ func TestStorageOffContinuedChatSendsAfterItsOwnEmptyHeadHoldExpires(t *testing. if err != nil || latest.Cell.Lease.Fence <= previous.Cell.Lease.Fence || latest.Cell.Lease.Device != s.Device.ID() { t.Fatalf("send did not reacquire: %+v %v", latest, err) } - if strings.Contains(screen.Plain(), "Continue this chat here?") { + if strings.Contains(screen.Plain(), "Move this chat here?") { t.Fatal("own expired chat asked to continue") } if store.writes.Load() != 0 { @@ -508,7 +508,7 @@ func testRecordedHeadReturn(t *testing.T, mode string) { t.Fatal(err) } waitStorageOffBoundary(t, "saved "+marker, func() bool { - if strings.Contains(shown(), "Continue this chat here?") { + if strings.Contains(shown(), "Move this chat here?") { t.Fatal("own chat asked to continue again") } raw, _ := os.ReadFile(cfg.SessionFile) @@ -591,7 +591,7 @@ func testRecordedHeadReturn(t *testing.T, mode string) { t.Fatal(err) } waitStorageOffBoundary(t, "continue question or missing-turns refusal", func() bool { - return strings.Contains(shown(), "Continue this chat here?") || mode == "missing saved turns" && strings.Contains(shown(), "this computer is missing saved turns; your local turns stay here") + return strings.Contains(shown(), "Move this chat here?") || mode == "missing saved turns" && strings.Contains(shown(), "this computer is missing saved turns; your local turns stay here") }) latest, err := s.Dir.Cell(t.Context(), c.ID) if err != nil || latest.Cell.Lease.Fence != free.Cell.Lease.Fence || turns.Load() != calls { diff --git a/cmd/codeaf/storage_optin_test.go b/cmd/codeaf/storage_optin_test.go index 8082f2c6ad..c099ac9d69 100644 --- a/cmd/codeaf/storage_optin_test.go +++ b/cmd/codeaf/storage_optin_test.go @@ -197,7 +197,7 @@ func TestStorageOptInQuitReceiptAfterRevocation(t *testing.T) { if err != nil { t.Fatal(err) } - if strings.TrimSpace(string(raw)) != "saved here; sync storage is off for this account, so it stays on this computer" { + if strings.TrimSpace(string(raw)) != "saved here; relay storage is off for this account, so it stays on this computer" { t.Fatalf("receipt: %s", raw) } } diff --git a/cmd/codeaf/sync_off_home_test.go b/cmd/codeaf/sync_off_home_test.go index 488de02fdb..77ab60f98b 100644 --- a/cmd/codeaf/sync_off_home_test.go +++ b/cmd/codeaf/sync_off_home_test.go @@ -487,7 +487,7 @@ func TestSyncOffHomeKeepsEveryChatOpensAndWrites(t *testing.T) { t.Fatalf("ReadHome() after writing returned %d chats, want 4: %+v", len(afterRows), afterRows) } if got := relayRequests.Load(); got != 0 { - t.Fatalf("sync off contacted the sync service %d times, want 0", got) + t.Fatalf("sync off contacted the relay %d times, want 0", got) } }) } diff --git a/cmd/codeaf/syncdrive.go b/cmd/codeaf/syncdrive.go index 8a85ce7019..9637cb0a5f 100644 --- a/cmd/codeaf/syncdrive.go +++ b/cmd/codeaf/syncdrive.go @@ -10,6 +10,7 @@ import ( "github.com/Agent-Field/codeaf/internal/cellstore" "github.com/Agent-Field/codeaf/internal/cellsync" "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/config" "github.com/Agent-Field/codeaf/internal/executor" "github.com/Agent-Field/codeaf/internal/home" "github.com/Agent-Field/codeaf/internal/session" @@ -218,6 +219,9 @@ func startLiveDrive(c cell.Cell, engine cellstore.Engine, report func(error), no OnNotice: say, OnViewer: viewer, OnDriving: driving, + // With remote control on, a chat is listed on the other computers when + // its first turn starts, not when it ends. Off, nothing changes. + EarlyRecord: config.RemoteControlOn, }) if _, refused := cellsync.RefusalOf(err); refused { return nil, err diff --git a/cmd/codeaf/syncdrive_live.go b/cmd/codeaf/syncdrive_live.go index f4bd8c82a8..f0be511bae 100644 --- a/cmd/codeaf/syncdrive_live.go +++ b/cmd/codeaf/syncdrive_live.go @@ -45,6 +45,11 @@ type liveDrive struct { turnStop context.CancelFunc parked bool // Startup awaits a journal owner. storageWaiting bool + // storageChecked is when a touched chat last read local truth to see + // whether the storage it waits for has opened, and storageOpen is that + // read (nil is [storageOpenAt]); see [liveDrive.storageReopened]. + storageChecked time.Time + storageOpen func(home string) bool waiting bool // local setup or a retryable failure still permits another attempt ready chan struct{} attempted bool @@ -59,6 +64,10 @@ type liveDrive struct { changes chan struct{} idleCheck func() bool surfaceIdle func() bool + // firstSave seals the chat now, through the recorder that seals everything + // else. It is set by the seat once there is one, and it is how a chat that + // has never been sealed gets the head an early record stands on. + firstSave func() } // newLiveDrive starts the drive side behind the first paint. Local startup @@ -105,6 +114,7 @@ func (l *liveDrive) afterFunc(d time.Duration, fn func()) func() bool { // The identity is one file read and the relay is asked only once it exists, so a // chat that never pairs costs nothing per call. func (l *liveDrive) try() { + l.storageReopened() l.mu.Lock() defer l.mu.Unlock() if l.parked || l.closed.Load() || l.storageWaiting || l.drive != nil || l.ready != nil || (l.attempted && !l.waiting) || (l.waiting && !syncsetup.MayTalk(home.Dir())) { @@ -127,6 +137,63 @@ func (l *liveDrive) try() { l.launch(l.ready) } +// storageRecheckEvery is the most often a touched chat that waits for storage +// looks at local files to see whether it has opened. Two seconds is below what +// a person notices after pairing and far above what a chat's touches cost. +const storageRecheckEvery = 2 * time.Second + +// storageOpenAt answers from local files alone, with no request, the question +// the drive's own startup asks: may this computer's chats be shared now, through +// the account's storage or live. It is [syncsetup.Sync.ChatStorageOff] turned +// round, for a caller that has only the home. +func storageOpenAt(home string) bool { + return syncsetup.StorageForHome(home) == "on" || syncsetup.LiveTransferForHome(home) +} + +// storageReopened wakes a chat that waits for closed storage as soon as it is +// touched after the storage has opened. THE WAIT HAS ONE OTHER WAKE-UP: a +// timer shared by the whole process that looks once a minute (syncsetup. +// StoragePollEvery), plus a call from this process's own pairing. A computer +// paired by ANOTHER process (a terminal, a second window's engine) therefore +// left a chat that was already open unshared for up to a minute. The chat is +// touched at every message, tool gate and save, so asking then costs nothing +// while nothing waits and at most one small local read every two seconds while +// something does, and adds no timer. A chat held back for any other reason (the +// relay refusing, no other computer yet) never reaches this read, and a chat +// whose storage is still closed stays exactly as it was. +func (l *liveDrive) storageReopened() { + open, due := l.storageRecheck() + if !due { + return + } + // The read and the wake happen outside the lock: waking clears the wait and + // may start the drive, which takes it again. + if open(home.Dir()) { + l.storageOpened() + } +} + +// storageRecheck says whether a touch should look at local files now, and +// through which read, and starts the two seconds again when it should. A chat +// that is not waiting for storage, or that looked less than two seconds ago, is +// not due. +func (l *liveDrive) storageRecheck() (open func(home string) bool, due bool) { + l.mu.Lock() + defer l.mu.Unlock() + if !l.storageWaiting || l.closed.Load() { + return nil, false + } + now := l.nowTime() + if !l.storageChecked.IsZero() && now.Sub(l.storageChecked) < storageRecheckEvery { + return nil, false + } + l.storageChecked = now + if l.storageOpen != nil { + return l.storageOpen, true + } + return storageOpenAt, true +} + // begin spends the reserved startup exactly once after the journal opens. func (l *liveDrive) begin() { l.mu.Lock() @@ -224,6 +291,7 @@ func (l *liveDrive) install(d *syncsetup.Drive, err error, ready chan struct{}) l.told = nil l.refusedSince = time.Time{} d.Working(l.working) + l.askFirstSave(d) d.SetIdleCheck(l.idleReady) d.CatchUp() l.retryWait = 0 @@ -365,7 +433,31 @@ func (l *liveDrive) Working(on bool) { l.working = on if l.drive != nil { l.drive.Working(on) + if on { + l.askFirstSave(l.drive) + } + } +} + +// setFirstSave gives the drive the seat's way of sealing the chat now. +func (l *liveDrive) setFirstSave(save func()) { + l.mu.Lock() + defer l.mu.Unlock() + l.firstSave = save +} + +// askFirstSave has the chat sealed when its first spoken turn has just started +// and there is no head for the early record to stand on ([syncsetup.Drive. +// EarlyHeadOwed]). A chat opened with /new has none, so without this the row +// waited for the turn to end. The seal runs off the turn's goroutine and +// reaches the drive through the ordinary store, which notes it and creates the +// record. The caller holds mu; nothing here waits for the seal. +func (l *liveDrive) askFirstSave(d *syncsetup.Drive) { + if l.firstSave == nil || !d.EarlyHeadOwed() { + return } + save := l.firstSave + guard.Go("first save of a new chat", save) } // TurnEnded keeps the shared working flag until all work the reply left behind diff --git a/cmd/codeaf/syncdrive_storage_recheck_test.go b/cmd/codeaf/syncdrive_storage_recheck_test.go new file mode 100644 index 0000000000..8705c2ca20 --- /dev/null +++ b/cmd/codeaf/syncdrive_storage_recheck_test.go @@ -0,0 +1,175 @@ +package main + +import ( + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/home" + "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/syncsetup" + "github.com/Agent-Field/codeaf/internal/wireauth" +) + +// These tests are the first chat after a fresh pairing (contract P1 to P3 in +// NOTES-POLISH). A chat opened while its computer had no other computer, or no +// storage, is held back from sharing. The one thing that wakes it for want of +// storage was a timer shared by the whole process that looks once a minute, so a +// computer paired by ANOTHER process left the chat unshared for up to a minute +// unless something in this process said so. The fix is a small local check each +// time the chat is touched, and the clock in these tests is a fake: nothing here +// sleeps. + +// recheckClock is the time a liveDrive reads, moved by hand. +type recheckClock struct { + mu sync.Mutex + now time.Time +} + +func (c *recheckClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *recheckClock) advance(d time.Duration) { + c.mu.Lock() + defer c.mu.Unlock() + c.now = c.now.Add(d) +} + +// heldBackForStorage is a chat whose startup was refused for closed storage: +// the first start answers wireauth.ErrStorageOff, and a later one succeeds with +// an empty fixture drive. The drive side's own clock and timers are fakes. +func heldBackForStorage(t *testing.T, startErr error) (l *liveDrive, clock *recheckClock, starts *atomic.Int32) { + t.Helper() + // A real home that is paired and whose permission file says storage is off: + // the state a chat opened just before the other computer's pairing started in. + _ = storageOffNoticeConfig(t) + clock = &recheckClock{now: time.Unix(1_800_000_000, 0)} + starts = &atomic.Int32{} + entered := make(chan struct{}) + l = newLiveDrive(func(func()) (*syncsetup.Drive, error) { + <-entered + if starts.Add(1) == 1 { + return nil, startErr + } + return &syncsetup.Drive{}, nil + }) + l.now = clock.Now + l.after = func(time.Duration, func()) func() bool { return func() bool { return true } } + l.say = func(string) {} + close(entered) + startupFinished(l) + t.Cleanup(func() { + // The empty fixture drive has no process to close. + l.mu.Lock() + l.drive = nil + l.mu.Unlock() + _ = l.Close(t.Context()) + }) + return l, clock, starts +} + +// P1, P2, P3: while storage stays closed a touched chat looks at local truth at +// most once every two seconds and stays held back; the first look after +// storage is open starts it, at the touch and not on the minute timer. +func TestAChatHeldBackForClosedStorageStartsAtTheNextTouchOnceStorageIsOpen(t *testing.T) { + l, clock, starts := heldBackForStorage(t, wireauth.ErrStorageOff) + if !l.storageWaiting { + t.Fatal("a chat refused for closed storage is not waiting for it") + } + var reads atomic.Int32 + var open atomic.Bool + l.storageOpen = func(string) bool { reads.Add(1); return open.Load() } + + // P2: the first touch looks once; touches inside the two seconds do not. + l.try() + if reads.Load() != 1 { + t.Fatalf("the first touch read local truth %d times, want 1", reads.Load()) + } + clock.advance(time.Second) + l.try() + l.Gate() + if reads.Load() != 1 { + t.Fatalf("touches within two seconds read local truth %d times, want 1", reads.Load()) + } + + // P3: past the two seconds it looks again, finds storage closed, and the + // chat stays held back with no new start. + clock.advance(2 * time.Second) + l.try() + if reads.Load() != 2 || !l.storageWaiting || starts.Load() != 1 { + t.Fatalf("reads=%d waiting=%v starts=%d, want 2 reads, still waiting, 1 start", reads.Load(), l.storageWaiting, starts.Load()) + } + + // Another process opens storage. A touch inside the two seconds still does + // not look, so the cost bound holds when storage opens too. + open.Store(true) + clock.advance(time.Second) + l.try() + if reads.Load() != 2 || starts.Load() != 1 { + t.Fatalf("a touch inside the two seconds looked: reads=%d starts=%d", reads.Load(), starts.Load()) + } + + // P1: the next touch after the two seconds, here the start of a turn, + // finds it open and starts the drive side. + clock.advance(2 * time.Second) + l.Working(true) + startupFinished(l) + if starts.Load() != 2 { + t.Fatalf("the drive side started %d times after storage opened, want 2", starts.Load()) + } + l.mu.Lock() + waiting, started := l.storageWaiting, l.drive != nil + l.mu.Unlock() + if waiting || !started { + t.Fatalf("storageWaiting=%v drive running=%v after storage opened", waiting, started) + } + + // P2: with a drive running, touching the chat reads nothing at all. + before := reads.Load() + for i := 0; i < 5; i++ { + clock.advance(time.Hour) + l.try() + } + if reads.Load() != before { + t.Fatalf("a running chat read local truth %d more times", reads.Load()-before) + } +} + +// P3: a chat held back for any other reason (the relay full, say) has no +// storage wait, so the new look never happens and its own wait is untouched. +func TestAChatHeldBackForAnotherReasonNeverLooksAtStorage(t *testing.T) { + l, clock, _ := heldBackForStorage(t, wireauth.ErrRelayFull) + var reads atomic.Int32 + l.storageOpen = func(string) bool { reads.Add(1); return true } + for i := 0; i < 3; i++ { + clock.advance(time.Second) + l.try() + } + if reads.Load() != 0 { + t.Fatalf("a chat that is not waiting for storage read it %d times", reads.Load()) + } +} + +// The look is the same question the drive's own startup asked: local files only. +// Closed while the account says off and no other computer is carrying chats +// live, open the moment the permission file says on. +func TestTheStorageLookReadsTheSameLocalFilesStartupDid(t *testing.T) { + _ = storageOffNoticeConfig(t) + if storageOpenAt(home.Dir()) { + t.Fatal("storage reads as open while the permission file says off") + } + id, err := identity.Ensure(home.Dir()) + if err != nil { + t.Fatal(err) + } + if err := syncsetup.SaveStorage(home.Dir(), syncsetup.Resolve(home.Dir()).URL, id.ID(), "on"); err != nil { + t.Fatal(err) + } + if !storageOpenAt(home.Dir()) { + t.Fatal("storage reads as closed after the permission file says on") + } +} diff --git a/cmd/codeaf/synctake.go b/cmd/codeaf/synctake.go index 93c2e01ad5..bfdd1922f3 100644 --- a/cmd/codeaf/synctake.go +++ b/cmd/codeaf/synctake.go @@ -33,7 +33,7 @@ import ( var surfaceNotices = tui3.NewNotices() // wireSync gives the surface everything that needs a relay: the chats on other -// machines, `continue here`, and what a branch row can do. With sync off, or +// machines, `move here`, and what a branch row can do. With sync off, or // when it cannot start, it adds nothing and the home screen must not fail to // start over a relay setting: every seam stays nil, and a nil seam is absent. func wireSync(o *tui3.Options) { @@ -58,10 +58,12 @@ func wireSync(o *tui3.Options) { o.NotShared = terminalNotShared } moving := terminalMoving - take := takeover{c: chatContinuerWith(s, surfaceNotices.Say, moving.report, true, continueSeams{arrived: terminalArrived(surfaceNotices)}), moving: moving} + take := takeover{c: chatContinuerWith(s, surfaceNotices.Say, moving.report, true, continueSeams{arrived: terminalArrived(surfaceNotices)}), moving: moving, home: s.Home} if o.Takeover == nil { o.Takeover = take } + liveRoads = syncLiveRoads(s) + wireLive(o, s.Home) if o.Branches.Open == nil { o.Branches.Open = take.OpenBranch } @@ -291,6 +293,15 @@ func standingRefusal(err error) error { type takeover struct { c *syncsetup.Continuer moving *takeProgress + // home is this computer's home, where the last-seen copies of chats that + // other computers run are kept. Empty (a test's literal) forgets nothing. + home string +} + +// movedHere forgets the last-seen copy of a chat that now runs on this +// computer. A copy of it kept for any other computer is only a stale picture. +func (t takeover) movedHere(id string) { + forgetViewedChatEverywhere(t.home, id) } func (t takeover) IdleHandoffAllowed() bool { @@ -380,6 +391,7 @@ func (t takeover) TakeSeen(ctx context.Context, id string, seen *directory.Lease t.moving.stop(id) return tui3.Taken{}, surfaceTakeError(err) } + t.movedHere(id) if got.AlreadyHere || got.LocalOnly { t.moving.stop(id) } @@ -394,6 +406,7 @@ func (t takeover) OpenAvailable(ctx context.Context, id string, seen *directory. t.moving.stop(id) return tui3.Taken{}, surfaceTakeError(err) } + t.movedHere(id) if got.AlreadyHere || got.LocalOnly { t.moving.stop(id) } @@ -408,6 +421,7 @@ func (t takeover) OpenAvailableWithWorkspaceRoots(ctx context.Context, id string t.moving.stop(id) return tui3.Taken{}, surfaceTakeError(err) } + t.movedHere(id) if got.AlreadyHere || got.LocalOnly { t.moving.stop(id) } @@ -422,6 +436,7 @@ func (t takeover) TakeSeenWithWorkspaceRoots(ctx context.Context, id string, see t.moving.stop(id) return tui3.Taken{}, surfaceTakeError(err) } + t.movedHere(id) if got.AlreadyHere || got.LocalOnly { t.moving.stop(id) } diff --git a/docs/changes/unreleased/2965-remote-control.md b/docs/changes/unreleased/2965-remote-control.md new file mode 100644 index 0000000000..8ad8101db0 --- /dev/null +++ b/docs/changes/unreleased/2965-remote-control.md @@ -0,0 +1,30 @@ +--- +kind: added +title: A paired computer can watch and drive a chat that keeps running here, over the relay or directly +pr: 2965 +surface: [chat, engine, remote, app, docs, build] +invalidates: + - "Was true: the Home card, the devices row, the resume offer, errors and the manual called carrying a chat to this computer Continue here (and Move here only for a chat another computer was running), and the read-only notices said another computer continued this chat. Is true now: the act reads Move here everywhere, alt+m and alt+c keep their keys, the notices say ` moved this chat. This copy is read-only and may be behind` and `another device moved this chat first`, and the manual keeps one heading that answers by the old label." + - "Was true: strings that named the server called it the sync service, and the word relay was also an ordinary verb in the Factory manager's instructions and manual (`relay what it answers`). Is true now: the server is the relay in refusals, pairing and status lines, `--help` and the manual, the word relay names only the server and its storage switch, the Factory wording is `report` and `passes on`, and a new test in internal/wordlaw keeps the old words out of strings and the manual." + - "Was true: the Devices setting that lets the relay keep sealed copies was called sync storage, in the row, `/status`, refusals and the access request a person files. Is true now: it is relay storage in all of them, the request's issue title is `relay storage access: `, and searching Settings for the old name still finds the row." + - "Was true: Enter on a Home row for a chat another of your computers was running always asked `Move this chat here?`. Is true now: with remote control on and that computer online, Enter opens the chat live (`on · live`), waiting for the list of your computers when Home has only just drawn; the card is behind alt+m on Home, alt+c on the resume card and the Move here verb of the devices row, and a computer that is offline or not on the list still gets the card." + - "Was true: with relay storage off the only way into another computer's chat was to move it while both computers ran, and the desktop could message a chat another computer was running only through a waiting note, which needs relay storage. Is true now: with remote control on a live view needs no storage, only both computers online, and typing goes straight to the chat where it runs; only a message for a computer that is offline still waits for relay storage." + - "Was true: watching a chat on another computer never typed into it, and a newly paired computer was told only ` is now paired. Your chats can continue there.` Is true now: with typing allowed for that computer a live view types into the chat where it runs; the line reads ` is now paired. can also see and control your chats here. Change that in /devices.`; a computer paired from now on watches and types, a computer paired before watches only and Home asks once `Let your other computers type into chats here?`; `w` and `t` on a computer's `/devices` row, or `codeaf devices permit --watch on|off --drive on|off`, change it per computer." + - "Was true: a message sent as a remote link dropped was not resent by the redial, and a holder applied every message each time it arrived. Is true now: a live view's redial resends in-flight messages that carry a client id, the holder remembers the ids it has applied for each device, and a resend after a drop is answered as already done." + - "Was true: a viewer that joined a chat over the remote wire was treated as an ordinary window of the holder with every verb open, and any answer from a window could settle any waiting ask. Is true now: a viewer arriving from another computer is a guest with a short list of verbs, a write deadline, an outbound cap and a bounded reader; its answer to an ask that cannot be taken back, or to a consent that widens its scope, is refused with `That one needs your OK on itself. Answer it there.`, and anything else that would change that computer's settings or files is refused with ` does not allow that from another computer`." + - "Was true: a paired computer could reach another computer only for files, a chat held by an engine-host daemon could be watched from another computer only over ssh with `--host`, and removing a computer stopped its next connection only. Is true now: with remote control on, the same registration carries live connections that the holder's router authenticates and hands to the process that holds the chat, up to 14 viewers at a time; removing or revoking a computer, or changing what it may do, cuts its live connections at once; a holder too old to know about live views is refused and the viewer says `Restart codeaf on to share this chat`." + - "Was true: when another computer took a chat a window was showing, the window became a read-only copy that said ` moved this chat. This copy is read-only and may be behind`. Is true now: with remote control on and the new holder online, the window (terminal or desktop) opens the chat live of the new holder; the terminal asks again after 1, 2, 4, 8 and 15 seconds while it is still on that chat and the directory still names the same computer, until the new holder has opened it, and the read-only sentence is still said at the first miss." + - "Was true: a chat this desktop ran was not offered to other computers, and a chat another computer ran could be shown only as a stored copy. Is true now: with remote control on, the desktop engine opens another computer's chat live (`chats.open_live`) and offers the chats it runs through a holder door, keeping a chat open while another computer watches it and ending their view when the chat is closed; it announces `settings.remote_control` in its hello and reads and writes the same `remote_control` row as the terminal, pinned by `CODEAF_REMOTE_CONTROL` when that is set; and it reports who has the keyboard of a chat it holds and lets the desktop take it back (`chats.live_keyboard`)." + - "Was true: a chat reached your other computers' Home only after its first turn ended, and a chat held back for want of another paired computer, once a different process paired this one, waited for a once-a-minute check. Is true now: with remote control on, the chat appears on the other computers' Home marked `working on ` when its first turn starts, as a directory record only (which computer runs it and that it is working, no words), and a chat nobody has typed in appears nowhere; a chat opened with /new is saved on its own computer when that first turn starts so the row has something to stand on, and with relay storage off that copy stays there and the row carries no title; a held-back chat is shared at the next touch, with at most one local check every two seconds; a row left by a computer that stopped mid-turn stays `untitled` until the chat is opened again there." + - "Was true: every dial to a computer shared its 16 relay streams first come first served, a stream was never cut for its rate, and no relay told a refused caller when to come back. Is true now: a dial may say what it is for in a `Codeaf-Door` header; a `live` dial stops once the computer has 14 streams attached, so two are always free for a `move` dial, while a dial that says nothing, which is every dial from an older build, still gets all 16; a live stream that sustains more than 4 MiB/s over 5 s is closed with code 1008, counted when a message arrives and never from a timer; the two rate-limit refusals (30 dials and 10 registrations a minute) carry `Retry-After`; on the hosted relay this takes effect when its Worker is deployed." + - "Was true: after a dropped link `codeaf serve`, the pairing host and the task door redialled the relay after exactly 1 s, 2 s, 4 s, so a relay restart brought every computer back in the same second, and every redialling client waited one second first. Is true now: those three hosts and the link of a live view, the roads dialled through a relay, wait 1 s plus a random 0 to 5 s first and each later wait is the doubling schedule times a random 0.75 to 1.25; an ssh `--host`, a local socket and an engine pipe keep the fixed one-second first pause that doubles up to 15 seconds." + - "Was true: every connection between two paired computers travelled through the relay, and a live view said nothing about its road. Is true now: with remote control on, about half a second after a view opens the two computers try to connect directly over a WebRTC data channel, signalled through the relay tunnel already open and served with the same handshake, permit and device list; when that works the view moves to the direct road without a notice, `/status` has a `road` row that says `live · direct` or `live · relay`, the desktop is told the road too, a direct road that stops working hands the view back to the relay within 5 seconds when the relay is reachable, and a network that blocks UDP stays on the relay. Move still goes through the relay." + - "Was true: nothing let a person choose how a live view travels or which servers help two computers find each other. Is true now: `CODEAF_REMOTE_ROAD=relay` on either computer keeps every view on the relay and asks no STUN server, `CODEAF_REMOTE_STUN` replaces the default Cloudflare then Google STUN servers with a comma list of `host:port` (`off` asks none), no TURN server is ever used, and `CODEAF_REMOTE_CONTROL` fixes the remote control setting for the run." + - "Was true: a pair record was written to its stream in two writes, a two-byte length and then the body. Is true now: a record is exactly one write, with the same bytes on the wire, which halves the relay messages a record costs." + - "Was true: every redial after a dropped remote link waited its pause and said `reconnecting`, and a viewer that came back had to ask for the keyboard again. Is true now: a link closed on purpose to change roads is redialled at once and the `reconnecting` note waits three quarters of a second; a live view keeps the keyboard across a redial only if it is the same authenticated device and the same window, for up to 30 seconds, and a first arrival still asks; the sentences a live view said about itself, such as `could not move this chat here`, stay across the re-sync." +--- +Remote control is off until it is turned on, on both computers: `/settings` → `Devices` → `remote control`, or `CODEAF_REMOTE_CONTROL=1`. Turning it on or off in a running terminal takes effect at once, with no restart. Turning it off refuses new live views at once and ends open ones within about 30 seconds with ` turned remote control off.`, after which the viewer does not redial by itself; the chats keep running, a live view's folder never becomes Home's project, and a quit leaves a live view of another computer's chat out of what it records for resume. +Live traffic is sealed end to end, so the relay cannot read it and stores none of it; with relay storage off the relay keeps no words, titles or folder names of your chats, only the small directory record that says which computer holds each chat and whether a turn is running. The relay sees how much traffic there is, when, and which of your computers are connected. +Limits: one line is at most 256 KiB; a live view is paced at 1 MiB/s each way; the host keeps a soft allowance of 256 MiB of relay traffic per UTC day (`CODEAF_REMOTE_DAILY_MB`; spent, views turn watch only until 00:00 UTC, and direct traffic is not counted); live views take 14 of a computer's 16 relay streams, two stay free for Move; a live stream above 4 MiB/s for 5 s is cut. +One computer types into a live chat at a time; the other reads `typing from now · enter types here`, its first `enter` takes the keyboard and sends nothing, and letters or commands typed while it does not hold the keyboard go nowhere. +The direct road needs no setup and falls back to the relay. It links the pion WebRTC stack, which grows the binary by about 9.5 MB; with remote control off, or with `CODEAF_REMOTE_ROAD=relay`, none of it runs. diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 4052a7dcd0..91b6d7a1d6 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -433,6 +433,8 @@ keeps the value in a private file the agent's commands read (the model's own | method | params | result | |---|---|---| | `chats.list` | `{}` | `ChatsResult` | +| `chats.live_keyboard` | `ChatLiveKeyboardParams` | `ChatLiveKeyboardResult` | +| `chats.open_live` | `ChatOpenLiveParams` | `ChatOpenLiveResult` | | `chats.read` | `ChatReadParams` | `ChatReadResult` | | `chats.preview` | `{cell}` | `{last_user?: string, last_assistant?: string}` | | `chats.send` | `ChatSendParams` | `ChatSendResult` | @@ -451,6 +453,7 @@ keeps the value in a private file the agent's commands read (the model's own | method | params | result | |---|---|---| | `devices.list` | `in.DeviceListParams` | `DevicesResult` | +| `devices.permit` | `in.DevicePermitParams` | `DevicePermitResult` | | `devices.remove` | `in.DeviceRemoveParams` | `DeviceRemoveResult` | | `devices.rename` | `in.DeviceRenameParams` | `DeviceRenameResult` | @@ -3148,6 +3151,26 @@ flight finish and are billed. Terminal Build saves an explicit on. `cost_note` is the shared `config.MemoryCostNote` disclosure, including the example of one small DeepSeek V4.1 Flash job at 39% ($0.0124 of $0.0315). +An engine whose hello carries `settings.remote_control` includes +`remote_control: bool` in Settings (`settings.get`, `settings.set`, and +`settings.changed`), always, off as `false`, and `remote_control_pinned_by: +string` only when an environment variable fixes the value, which makes the +switch read only. It is the row the terminal's Settings > Devices tab writes, in +the engine's own profile. `settings.set` takes optional `remote_control: bool`; +any non-boolean, including null, is `bad_params`, and so is the field sent to an +engine without the feature (`settings has no field remote_control`), so a window +draws the switch only when the word is in the hello. A write the environment +pins is refused whole, before any other field of the patch lands, as +`bad_params` with `Remote control is set by CODEAF_REMOTE_CONTROL`. ON applies +to chats opened afterwards: the holder door starts with the next chat the +desktop opens, and chats already open stay as they were. `chats.live` and +`devices.permit` are announced in the hello, which is read once when the engine +starts, so they appear only after the engine restarts; a window that finds the +switch and `devices.permit` disagreeing says so and offers the restart. OFF +applies at once: the door stops handing chats out and every view another +computer has of a chat this desktop holds is ended (that computer reads it as the +chat closing); the desktop's own chats go on and keep what was said. + An engine whose hello carries the feature `settings.models.auxiliary` adds a fourth role to the task models: `roles.auxiliary` in `settings.models.get` (and in `settings.changed`'s `task_models`) is `{pin, warning, eligible_count}` like @@ -3648,6 +3671,58 @@ Example row: `{"cell":"01M7H89T8KA9W804DZX67NFAAT","title":"Todo CLI in Python","here":false,"status":"running","crew":"da48d479ea82","crew_name":"Todo crew","crew_manager":true,...}`. +Remote control (a live view). `chats.live` in `hello` says `chats.open_live +{cell}` and `chats.live_keyboard {agent, take?}` exist and rows may carry +`can_live:true`. It is absent unless the engine can dial the live door AND the +person turned Remote control on, so a client that never sees it must never send +either call. `can_live` is true on a row whose chat another computer holds and +runs while that computer is online. `chats.open_live` opens that chat WITHOUT +moving it and answers an `agent`, a local-looking one: its `location` carries +`here:false`, the chat's `cell`, `holder`, `can_take` and `seen` as for any held +chat (so `agents.take` still works from it) plus `live`. Everything the app does +in a chat is the agent's own call: a live send is `agents.send` on that agent, +never `chats.send`; steer, queue, stop, close and `asks.answer` likewise; older +messages are `agents.entries {before, limit}`. Opening it again is how a view +that detached or went offline is repaired, and answers the same agent id. It +refuses with `not_found` (the chat is not listed), `unreachable` (the computer +is not on, is not running that chat, or needs a restart, each in its own +sentence), or `conflict` (that computer does not share its chats with this one, +or this computer was removed). Every refusal carries the sentence a person +reads and `detail:{kind:"live_refused", reason}` with the closed reason. + +`location.live` is `{state, driver?, road?, seen_at?, permit?}`. `state` is +`live`, `reconnecting`, `offline`, `idle` (the view detached after ten quiet +minutes and sent nothing first) or `watching` (the holder allows reading and not +typing, or its daily allowance is used). `driver` is `{yours?, machine?, here?}` +and is present only when another window holds the keyboard; `chats.live_keyboard +{agent, take:true}` asks for it and answers `{driver}`. `road` is `relay`. +`seen_at` is RFC 3339. `permit` is `{watch, drive, reason?}`; `reason` is the +finished sentence for why typing is off, shown verbatim. Every change to any of +these arrives as one `agent.changed` carrying the whole agent; there is no new +event and no field on `turn.delta` or `turn.thinking`. A live agent is left out +of `agents.list`. + +`location.keyboard` is `{yours?, machine?, here?}`, the same three words as a +live view's `driver`, on a chat THIS computer holds and runs when another window +than the one drawing it has the keyboard: another of the person's computers that +took it, or another window here. It rides on the existing `agent.changed` of +that agent and nowhere else, with Remote control on (`chats.live` in `hello`); +absent says the window drawing the chat holds the keyboard, which is every chat +nobody else has joined, and with Remote control off no agent ever carries it. A +window that sees it draws who is typing and offers one button, which is +`chats.live_keyboard {agent, take:true}` on the held agent itself (not a live +one): it asks the engine for the keyboard and answers `{driver}` as it does for +a live view. A held agent whose chat is not open to other computers answers +`conflict` as before. + +`devices.permit {id, watch?, drive?}` edits ONLY this computer's own book of what +a paired computer may do in chats here (`devices.permit` in `hello`, absent while +Remote control is off); a switch left out keeps what it was. Each device row +then carries `permit:{watch, drive}` (absent on this computer's own row and on a +removed one). The answer is `{device?, line?}` and `devices.changed` follows +with the whole roster. A permit edited by the terminal's `codeaf devices permit` +arrives the same way. + Before a move, a row says what it would copy: `folder` is the name of the folder the chat works in on its holder (absent for a chat in its own private folder, from older publishers, or from a relay that does not answer diff --git a/docs/testing-anywhere.md b/docs/testing-anywhere.md index 7d2cc0f90b..af613aaa6d 100644 --- a/docs/testing-anywhere.md +++ b/docs/testing-anywhere.md @@ -240,8 +240,8 @@ already has your work, B is the new one. This is what each step should look like 6. **See B from A.** A's home shows a devices row with both machines online (filled dots). `/devices` lists both. 7. **The continue card.** Close the chat on B (or leave B idle), reopen A. A offers "Continue - where you left off on ?". Enter chooses "continue here". -8. **Move.** A asks "Continue this chat here?". Confirm. A prints a banner "Moved from + where you left off on ?". Enter chooses "move here". +8. **Move.** A asks "Move this chat here?". Confirm. A prints a banner "Moved from in N s" and opens the chat with a resume card: the files not yet committed, the last test run and what B saw. Your folder is the same, file for file. 9. **Take it back.** Do step 5 to 8 the other way: work on A, then on B continue the same chat diff --git a/docs/ux-pairing-contract.md b/docs/ux-pairing-contract.md index eba4fff45a..cd5b2c864e 100644 --- a/docs/ux-pairing-contract.md +++ b/docs/ux-pairing-contract.md @@ -5,8 +5,9 @@ nothing of this file keeps working: the six-digit code path (`/v1/pair`, interna internal/pair), `{"v":N}` watch frames, `POST /v1/dir/devices/{id}/revoke` and the existing `directory.Device` JSON all stay as they are. -Words in UI strings follow the vocabulary law: "device", "Move here", "Continue here". The words in -this file (relay, node, lease, manifest) never reach a screen. +Words in UI strings follow the vocabulary law: "device", "Move here". The words in +this file (node, lease, manifest) never reach a screen, and "relay" reaches one only as the name of +the server and its storage switch. Conventions: JSON bodies; errors are `{"err":""}` with the status given (the relay's existing shape, `wire.js`). Times are Unix milliseconds. `b64u` is unpadded base64url. Every answer carries diff --git a/go.mod b/go.mod index 6e9d8abde6..2d7f7f17d5 100644 --- a/go.mod +++ b/go.mod @@ -24,6 +24,11 @@ require ( github.com/int128/oauth2cli v1.18.0 github.com/invopop/jsonschema v0.14.0 github.com/modelcontextprotocol/go-sdk v1.7.0 + github.com/pion/ice/v4 v4.4.9 + github.com/pion/logging v0.2.4 + github.com/pion/stun/v4 v4.0.1 + github.com/pion/transport/v5 v5.1.5 + github.com/pion/webrtc/v4 v4.2.29 github.com/rivo/uniseg v0.4.7 github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 github.com/segmentio/encoding v0.5.4 @@ -43,14 +48,26 @@ require ( ) require ( - github.com/fxamacker/cbor/v2 v2.9.4 // indirect + github.com/fxamacker/cbor/v2 v2.9.4 github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/go-webauthn/webauthn v0.18.2 github.com/go-webauthn/x v0.3.1 // indirect github.com/golang-jwt/jwt/v5 v5.3.1 // indirect github.com/google/go-tpm v0.9.8 // indirect github.com/philhofer/fwd v1.2.0 // indirect + github.com/pion/datachannel v1.6.4 // indirect + github.com/pion/dtls/v3 v3.1.16 // indirect + github.com/pion/interceptor v0.1.51 // indirect + github.com/pion/mdns/v2 v2.2.2 // indirect + github.com/pion/randutil v0.1.0 // indirect + github.com/pion/rtcp v1.2.20 // indirect + github.com/pion/rtp v1.10.6 // indirect + github.com/pion/sctp v1.12.1 // indirect + github.com/pion/sdp/v3 v3.0.20 // indirect + github.com/pion/srtp/v3 v3.1.3 // indirect + github.com/pion/turn/v5 v5.1.3 // indirect github.com/tinylib/msgp v1.6.4 // indirect + github.com/wlynxg/anet v0.0.5 // indirect github.com/x448/float16 v0.8.4 // indirect ) diff --git a/go.sum b/go.sum index 5c708f5c22..b668125932 100644 --- a/go.sum +++ b/go.sum @@ -192,6 +192,38 @@ github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP github.com/pb33f/ordered-map/v2 v2.3.1/go.mod h1:qxFQgd0PkVUtOMCkTapqotNgzRhMPL7VvaHKbd1HnmQ= github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +github.com/pion/datachannel v1.6.4 h1:yFynqnFQ2Z+R01+kJmcU6SAMemRst972ZjKJVtb8/4Y= +github.com/pion/datachannel v1.6.4/go.mod h1:AyOmAGX4Y8UHfhGTXwL5bwpIfCD2GPxfm2+h00WJ7nQ= +github.com/pion/dtls/v3 v3.1.16 h1:xZgZsNO24nM3wNGHvmKCt/6J6nwy6KORjFY0YlQGDdA= +github.com/pion/dtls/v3 v3.1.16/go.mod h1:iKFQNYrjsN2TiA2YKKMqB9MOZaFpjFULBI/A4sW0eyc= +github.com/pion/ice/v4 v4.4.9 h1:lZH1vq+mdXfxuZhcbarK6kcLkBbijgILFN+/CdDi3Ws= +github.com/pion/ice/v4 v4.4.9/go.mod h1:zCRRg4Mkpdbx9B+75fd4z2APvIXeIraeUOB7IMPt8mU= +github.com/pion/interceptor v0.1.51 h1:PU09y6RghjWXR4AYJ+AVNyDX7EmgIZuDFMGDl6smKQA= +github.com/pion/interceptor v0.1.51/go.mod h1:nVgAA8pNNhaglm6NSe9lMuFhmi8kwWbf7Whw1ukt9VU= +github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8= +github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so= +github.com/pion/mdns/v2 v2.2.2 h1:qq9Kj3PnjF0mfSwd8Icu0CXy5aoYdQKnNUIsGPeUpgk= +github.com/pion/mdns/v2 v2.2.2/go.mod h1:ZX5f0AAH1D6TOjdjvcBORZZHaZuG0t9+br78lHEwiJ4= +github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA= +github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8= +github.com/pion/rtcp v1.2.20 h1:ZxQpb1Z3st9W5Rts4PjGoC3ynDhUtQ9B/itKJho8h2I= +github.com/pion/rtcp v1.2.20/go.mod h1:vX7Es6skWYm4oVvOSC5+4WHLYUTZHcbGNmk5wjzMGH4= +github.com/pion/rtp v1.10.6 h1:1qs356bmniSc89gTF1KFdI0kej7qTdIUSnHOXu3P2EY= +github.com/pion/rtp v1.10.6/go.mod h1:qvV617FVkp5DBUfoHGxP8uOnTI4UaNDJK0z7Sildylk= +github.com/pion/sctp v1.12.1 h1:C9av2iqCNGUeO5gAro4lNdknZxdQojIyV1v/EdI4gzw= +github.com/pion/sctp v1.12.1/go.mod h1:+lrF9pgQonc0JWC3FU9pzFJAl33eJY24uf0chnDY/38= +github.com/pion/sdp/v3 v3.0.20 h1:TS6DViqcmp+49f0+mjw9anbr9xY3vJtsZewxAvlMCRQ= +github.com/pion/sdp/v3 v3.0.20/go.mod h1:slIMXDK5OKj0nhISwjfeN18AzTBCt2LYZq9uPw0cU5Q= +github.com/pion/srtp/v3 v3.1.3 h1:O3sfbfWfq/OyEaXRbX02Z0SNQRijS9nDdc/DEb8jxlU= +github.com/pion/srtp/v3 v3.1.3/go.mod h1:v3uQtrCz9LH3aahau0jtzRDsWGwKkh4a0BiBwzzxhtQ= +github.com/pion/stun/v4 v4.0.1 h1:S2ggK4hsUJJKoZfpL90uIqIRTj6xJ0NOIEkXgcpQif0= +github.com/pion/stun/v4 v4.0.1/go.mod h1:byktbPA8U7HjJ2H8w3moP7nzq0Q+kYNulvMLPaubQL4= +github.com/pion/transport/v5 v5.1.5 h1:73fa352Y9dq85kCd9rzyBV7wd/qhAiBIuTtwzWO3WS0= +github.com/pion/transport/v5 v5.1.5/go.mod h1:Qxw6fCEjFWQkRDZOhS4Vf+neJBcihauvA3uyEa1J1F0= +github.com/pion/turn/v5 v5.1.3 h1:dxBq+M6o5DCxIjtiBQNvtHkKshS+xlJbXwgc1MKzBH8= +github.com/pion/turn/v5 v5.1.3/go.mod h1:ocKg/4W5d4N9hvpADSwoc5HdU53/4i966FIU1qJL0tY= +github.com/pion/webrtc/v4 v4.2.29 h1:uL1F7paed+teOlkBKaO2GO3H70paTa22FeJLy5iOG74= +github.com/pion/webrtc/v4 v4.2.29/go.mod h1:MP1ZQZocg9mRkfbmpQi8hxjehjWgTHgmO1w+mMSQwDM= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= @@ -212,6 +244,8 @@ github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWD github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ= github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA= +github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU= +github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= diff --git a/internal/appwire/chats.go b/internal/appwire/chats.go index ed97a1fd90..fc2765daf7 100644 --- a/internal/appwire/chats.go +++ b/internal/appwire/chats.go @@ -1,6 +1,9 @@ package appwire -import "time" +import ( + "encoding/json" + "time" +) const ( FeatureChatsTake = "chats.take" @@ -43,6 +46,11 @@ const ( // a holder whose build or relay does not say carries none (a loose row). FeatureChatsCrew = "chats.crew" FeatureSyncRelay = "sync.relay" + // FeatureChatsLive says chats.open_live and chats.live_keyboard exist and + // chat rows carry can_live: a chat another computer holds can be opened as a + // live view and typed into there, with nothing moved. It is absent unless + // the engine can dial that computer and remote control is on. + FeatureChatsLive = "chats.live" EventChatChanged = "chat.changed" EventChatRemoved = "chat.removed" ) @@ -90,6 +98,9 @@ type ChatRow struct { // Working says the holder has a turn or background work still to settle // and save (status running only). Absent while it is merely open there. Working bool `json:"working,omitempty"` + // CanLive says chats.open_live may be asked for this chat now: the computer + // holding it is online and running it, and this engine can dial it. + CanLive bool `json:"can_live,omitempty"` // Notes are the messages this computer wrote to the chat while another // computer held it, oldest first: waiting until that computer takes one into // the chat's queue, then delivered. Delivered ones are kept while this engine @@ -188,6 +199,56 @@ type TakeParams struct { type TakeResult struct { Agent Agent `json:"agent"` } + +// ChatOpenLiveParams is chats.open_live: the chat another computer holds, by +// its cell id. +type ChatOpenLiveParams struct { + Cell string `json:"cell"` +} + +// ChatOpenLiveResult is the chat as a local-looking agent. Its location carries +// live; a send into it is agents.send, never chats.send. +type ChatOpenLiveResult struct { + Agent Agent `json:"agent"` +} + +// ChatLiveKeyboardParams is chats.live_keyboard: take, or only ask who holds, +// the keyboard of an agent opened live. +type ChatLiveKeyboardParams struct { + Agent string `json:"agent"` + Take bool `json:"take,omitempty"` +} + +// ChatLiveKeyboardResult says who holds the keyboard now. +type ChatLiveKeyboardResult struct { + Driver LiveDriver `json:"driver"` +} + +// ChatsLiveOpener opens a chat another computer holds as a live view. +type ChatsLiveOpener interface { + OpenLive(ChatOpenLiveParams) (Agent, error) + LiveKeyboard(ChatLiveKeyboardParams) (ChatLiveKeyboardResult, error) +} + +// CallNoter is an optional engine door that hears of each agents.* call as it +// arrives, before it is run. It must not block: it only notes that the person +// touched the agent the params name. +type CallNoter interface { + NoteCall(method string, params json.RawMessage) +} + +// LiveRefused is the detail of a refused chats.open_live: the closed reason a +// live door gives (not-running, not-allowed, holder-old, removed, ...), beside +// the sentence the person reads. +type LiveRefused struct { + Kind string `json:"kind" enum:"live_refused"` + Reason string `json:"reason"` +} + +// ChatsLiveOffer is an engine's answer to whether live views are on now. A +// capability that cannot work is absent, not broken: an engine that answers +// false does not advertise chats.live, so no client shows the verb. +type ChatsLiveOffer interface{ ChatsLiveOffered() bool } type TakeCancelParams struct { Cell string `json:"cell"` } @@ -298,6 +359,11 @@ func withChatsFeatures(h Hello, e Engine) Hello { h = withFeature(h, FeatureChatsSend) } } + if _, ok := e.(ChatsLiveOpener); ok { + if offer, asked := e.(ChatsLiveOffer); asked && offer.ChatsLiveOffered() { + h = withFeature(h, FeatureChatsLive) + } + } if d, ok := e.(ChatsReader); ok && d.CanReadChats() { h = withFeature(h, FeatureChatsReadPaged) } @@ -333,7 +399,7 @@ func init() { methods["agents.take"] = typed(func(e Engine, p TakeParams) (*TakeResult, error) { d, ok := e.(ChatsTaker) if !ok { - return nil, Errorf(CodeUnknownMethod, "this engine does not continue chats here") + return nil, Errorf(CodeUnknownMethod, "this engine does not move chats here") } if _, err := required("cell", p.Cell); err != nil { return nil, err @@ -358,6 +424,28 @@ func init() { got, err := d.SendToChat(p) return &ChatSendResult{Note: got}, err }) + methods["chats.open_live"] = typed(func(e Engine, p ChatOpenLiveParams) (*ChatOpenLiveResult, error) { + d, ok := e.(ChatsLiveOpener) + if offer, asked := e.(ChatsLiveOffer); !ok || !asked || !offer.ChatsLiveOffered() { + return nil, Errorf(CodeUnknownMethod, "this engine does not open chats on other computers live") + } + if _, err := required("cell", p.Cell); err != nil { + return nil, err + } + got, err := d.OpenLive(p) + return &ChatOpenLiveResult{Agent: got}, err + }) + methods["chats.live_keyboard"] = typed(func(e Engine, p ChatLiveKeyboardParams) (*ChatLiveKeyboardResult, error) { + d, ok := e.(ChatsLiveOpener) + if offer, asked := e.(ChatsLiveOffer); !ok || !asked || !offer.ChatsLiveOffered() { + return nil, Errorf(CodeUnknownMethod, "this engine does not open chats on other computers live") + } + if _, err := required("agent", p.Agent); err != nil { + return nil, err + } + got, err := d.LiveKeyboard(p) + return &got, err + }) methods["chats.read"] = typed(func(e Engine, p ChatReadParams) (*ChatReadResult, error) { d, ok := e.(ChatsReader) if !ok || !d.CanReadChats() { diff --git a/internal/appwire/devices.go b/internal/appwire/devices.go index 878cbe1df0..a7e8b0817c 100644 --- a/internal/appwire/devices.go +++ b/internal/appwire/devices.go @@ -6,6 +6,10 @@ import ( const ( FeatureDevicesManage = "devices.manage" + // FeatureDevicesPermit says devices carry permit and devices.permit exists: + // what each paired computer may do in chats HERE, edited in this computer's + // own book. Absent unless remote control is on. + FeatureDevicesPermit = "devices.permit" EventDevicesChanged = "devices.changed" DevicesQuiet = "quiet" DevicesOn = "on" @@ -23,6 +27,17 @@ type Device struct { LastSeen time.Time `json:"last_seen,omitzero"` Online *bool `json:"online,omitempty"` RemoveLine string `json:"remove_line,omitempty"` + // Permit is what this paired computer may do in chats on THIS one. Absent on + // this computer's own row, on a removed one, and from an engine without the + // feature. + Permit *DevicePermit `json:"permit,omitempty"` +} + +// DevicePermit is the two switches kept for each paired computer: whether it +// may watch chats here, and whether it may type into them. +type DevicePermit struct { + Watch bool `json:"watch"` + Drive bool `json:"drive"` } type Devices struct { @@ -42,6 +57,20 @@ type DeviceRenameParams struct { type DeviceListParams struct{} +// DevicePermitParams is devices.permit. Only the switches named change; one +// that is left out keeps what it was. +type DevicePermitParams struct { + ID string `json:"id"` + Watch *bool `json:"watch,omitempty"` + Drive *bool `json:"drive,omitempty"` +} + +// DevicePermitResult is the row as it stands after the change. +type DevicePermitResult struct { + Device *Device `json:"device,omitempty"` + Line string `json:"line,omitempty"` +} + type DeviceRemoveParams struct { ID string `json:"id"` } @@ -56,6 +85,11 @@ func (p *DeviceRenameParams) UnmarshalJSON(raw []byte) error { return decodeStrict("devices.rename", raw, (*plain)(p)) } +func (p *DevicePermitParams) UnmarshalJSON(raw []byte) error { + type plain DevicePermitParams + return decodeStrict("devices.permit", raw, (*plain)(p)) +} + func (p *DeviceRemoveParams) UnmarshalJSON(raw []byte) error { type plain DeviceRemoveParams return decodeStrict("devices.remove", raw, (*plain)(p)) @@ -77,9 +111,22 @@ type DeviceManager interface { RemoveDevice(string) (DeviceRemoveResult, error) } +// DevicePermitter edits what a paired computer may do in this computer's chats. +type DevicePermitter interface { + PermitDevice(DevicePermitParams) (DevicePermitResult, error) +} + +// DevicePermitOffer is an engine's answer to whether permits are on now. +type DevicePermitOffer interface{ DevicePermitsOffered() bool } + func withDevicesFeatures(hello Hello, e Engine) Hello { if _, ok := e.(DeviceManager); ok { - return withFeature(hello, FeatureDevicesManage) + hello = withFeature(hello, FeatureDevicesManage) + } + if _, ok := e.(DevicePermitter); ok { + if offer, asked := e.(DevicePermitOffer); asked && offer.DevicePermitsOffered() { + hello = withFeature(hello, FeatureDevicesPermit) + } } return hello } @@ -102,6 +149,20 @@ func init() { got, err := door.RenameDevice(p.Name) return &got, err }) + methods["devices.permit"] = typed(func(e Engine, p DevicePermitParams) (*DevicePermitResult, error) { + door, ok := e.(DevicePermitter) + if offer, asked := e.(DevicePermitOffer); !ok || !asked || !offer.DevicePermitsOffered() { + return nil, Errorf(CodeUnknownMethod, "this engine does not set what other computers may do here") + } + if _, err := required("id", p.ID); err != nil { + return nil, err + } + if p.Watch == nil && p.Drive == nil { + return nil, Errorf(CodeBadParams, "name the switch to change: watch, drive or both") + } + got, err := door.PermitDevice(p) + return &got, err + }) methods["devices.remove"] = typed(func(e Engine, p DeviceRemoveParams) (*DeviceRemoveResult, error) { door, ok := e.(DeviceManager) if !ok { diff --git a/internal/appwire/remotecontrol_settings.go b/internal/appwire/remotecontrol_settings.go new file mode 100644 index 0000000000..b7b70294ad --- /dev/null +++ b/internal/appwire/remotecontrol_settings.go @@ -0,0 +1,20 @@ +package appwire + +// FeatureSettingsRemoteControl announces the Remote control switch: the +// `remote_control` field of settings.get and settings.set, the same row the +// terminal's Settings > Devices tab writes. A window draws its switch only +// when this word is in the hello, because an engine without the field refuses +// the whole of a settings.set that names it. +const FeatureSettingsRemoteControl = "settings.remote_control" + +// RemoteControlSettingsServer marks an engine that serves the Remote control +// switch. Like [MemorySettingsServer] it is a marker, because the answer is the +// same for the whole life of the engine: the row is always there, off or on. +type RemoteControlSettingsServer interface{ RemoteControlSettings() } + +func withRemoteControlSettingsFeature(h Hello, e Engine) Hello { + if _, ok := e.(RemoteControlSettingsServer); !ok { + return h + } + return withFeature(h, FeatureSettingsRemoteControl) +} diff --git a/internal/appwire/remotecontrol_settings_test.go b/internal/appwire/remotecontrol_settings_test.go new file mode 100644 index 0000000000..c237312a56 --- /dev/null +++ b/internal/appwire/remotecontrol_settings_test.go @@ -0,0 +1,93 @@ +package appwire + +import ( + "encoding/json" + "slices" + "strings" + "testing" +) + +// remoteControlEngine is an engine that serves the Remote control switch: the +// plain fake plus the marker the hello word follows. +type remoteControlEngine struct{ *fakeEngine } + +func (remoteControlEngine) RemoteControlSettings() {} + +// R2, R7: the switch is announced by an engine that serves it, and only by one. +// A desktop that sees no word draws no row and sends no field, because an engine +// that has the field not is refusing a whole write over it. +func TestTheRemoteControlSwitchIsAnnouncedOnlyByAnEngineThatServesIt(t *testing.T) { + plain := startWire(t, &fakeEngine{}) + if slices.Contains(features(plain.next()), any(FeatureSettingsRemoteControl)) { + t.Fatal("an engine with no remote control setting announced one") + } + fake := &fakeEngine{} + served := startWireOver(t, remoteControlEngine{fake}, fake) + if !slices.Contains(features(served.next()), any(FeatureSettingsRemoteControl)) { + t.Fatal("an engine that serves the switch did not announce it") + } + if FeatureSettingsRemoteControl != "settings.remote_control" { + t.Fatalf("the word is %q, and the desktop spells it settings.remote_control", FeatureSettingsRemoteControl) + } +} + +// R3: the switch is one more field of settings.set, read as a plain true or +// false and nothing else, the way the memory switch is; and an engine that does +// not serve it refuses it in the words an older engine used for any field it +// lacked, so the desktop's own check and the engine's agree. +func TestTheRemoteControlSwitchTravelsThroughTheSettingsDoor(t *testing.T) { + fake := &fakeEngine{} + e := remoteControlEngine{fake} + for _, tc := range []struct { + params string + want bool + }{{`{"remote_control":true}`, true}, {`{"remote_control":false}`, false}} { + fake.patch = SettingsPatch{} + if _, err := methods["settings.set"].call(e, json.RawMessage(tc.params)); err != nil { + t.Fatalf("%s: %v", tc.params, err) + } + if fake.patch.RemoteControl == nil || *fake.patch.RemoteControl != tc.want { + t.Fatalf("%s reached the engine as %+v", tc.params, fake.patch.RemoteControl) + } + if fake.patch.MemoryEnabled != nil || fake.patch.DefaultModel != nil { + t.Fatalf("%s changed a field it did not name: %+v", tc.params, fake.patch) + } + } + for _, bad := range []string{`{"remote_control":null}`, `{"remote_control":"on"}`, `{"remote_control":1}`} { + fake.patch = SettingsPatch{} + _, err := methods["settings.set"].call(e, json.RawMessage(bad)) + if codeOf(err) != CodeBadParams { + t.Fatalf("%s = %v, want bad_params", bad, err) + } + if fake.patch.RemoteControl != nil { + t.Fatalf("%s reached the engine", bad) + } + } + _, err := methods["settings.set"].call(&fakeEngine{}, json.RawMessage(`{"remote_control":true}`)) + if codeOf(err) != CodeBadParams || !strings.Contains(err.Error(), "settings has no field remote_control") { + t.Fatalf("an engine without the switch answered %v", err) + } +} + +// R3, R4, R7: the read carries the value and, when the environment fixes it, +// the name that does; an engine that does not serve the switch sends neither, so +// a reader that predates it sees the same bytes it always saw. +func TestTheRemoteControlSettingIsReadAsTheSwitchAndWhatPinsIt(t *testing.T) { + on := true + raw, err := json.Marshal(Settings{RemoteControl: &on, RemoteControlPinnedBy: "CODEAF_REMOTE_CONTROL"}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(raw), `"remote_control":true`) || !strings.Contains(string(raw), `"remote_control_pinned_by":"CODEAF_REMOTE_CONTROL"`) { + t.Fatalf("the read says %s", raw) + } + off := false + raw, err = json.Marshal(Settings{RemoteControl: &off}) + if err != nil || !strings.Contains(string(raw), `"remote_control":false`) || strings.Contains(string(raw), "pinned_by") { + t.Fatalf("an off switch says %s, %v", raw, err) + } + raw, err = json.Marshal(Settings{}) + if err != nil || strings.Contains(string(raw), "remote_control") { + t.Fatalf("an engine without the switch says %s, %v", raw, err) + } +} diff --git a/internal/appwire/server.go b/internal/appwire/server.go index 4f80fad54b..0708276c6e 100644 --- a/internal/appwire/server.go +++ b/internal/appwire/server.go @@ -225,6 +225,7 @@ func (s *Server) Serve(ctx context.Context, in io.Reader, hello Hello, engine En hello = withInboxDismissFeature(hello, engine) hello = withTaskModelsAuxiliaryFeature(hello, engine) hello = withMemorySettingsFeature(hello, engine) + hello = withRemoteControlSettingsFeature(hello, engine) hello = withTaskModelsInsightFeature(hello, engine) hello = withProcessFeatures(hello, engine) hello = withProcessActionFeature(hello, engine) @@ -423,6 +424,12 @@ func (s *Server) handle(ctx context.Context, line []byte, engine Engine, infligh s.send(frame{id: id, err: Errorf(CodeBadParams, "params must be an object")}) return false } + // An engine that keeps live views of other computers is told of every + // agents.* call as it arrives, so a view that is being used is not detached + // for being idle. Telling it never waits and never changes the answer. + if noter, ok := engine.(CallNoter); ok && strings.HasPrefix(req.Method, "agents.") { + noter.NoteCall(req.Method, params) + } inflight.Add(1) go func() { defer inflight.Done() diff --git a/internal/appwire/setup.go b/internal/appwire/setup.go index 137c96adcb..6446793486 100644 --- a/internal/appwire/setup.go +++ b/internal/appwire/setup.go @@ -159,6 +159,14 @@ var setupMethods = map[string]method{ if err != nil { return nil, err } + if patch.RemoteControl != nil { + // An engine that does not serve the switch says what an older one + // said of any field it lacked, so a window that checked the hello + // and one that did not get the same answer. + if _, ok := e.(RemoteControlSettingsServer); !ok { + return nil, Errorf(CodeBadParams, "settings has no field remote_control") + } + } settings, err := e.SetSettings(patch) if err != nil { return nil, err @@ -222,6 +230,7 @@ type SettingsPatchWire struct { KnowledgeModel *string `json:"knowledge_model,omitempty"` WhenPlanPaused map[string]string `json:"when_plan_paused,omitempty"` MemoryEnabled *bool `json:"memory_enabled,omitempty"` + RemoteControl *bool `json:"remote_control,omitempty"` DefaultModel *string `json:"default_model,omitempty"` AsksBefore *string `json:"asks_before,omitempty"` WorkFolder *string `json:"work_folder,omitempty"` @@ -372,6 +381,13 @@ func decodeSettingsPatch(raw json.RawMessage) (SettingsPatch, error) { } else { err = flag(name, &patch.MemoryEnabled) } + case "remote_control": + // A switch has no "none": null would otherwise read as "leave it". + if strings.TrimSpace(string(fields[name])) == "null" { + err = Errorf(CodeBadParams, "remote_control must be true or false") + } else { + err = flag(name, &patch.RemoteControl) + } case "dock_badge": err = flag(name, &patch.DockBadge) case "checks_model": diff --git a/internal/appwire/sync.go b/internal/appwire/sync.go index 9ce010d6f2..b61b3ecd19 100644 --- a/internal/appwire/sync.go +++ b/internal/appwire/sync.go @@ -76,6 +76,65 @@ type Location struct { Here bool `json:"here"` Holder *LocationHolder `json:"holder,omitempty"` Line string `json:"line,omitempty"` + // Live says the chat is open as a live view of the computer that holds it + // (chats.open_live), and how that view stands. It rides on the existing + // agent.changed; a client that does not know the feature never receives an + // agent that carries it. Absent for every chat that is held here or only read. + Live *LocationLive `json:"live,omitempty"` + // Keyboard says who holds the keyboard of a chat that is held and run on + // THIS computer when another window than the one drawing it does: another + // of the person's computers that took it, or another window here. It is the + // same three words a live view's driver says, and it rides on the existing + // agent.changed with remote control on and nowhere else. Absent says the + // window drawing the chat holds it, which is every chat with nobody else in + // it. chats.live_keyboard {agent, take:true} takes it back for this window. + Keyboard *LiveDriver `json:"keyboard,omitempty"` +} + +// The states of a live view, as the app reads them. An unknown state is read as +// live, and the permit then decides what the person may do in it. +const ( + LiveStateLive = "live" + LiveStateReconnecting = "reconnecting" + LiveStateOffline = "offline" + LiveStateIdle = "idle" + // LiveStateWatching is the holder's own verdict that this computer may read + // the chat and not type in it: the permit it holds, or the day's allowance used. + LiveStateWatching = "watching" +) + +// LocationLive is how a live view of a chat on another computer stands. +type LocationLive struct { + State string `json:"state" enum:"live,reconnecting,offline,idle,watching"` + // Driver names who holds the keyboard when it is not this window. Absent + // says nobody else does. + Driver *LiveDriver `json:"driver,omitempty"` + // Road is how the bytes travel: "relay", or "direct" once the two computers + // have connected to each other. It changes while a view is open and the engine + // says so with an agent.changed of its own; it is a word of the strip and + // nothing a call may depend on. + Road string `json:"road,omitempty"` + // SeenAt is when the other computer was last heard from, RFC 3339. + SeenAt string `json:"seen_at,omitempty"` + // Permit is what the other computer lets this one do in the chat. + Permit *LivePermit `json:"permit,omitempty"` +} + +// LiveDriver is who holds the keyboard of a live chat, as the engine's own +// driver fact says it. Yours is this window; Machine names another computer; +// Here is another window on this computer. +type LiveDriver struct { + Yours bool `json:"yours,omitempty"` + Machine string `json:"machine,omitempty"` + Here bool `json:"here,omitempty"` +} + +// LivePermit is what the computer holding the chat lets this one do in it. +// Reason is a finished sentence for why typing is off, shown unchanged. +type LivePermit struct { + Watch bool `json:"watch"` + Drive bool `json:"drive"` + Reason string `json:"reason,omitempty"` } type LocationHolder struct { diff --git a/internal/appwire/wire.go b/internal/appwire/wire.go index 96d114970e..ab9bba2077 100644 --- a/internal/appwire/wire.go +++ b/internal/appwire/wire.go @@ -780,6 +780,13 @@ type Settings struct { // the posture ladder: the gate a conversation that follows Settings // stands at. Read only; settings.set changes it through asks_before. ApprovalPosture string `json:"approval_posture,omitempty" enum:"ask,guardian,allow,deny"` + // RemoteControl is the Remote control switch: whether another computer of + // this person's may open the chats this one runs. It is present only from + // an engine that announces settings.remote_control, and then always, off + // as false. RemoteControlPinnedBy names the environment variable that + // fixes the value, which makes the switch read only; absent is not pinned. + RemoteControl *bool `json:"remote_control,omitempty"` + RemoteControlPinnedBy string `json:"remote_control_pinned_by,omitempty"` } // SettingsPatch is settings.set's params: only the fields present change. A @@ -789,6 +796,7 @@ type SettingsPatch struct { KnowledgeModel *string WhenPlanPaused map[string]string MemoryEnabled *bool + RemoteControl *bool DefaultModel *string BudgetUSD *Figure AsksBefore *string diff --git a/internal/atlas/pairing.go b/internal/atlas/pairing.go index 2860edafdc..31386bbbbd 100644 --- a/internal/atlas/pairing.go +++ b/internal/atlas/pairing.go @@ -6,23 +6,23 @@ package atlas var Pairing = &Map{ Name: "pairing", Title: "Pairing", - Description: "codeaf on two computers: pair with a link, continue a chat on the other", + Description: "codeaf on two computers: pair with a link, move a chat to the other", Nodes: []Node{ // ── machines ────────────────────────────────────────────────────── {ID: "machineA", Label: "Machine A", Short: "existing device", Kind: KindMachine, X: 0.08, Y: 0.1, - Summary: "The computer that already runs codeaf. It approves new machines and publishes each chat's turns so another machine can continue them.", + Summary: "The computer that already runs codeaf. It approves new machines and publishes each chat's turns so another machine can pick them up.", Details: []string{"Holds the identity key and a device cert signed by it", "Publishes encrypted frames every turn while it holds the chat's lease"}, Files: []FileRef{ {Path: "cmd/codeaf/approvals.go", Symbols: []string{"approvalsDoor"}}, {Path: "cmd/codeaf/syncdrive.go", Symbols: []string{"startDrive"}, Note: "starts the drive side: publishes turns while this machine holds the lease"}, }}, {ID: "machineB", Label: "Machine B", Short: "new device", Kind: KindMachine, X: 0.92, Y: 0.1, - Summary: "The computer being added. It runs `codeaf pair`, and once joined it can 'continue here' on a chat that is running on A.", + Summary: "The computer being added. It runs `codeaf pair`, and once joined it can 'move here' on a chat that is running on A.", Details: []string{"Generates its own ed25519 device key and x25519 box key", "Plaintext files only ever exist on the machines, never on the relay"}, Files: []FileRef{{Path: "cmd/codeaf/pair.go", Symbols: []string{"runPair"}}}}, // ── services ────────────────────────────────────────────────────── {ID: "hosted", Label: "hosted relay", Short: "default", Kind: KindService, X: 0.38, Y: 0.1, - Summary: "The default hosted sync service selected per release channel in internal/syncsetup/relayurl.go: a Cloudflare Worker with Durable Objects and R2. It holds the directory, the encrypted blobs and pairing requests, and it cannot decrypt any of them.", + Summary: "The default hosted relay selected per release channel in internal/syncsetup/relayurl.go: a Cloudflare Worker with Durable Objects and R2. It holds the directory, the encrypted blobs and pairing requests, and it cannot decrypt any of them.", Details: []string{ "Limits: 5 GiB/identity, 1200 req/min/identity, 600/min/device", "Pairing: 10-minute TTL, 10 link creates/hr, 3 pending per IP", @@ -84,7 +84,7 @@ var Pairing = &Map{ {Path: "internal/directory/presence.go"}, }}, {ID: "sync", Label: "sync", Short: "syncsetup", Kind: KindGo, X: 0.55, Y: 0.38, - Summary: "Opens the connection to the relay, signs requests, seals the vault with chacha20poly1305, follows the directory (\"running on A\"), and runs Continuer.Take for 'continue here'.", + Summary: "Opens the connection to the relay, signs requests, seals the vault with chacha20poly1305, follows the directory (\"running on A\"), and runs Continuer.Take for 'move here'.", Files: []FileRef{ {Path: "cmd/codeaf/syncwire.go", Symbols: []string{"syncOf", "syncFrom"}}, {Path: "cmd/codeaf/synctake.go", Symbols: []string{"wireSync", "watchStanding"}}, @@ -94,8 +94,8 @@ var Pairing = &Map{ {Path: "internal/syncsetup/take.go", Symbols: []string{"Continuer.Take", "restoreCopies", "pullVaultVia"}}, {Path: "internal/keys/seal.go", Symbols: []string{"seal", "open"}}, }}, - {ID: "cells", Label: "cells", Short: "continue here", Kind: KindGo, X: 0.8, Y: 0.38, - Summary: "A cell is a chat together with its workspace. Available by default on Linux and macOS with a compatible engine. Pair the computers first; existing chats keep their layout and do not move. 'Continue here' on home moves the files, history, tool output and task records to this machine.", + {ID: "cells", Label: "cells", Short: "move here", Kind: KindGo, X: 0.8, Y: 0.38, + Summary: "A cell is a chat together with its workspace. Available by default on Linux and macOS with a compatible engine. Pair the computers first; existing chats keep their layout and do not move. 'Move here' on home moves the files, history, tool output and task records to this machine.", Details: []string{"do_continue.go continues a `do` run on the same machine; it does not move anything between machines"}, Files: []FileRef{ {Path: "cmd/codeaf/cell.go", Symbols: []string{"runCell", "cellRewind", "cellEngine"}}, @@ -174,7 +174,7 @@ var Pairing = &Map{ {ID: "identity-sync", From: "identity", To: "sync", Label: "signs requests", Detail: "ed25519 device cert via wireauth."}, {ID: "sync-hosted", From: "sync", To: "hosted", Label: "/v1/dir + store", Detail: "Signed requests. Only ciphertext and directory rows cross."}, {ID: "sync-self", From: "sync", To: "selfrelay", Label: "CODEAF_SYNC_URL"}, - {ID: "b-cells", From: "machineB", To: "cells", Label: "continue here"}, + {ID: "b-cells", From: "machineB", To: "cells", Label: "move here"}, {ID: "cells-sync", From: "cells", To: "sync", Label: "Continuer.Take"}, {ID: "cells-cellsync", From: "cells", To: "cellsync", Label: "fetch + acquire"}, {ID: "cellsync-hosted", From: "cellsync", To: "hosted", Label: "encrypted frames", Detail: "Frames are XChaCha20-Poly1305 ciphertext; the relay never sees plaintext."}, @@ -197,8 +197,8 @@ var Pairing = &Map{ {From: "pair", To: "hosted", Message: "POST /v1/dir/requests/{code}/approve (signed); relay writes the Device record", Edge: "pair-hosted"}, {From: "hosted", To: "machineB", Message: "awaitDecision gets the grant; openLinkGrant installs identity, cert and SyncURL", Note: "single use: a second approver gets 409"}, }}, - {ID: "continue", Title: "Continue chat", Summary: "Machine B takes over a chat running on A: workspace, history, tool output and task records.", Steps: []Step{ - {From: "machineB", To: "cells", Message: "home shows 'running on A'; the person picks continue here", Edge: "b-cells", Note: "internal/tui3/homepanel_continue.go"}, + {ID: "continue", Title: "Move chat", Summary: "Machine B takes over a chat running on A: workspace, history, tool output and task records.", Steps: []Step{ + {From: "machineB", To: "cells", Message: "home shows 'running on A'; the person picks move here", Edge: "b-cells", Note: "internal/tui3/homepanel_continue.go"}, {From: "cells", To: "sync", Message: "syncsetup's Continuer.Take runs the takeover (internal/handoff): B's own unsealed edits are sealed into a branch first, then the lease moves", Edge: "cells-sync"}, {From: "sync", To: "hosted", Message: "Dir.Cell(id): read head, frame list and lease", Edge: "sync-hosted"}, {From: "cells", To: "cellsync", Message: "keepLocal: B's own edits are sealed and kept as a branch", Edge: "cells-cellsync"}, diff --git a/internal/cell/arrival.go b/internal/cell/arrival.go index 6f9a310163..858f4f44c3 100644 --- a/internal/cell/arrival.go +++ b/internal/cell/arrival.go @@ -265,7 +265,7 @@ func arrivalFailure(reason string) error { type abandonedArrivalError struct{ reason string } func (e *abandonedArrivalError) Error() string { - const next = "the window that was fetching them has closed, so continue the chat here again to fetch them" + const next = "the window that was fetching them has closed, so move the chat here again to fetch them" if e.reason == "" { return fmt.Sprintf("workspace files could not arrive: %v; %s", ErrWorkspaceArrivalAbandoned, next) } diff --git a/internal/cell/arrival_hold_test.go b/internal/cell/arrival_hold_test.go index f04e6e35bd..5cb0489313 100644 --- a/internal/cell/arrival_hold_test.go +++ b/internal/cell/arrival_hold_test.go @@ -342,8 +342,8 @@ func TestW10bFailedArrivalWhoseOwnerDiedKeepsRefusingEveryProcess(t *testing.T) if err == nil { t.Fatalf("%s: waiter on a failed arrival whose owner is gone = nil; want a refusal, the tree is a partial one", when) } - if !errors.Is(err, ErrWorkspaceArrivalAbandoned) || !strings.Contains(err.Error(), reason) || !strings.Contains(err.Error(), "continue the chat here again") { - t.Fatalf("%s: refusal = %v; want it to carry the reason %q and say to continue the chat here again", when, err, reason) + if !errors.Is(err, ErrWorkspaceArrivalAbandoned) || !strings.Contains(err.Error(), reason) || !strings.Contains(err.Error(), "move the chat here again") { + t.Fatalf("%s: refusal = %v; want it to carry the reason %q and say to move the chat here again", when, err, reason) } if took > 2*time.Second { t.Fatalf("%s: the refusal took %s; with no owner left there is nothing to wait for", when, took) diff --git a/internal/cellstore/arrival_failed_test.go b/internal/cellstore/arrival_failed_test.go index 895d4d411f..27a30ba1c3 100644 --- a/internal/cellstore/arrival_failed_test.go +++ b/internal/cellstore/arrival_failed_test.go @@ -200,8 +200,8 @@ func TestW10bSealAndCaptureRefuseAfterTheOwnerOfAFailedArrivalDied(t *testing.T) defer cancel() callErr = call.do(ctx) }() - if !errors.Is(callErr, cell.ErrWorkspaceArrivalAbandoned) || !strings.Contains(callErr.Error(), reason) || !strings.Contains(callErr.Error(), "continue the chat here again") { - t.Fatalf("%s after the owner of a failed arrival died = %v; want a refusal that carries %q and says to continue the chat here again", call.name, callErr, reason) + if !errors.Is(callErr, cell.ErrWorkspaceArrivalAbandoned) || !strings.Contains(callErr.Error(), reason) || !strings.Contains(callErr.Error(), "move the chat here again") { + t.Fatalf("%s after the owner of a failed arrival died = %v; want a refusal that carries %q and says to move the chat here again", call.name, callErr, reason) } } if _, err := os.Stat(marker); err != nil { diff --git a/internal/cellstore/l4_outage_test.go b/internal/cellstore/l4_outage_test.go index 9ab616ee34..f58b31405d 100644 --- a/internal/cellstore/l4_outage_test.go +++ b/internal/cellstore/l4_outage_test.go @@ -18,7 +18,7 @@ func TestL4SyncOutageNeedsNetworkRecovery(t *testing.T) { var w SealWatch cause := &url.Error{Op: "Put", URL: "http://127.0.0.1:8901/v1/dir/devices/private", Err: syscall.ECONNREFUSED} w.Report(cause) - want := "the sync service at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back" + want := "the relay at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back" if got := w.Take(); got != want { t.Fatal(got) } diff --git a/internal/chatlist/copy.go b/internal/chatlist/copy.go index 3d16c22e06..947adf9fc1 100644 --- a/internal/chatlist/copy.go +++ b/internal/chatlist/copy.go @@ -14,7 +14,7 @@ import ( // chats move by blind pass-through (internal/syncsetup/livetransfer.go): what is // true there is that chats are not stuck, and that what still needs the relay's // storage waits. -const RelayStorageOffLive = "chats move between your computers by blind pass-through while both run codeaf; keys, memories, teams and preferences wait for sync storage (request access in Settings under Devices)" +const RelayStorageOffLive = "chats move between your computers by blind pass-through while both run codeaf; keys, memories, teams and preferences wait for relay storage (request access in Settings under Devices)" // LiveCarriesChats answers whether blind pass-through is carrying this computer's // chats now. The program that owns the home sets it at startup; nothing that @@ -75,21 +75,24 @@ func StorageOffChanged() (string, bool) { // from here so a respelling happens once. const ( // Available describes a free lease while work admission acquires a new fence. - Available = "This chat is available to continue here." - OfferContinue = "continue here" - // MoveHere is the verb for a chat another device is running right now, and - // ContinueVerb for one it let go of; the devices row offers them by name. + Available = "This chat is available to move here." + // OfferMove is the yes answer on the takeover card, the same words in the + // card's own lower case. + OfferMove = "move here" + // MoveHere is THE verb for carrying a chat from another computer to this one, + // wherever a person meets it: the devices row, the Home card's buttons, the + // resume offer. A chat another computer is running and one it let go of used to + // be offered two different verbs; one act has one word now. MoveHere = "Move here" - ContinueVerb = "Continue here" - LostRace = "another device continued this chat first" + LostRace = "another device moved this chat first" PickedUpAgain = "%s picked this chat up again" NoIdentity = "this machine has no identity yet: codeaf identity import" - RelayStorageOff = "sync storage is off for this account, so chats stay on this computer; request access in Settings under Devices" - SyncOff = "sync is off: set CODEAF_SYNC_URL to your sync service's address" - Unreachable = "the sync service is not answering" + RelayStorageOff = "relay storage is off for this account, so chats stay on this computer; request access in Settings under Devices" + SyncOff = "sync is off: set CODEAF_SYNC_URL to your relay's address" + Unreachable = "the relay is not answering" // TakeBackUnreachable explains why a released writer keeps a send unsent. TakeBackUnreachable = Unreachable + ", so this chat cannot be taken back yet; your words are still in the box" - ReadTimedOut = "the sync service did not answer in time" + ReadTimedOut = "the relay did not answer in time" SyncPaused = syncwords.UnknownOutage SyncRestored = "this chat is syncing again" ClockOff = "this computer's clock is off by more than 5 minutes" @@ -119,7 +122,7 @@ const ( takeoverMore = "; up to %s may still be on %s" keptEdits = "your unsaved edits here were kept as %s from %s" keptTurns = "kept %s from %s as a separate chat" - supersededLine = "%s continued this chat. This copy is read-only and may be behind" + supersededLine = "%s moved this chat. This copy is read-only and may be behind" copiesCame = "working copies of tasks came along: %s" copyCame = "the working copy of a task came along: %s" setupAsk = "Set this machine up like %s had it?" @@ -224,6 +227,12 @@ func nameList(names []string) string { // StatusLine is what a list row says beside the title. Idle and Here say // nothing (the emptiness law), so their line is empty. func StatusLine(r Row) string { + return StatusLineAt(r, time.Now()) +} + +// StatusLineAt formats a list row's status at a caller-supplied clock so an +// offline holder's last-seen word uses the surface's own calendar day. +func StatusLineAt(r Row, now time.Time) string { switch r.Status { case Running: if r.Working { @@ -231,7 +240,11 @@ func StatusLine(r Row) string { } return fmt.Sprintf(heldOn, r.Device) case Off: - return fmt.Sprintf(deviceOff, r.Device) + line := fmt.Sprintf(deviceOff, r.Device) + if seen := LiveSeenAt(r.HolderSeen, now); seen != "" { + line += " · last seen " + seen + } + return line case Branch: return fmt.Sprintf(branchLine, turns(r.OrphanTurns), r.Device) } diff --git a/internal/chatlist/devices.go b/internal/chatlist/devices.go index 3024843ca7..d4238516ca 100644 --- a/internal/chatlist/devices.go +++ b/internal/chatlist/devices.go @@ -3,12 +3,13 @@ package chatlist import ( "fmt" "sort" + "time" "github.com/Agent-Field/codeaf/internal/directory" ) -// The words of the devices row. The two verbs it offers, MoveHere and -// ContinueVerb, are in copy.go with the other contract sentences. +// The words of the devices row. The verb it offers, MoveHere, is in copy.go with +// the other contract sentences. const ( thisMac = "This Mac" thisDevice = "This computer" @@ -22,6 +23,8 @@ type Device struct { ID, Name string // Self marks the device the row is drawn on. Self bool + // LastSeen is when the directory last heard from this device, or zero when unknown. + LastSeen time.Time } // Devices lists the devices that are not revoked, this one first and the rest by @@ -30,7 +33,11 @@ func Devices(l directory.Listing, self string, open Opener) []Device { var out []Device for id, d := range l.Devices { if !d.Revoked { - out = append(out, Device{ID: id, Name: ownName(id == self, d, open, id, l), Self: id == self}) + var seen time.Time + if d.LastSeen > 0 { + seen = time.UnixMilli(d.LastSeen) + } + out = append(out, Device{ID: id, Name: ownName(id == self, d, open, id, l), Self: id == self, LastSeen: seen}) } } sort.Slice(out, func(i, j int) bool { return deviceBefore(out[i], out[j]) }) @@ -67,13 +74,7 @@ func (d Device) Mark(online bool, mark string) string { return mark + " " + d.Name + " " + offlineTag } -// VerbFor is the verb the devices row offers for a chat on another device. -func VerbFor(r Row) string { - if r.Status == Running { - return MoveHere - } - return ContinueVerb -} - -// VerbFrom is the verb with the device it brings the chat from. -func VerbFrom(r Row) string { return fmt.Sprintf(verbFrom, VerbFor(r), r.Device) } +// VerbFrom is the verb with the device it brings the chat from. The verb is +// [MoveHere] for every chat on another device, whether that device is running it +// or let it go. +func VerbFrom(r Row) string { return fmt.Sprintf(verbFrom, MoveHere, r.Device) } diff --git a/internal/chatlist/devices_test.go b/internal/chatlist/devices_test.go index 01a492d9a1..55f6b0cb30 100644 --- a/internal/chatlist/devices_test.go +++ b/internal/chatlist/devices_test.go @@ -31,11 +31,10 @@ func TestL4B2DevicesListSelfFirstSkipRevokedAndMarkPresence(t *testing.T) { } } -func TestVerbsFollowTheChatsStatus(t *testing.T) { - if VerbFor(Row{Status: Running}) != MoveHere || VerbFor(Row{Status: Off}) != ContinueVerb { - t.Fatal("wrong verb") - } - if got := VerbFrom(Row{Status: Running, Device: "tower"}); got != "Move here from tower" { - t.Fatal(got) +func TestOneVerbOffersTheMoveWhateverTheChatsStatus(t *testing.T) { + for _, status := range []Status{Running, Off} { + if got := VerbFrom(Row{Status: status, Device: "tower"}); got != "Move here from tower" { + t.Fatalf("a chat with status %v offered %q", status, got) + } } } diff --git a/internal/chatlist/l4fix_words_test.go b/internal/chatlist/l4fix_words_test.go index 2ab730e24c..49008f0b13 100644 --- a/internal/chatlist/l4fix_words_test.go +++ b/internal/chatlist/l4fix_words_test.go @@ -8,7 +8,7 @@ import ( // L4-G3: The sync-off command refusal names the service's address. func TestL4FixSyncOffWords(t *testing.T) { - if SyncOff != "sync is off: set CODEAF_SYNC_URL to your sync service's address" { + if SyncOff != "sync is off: set CODEAF_SYNC_URL to your relay's address" { t.Fatal(SyncOff) } } diff --git a/internal/chatlist/liveview.go b/internal/chatlist/liveview.go new file mode 100644 index 0000000000..6ecba5ae52 --- /dev/null +++ b/internal/chatlist/liveview.go @@ -0,0 +1,132 @@ +package chatlist + +import ( + "fmt" + "strings" +) + +// The words of a live view: a chat that keeps running on another of this +// person's computers and is read, and typed into, from this one. They live in +// one file because two surfaces draw them, the terminal and the desktop app, and +// a sentence spelled twice is a sentence that drifts. Every surface takes its +// words from here; the manual quotes them as they stand. +// +// NONE OF THEM NAMES THE MACHINERY. The person-facing vocabulary of a pairing +// (internal/e2e's pairing journey) has no word for the relay, a lease, a node or +// a manifest, and a live view is part of that journey, so the sentences say what +// is true for the person and what, if anything, to do about it. + +// otherComputer stands in for a host whose name is not known yet, so a sentence +// never reads " lets this computer watch". +const otherComputer = "the other computer" + +func hostWord(host string) string { + if host == "" { + return otherComputer + } + return host +} + +const ( + // LiveMoving is what the view says between choosing Move here and the chat + // arriving. It stays on screen until the move either succeeds or fails. + LiveMoving = "Moving here…" + // LiveIdle is said to a view that detached after the quiet spell. The chat is + // still readable; any key reconnects. + LiveIdle = "Disconnected after 10 minutes idle. Enter to reconnect." + // LiveBudget is said when the host's daily allowance of live traffic is used + // up: sessions stay open and readable, and typing waits for the next day. + LiveBudget = "watch only until 00:00 UTC (daily limit)" + // LiveRemoved is said to a computer taken off the person's list. It is the + // same sentence the move door says, so a person meets one wording. + LiveRemoved = "this computer was removed from your devices" +) + +// LiveWentOffline is the banner of a view whose host stopped answering. The +// view keeps what it last showed and the words typed in the box. +func LiveWentOffline(host string) string { return hostWord(host) + " went offline" } + +// LiveOfflineSeen is the composer-position bar of a view whose host is not +// running the chat, with the time the copy on this computer was last updated. +func LiveOfflineSeen(host, seen string) string { + return fmt.Sprintf("%s offline · last seen %s", hostWord(host), seen) +} + +// LiveWatchOnly is said to a computer that may read but not type, both as the +// composer's reason and as the refusal a send gets back. +func LiveWatchOnly(host string) string { + return fmt.Sprintf("%s lets this computer watch, not type. Change that in /devices there.", hostWord(host)) +} + +// LiveTypingFrom is what a view without the keyboard says about who has it. +func LiveTypingFrom(holder string) string { + return fmt.Sprintf("typing from %s now · enter types here", hostWord(holder)) +} + +// LiveNotAllowedHere is the refusal for anything a computer on the other end of +// a live view may never ask for, whichever of the two permissions it holds. +func LiveNotAllowedHere(host string) string { + return fmt.Sprintf("%s does not allow that from another computer.", hostWord(host)) +} + +// LiveNeedsItsOwnOK is what a viewer is told when it tries to answer a question +// that only the computer running the chat may settle. +func LiveNeedsItsOwnOK(host string) string { + return fmt.Sprintf("That one needs your OK on %s itself. Answer it there.", hostWord(host)) +} + +// LiveSaid is the sentence for one close reason of a live view. The reasons are +// a closed set, spelled the same on the wire and here; an unknown one is said as +// a plain loss of connection rather than invented around. +func LiveSaid(reason, host string) string { + name := hostWord(host) + switch reason { + case "not-running": + return name + " is not running this chat right now." + case "not-allowed": + return name + " does not share its chats with this computer. Change that in /devices there." + case "holder-gone": + return name + " closed this chat." + case "holder-old": + return "Restart codeaf on " + name + " to share this chat." + case "removed": + return LiveRemoved + case "permit-changed": + return name + " changed what this computer may do in its chats." + case "remote-control-off": + return name + " turned remote control off." + case "lagging": + return "Catching up with " + name + "." + case "frame-too-large": + return "One message was too large to show live." + case "budget": + return LiveBudget + case "idle": + return LiveIdle + case "host-closing": + return name + " is closing codeaf." + case "too-many": + return name + " has too many computers open on its chats right now. Try again in a minute." + } + return "Lost the connection to " + name + "." +} + +// LiveRoad is the road row of /status and of the desktop's live strip: how the +// bytes of a live view travel right now. It has exactly two values, and both +// surfaces read them from here so the terminal and the desktop cannot disagree +// about a swap. A road the link has not named yet draws as nothing (the +// emptiness law), and any road that is not the direct one is the relay, the +// word phase 1 already shipped. +// +// "relay" appears here as the name of the server, as it did on the row phase 1 +// shipped; no sentence calls the feature relay (V12). +func LiveRoad(road string) string { + switch strings.TrimSpace(road) { + case "": + return "" + case "direct": + return "live · direct" + default: + return "live · relay" + } +} diff --git a/internal/chatlist/liveview_test.go b/internal/chatlist/liveview_test.go new file mode 100644 index 0000000000..966feced97 --- /dev/null +++ b/internal/chatlist/liveview_test.go @@ -0,0 +1,88 @@ +package chatlist + +import ( + "strings" + "testing" +) + +// liveReasons is the closed set of close reasons a live view can end with. It is +// written out here from the contract and not read from the code, so a reason +// added on the wire without words fails this test instead of rendering blank. +var liveReasons = []string{ + "not-running", "not-allowed", "holder-gone", "holder-old", "removed", "permit-changed", + "lagging", "frame-too-large", "budget", "idle", "host-closing", "too-many", "remote-control-off", +} + +// V12/V25 vocabulary: a live view is part of the pairing journey, so none of its +// sentences may use the words that journey bans, and every reason has its own +// sentence that names the computer when it is about one. +func TestEveryLiveCloseReasonHasItsOwnSentenceInThePairingVocabulary(t *testing.T) { + banned := []string{"relay", "lease", "cell", "directory", "manifest", "take ", "node"} + seen := map[string]string{} + for _, reason := range liveReasons { + said := LiveSaid(reason, "Desktop") + if strings.TrimSpace(said) == "" { + t.Fatalf("reason %q has no sentence", reason) + } + if other, dup := seen[said]; dup { + t.Fatalf("reasons %q and %q say the same thing: %q", reason, other, said) + } + seen[said] = reason + for _, word := range banned { + if strings.Contains(strings.ToLower(said), word) { + t.Fatalf("reason %q says %q, which uses the banned word %q", reason, said, word) + } + } + } + if said := LiveSaid("something-new", "Desktop"); !strings.Contains(said, "Desktop") { + t.Fatalf("an unknown reason should still name the computer: %q", said) + } +} + +// A host whose name is not known yet never leaves a hole in a sentence. +func TestALiveSentenceWithNoHostNameReadsAsTheOtherComputer(t *testing.T) { + for _, said := range []string{LiveWatchOnly(""), LiveWentOffline(""), LiveSaid("not-running", ""), LiveNeedsItsOwnOK(""), LiveNotAllowedHere("")} { + if !strings.Contains(said, otherComputer) || strings.HasPrefix(said, " ") || strings.Contains(said, " ") { + t.Fatalf("a sentence with no host name has a hole in it: %q", said) + } + } +} + +// The needles the terminal e2e suite waits for are spelled in this package. +func TestTheLiveWordsTheTmuxSuiteWaitsForAreSpelledHere(t *testing.T) { + for want, said := range map[string]string{ + "Moving here": LiveMoving, + "went offline": LiveWentOffline("Desktop"), + "watch, not type": LiveWatchOnly("Desktop"), + "typing from": LiveTypingFrom("Desktop"), + } { + if !strings.Contains(said, want) { + t.Fatalf("%q does not contain %q", said, want) + } + } +} + +// V30 and V41: the road row has exactly two values and one home, whichever +// surface draws it, and a road nobody has named yet draws as nothing. +func TestTheRoadWordsHaveOneHome(t *testing.T) { + for road, want := range map[string]string{ + "direct": "live · direct", + "relay": "live · relay", + " direct ": "live · direct", + "somewhere else": "live · relay", + "": "", + } { + if got := LiveRoad(road); got != want { + t.Fatalf("LiveRoad(%q) = %q, want %q", road, got, want) + } + } +} + +// A road change is the viewer's own business and is never spoken: it has no +// sentence of its own, so asking for one gets the generic fallback every unknown +// reason gets, and the closed set above stays closed. +func TestARoadChangeIsViewerLocalAndHasNoSentenceOfItsOwn(t *testing.T) { + if got, fallback := LiveSaid("road-change", "Desktop"), LiveSaid("unknown-reason-sentinel", "Desktop"); got != fallback { + t.Fatalf("road-change has a sentence of its own: %q", got) + } +} diff --git a/internal/chatlist/liveview_viewer.go b/internal/chatlist/liveview_viewer.go new file mode 100644 index 0000000000..908cb7d5f4 --- /dev/null +++ b/internal/chatlist/liveview_viewer.go @@ -0,0 +1,27 @@ +package chatlist + +import "time" + +// LiveNotSentOffline explains why a message typed into an offline live view was +// held back in the composer rather than sent. +func LiveNotSentOffline(host string) string { + return "not sent. " + hostWord(host) + " is offline; your words are still in the box" +} + +// LiveSeenAt formats the moment a viewer's local copy of a chat was last +// brought up to date, using clock time on the same local calendar day and +// adding the day and month once the day has turned. A zero timestamp renders as +// nothing under the emptiness law. +func LiveSeenAt(seen, now time.Time) string { + if seen.IsZero() { + return "" + } + local := seen.Local() + if !now.IsZero() { + today := now.Local() + if local.Year() == today.Year() && local.YearDay() == today.YearDay() { + return local.Format("15:04") + } + } + return local.Format("2 Jan 15:04") +} diff --git a/internal/chatlist/offer.go b/internal/chatlist/offer.go index ad1d50c072..7807559f5d 100644 --- a/internal/chatlist/offer.go +++ b/internal/chatlist/offer.go @@ -20,8 +20,8 @@ type Offer struct { // another device is continued like one that went off: the person who opens it // decides it moves, and the takeover screen says where it runs now. var offers = map[Status]func(Row) Offer{ - Off: func(Row) Offer { return Offer{ContinueHere, OfferContinue} }, - Running: func(Row) Offer { return Offer{ContinueHere, OfferContinue} }, + Off: func(Row) Offer { return Offer{ContinueHere, OfferMove} }, + Running: func(Row) Offer { return Offer{ContinueHere, OfferMove} }, Branch: func(r Row) Offer { return Offer{Merge, StatusLine(r)} }, } diff --git a/internal/chatlist/offer_test.go b/internal/chatlist/offer_test.go index 3c5f477323..7cd02e73a2 100644 --- a/internal/chatlist/offer_test.go +++ b/internal/chatlist/offer_test.go @@ -11,8 +11,8 @@ func TestOfferCopy(t *testing.T) { row Row want Offer }{ - {Row{Status: Off, Device: "host-a"}, Offer{ContinueHere, "continue here"}}, - {Row{Status: Running, Device: "host-a"}, Offer{ContinueHere, "continue here"}}, + {Row{Status: Off, Device: "host-a"}, Offer{ContinueHere, "move here"}}, + {Row{Status: Running, Device: "host-a"}, Offer{ContinueHere, "move here"}}, {Row{Status: Branch, Device: "host-a", OrphanTurns: 3}, Offer{Merge, "3 turns from host-a: merge / discard"}}, {Row{Status: Idle}, Offer{Kind: Open}}, {Row{Status: Here}, Offer{Kind: Open}}, @@ -82,12 +82,12 @@ func TestFrozenSentences(t *testing.T) { if got := KeptEdits(2, "host-a"); got != "your unsaved edits here were kept as 2 turns from host-a" { t.Error(got) } - if got := Superseded("host-a"); got != "host-a continued this chat. This copy is read-only and may be behind" { + if got := Superseded("host-a"); got != "host-a moved this chat. This copy is read-only and may be behind" { t.Error(got) } for got, want := range map[string]string{ NoIdentity: "this machine has no identity yet: codeaf identity import", - Unreachable: "the sync service is not answering", + Unreachable: "the relay is not answering", ClockOff: "this computer's clock is off by more than 5 minutes", ReplacedGone: "your identity was replaced and sync has deleted the old one; pair this computer again (/pair on a computer that has the new one)", Replaced: "your chats are moving to a new identity; when that is done, pair this computer again (/pair on the computer that moved them)", @@ -167,3 +167,34 @@ func TestEarlierRemovedNoticeIsStillARemoval(t *testing.T) { t.Fatal("removal notices from before --replace are no longer recognised") } } + +// V27 (Part 4): an offline row says when its holder was last seen only when +// HolderSeen is non-zero, and a zero timestamp renders as nothing. +func TestAnOfflineRowSaysWhenItWasLastSeenOnlyWhenKnown(t *testing.T) { + now := time.Date(2026, time.November, 23, 16, 30, 0, 0, time.Local) + seenToday := time.Date(2026, time.November, 23, 14, 2, 0, 0, time.Local) + seenEarlier := time.Date(2026, time.January, 2, 14, 2, 0, 0, time.Local) + + unknown := Row{Status: Off, Device: "tower"} + if got, want := StatusLineAt(unknown, now), "tower offline"; got != want { + t.Fatalf("offline row with unknown HolderSeen = %q, want %q", got, want) + } + if got, want := StatusLine(unknown), "tower offline"; got != want { + t.Fatalf("StatusLine with unknown HolderSeen = %q, want %q", got, want) + } + + knownToday := Row{Status: Off, Device: "tower", HolderSeen: seenToday} + if got, want := StatusLineAt(knownToday, now), "tower offline · last seen 14:02"; got != want { + t.Fatalf("offline row with today HolderSeen = %q, want %q", got, want) + } + + knownEarlier := Row{Status: Off, Device: "tower", HolderSeen: seenEarlier} + if got, want := StatusLineAt(knownEarlier, now), "tower offline · last seen 2 Jan 14:02"; got != want { + t.Fatalf("offline row with earlier HolderSeen = %q, want %q", got, want) + } + + running := Row{Status: Running, Device: "tower", HolderSeen: seenToday} + if got, want := StatusLineAt(running, now), "held on tower"; got != want { + t.Fatalf("running row with HolderSeen = %q, want %q", got, want) + } +} diff --git a/internal/chatlist/rows.go b/internal/chatlist/rows.go index 23b52ca624..10d2cf7509 100644 --- a/internal/chatlist/rows.go +++ b/internal/chatlist/rows.go @@ -86,6 +86,9 @@ type Row struct { // HolderRemoved says the last holder was removed from the person's // devices: its lease reads as released and it is never offered (#2072). HolderRemoved bool + // HolderSeen is when the directory last heard from the device holding this + // row, or zero when unknown. + HolderSeen time.Time // BranchRedundant reports that a branch row's saved head is already in its // parent chat's turn history, so archiving the branch loses nothing. BranchRedundant bool diff --git a/internal/clusterctl/control.go b/internal/clusterctl/control.go index cf18f45289..5e5d66d9c9 100644 --- a/internal/clusterctl/control.go +++ b/internal/clusterctl/control.go @@ -24,7 +24,7 @@ var ErrUnavailable = errors.New(cs.LeadershipUnavailable) // ErrUnsupported distinguishes an absent leadership capability from a lost // quorum. Clients can refuse before saving an intent the relay cannot finish. -var ErrUnsupported = errors.New("this sync service does not offer cluster leadership yet; your saved chats are still here") +var ErrUnsupported = errors.New("this relay does not offer cluster leadership yet; your saved chats are still here") type CommittedRefusal struct { Code cs.Code `json:"code"` diff --git a/internal/config/derivation_test.go b/internal/config/derivation_test.go index ad875078b2..9d913669bf 100644 --- a/internal/config/derivation_test.go +++ b/internal/config/derivation_test.go @@ -121,6 +121,7 @@ var settingReaders = map[string]string{ KeyWork: "workMode", KeyIcons: "iconMode", KeyTeamsShare: "TeamsShareAt", + KeyRemoteControl: "RemoteControlOn", KeyDailyBudget: "DailyBudgetUSD", KeyPlanConsent: "PlanConsentUSD", KeyDocumentEngine: "DocumentEngine", diff --git a/internal/config/settings.go b/internal/config/settings.go index 04251204dc..a4b0917fd2 100644 --- a/internal/config/settings.go +++ b/internal/config/settings.go @@ -4,7 +4,9 @@ import ( "encoding/hex" "encoding/json" "fmt" + "net" "os" + "slices" "sort" "strconv" "strings" @@ -126,6 +128,7 @@ const ( KeyAttribution = "attribution" KeyAttributionModel = "attribution.model" KeyIdleHandoff = "idle_handoff" + KeyRemoteControl = "remote_control" KeySplitPct = "split_pct" // The two rows the v3 chat surface keeps on disk BESIDE the conversation: @@ -1517,6 +1520,22 @@ var OperatorEnvPins = []string{ // (internal/syncsetup). It is the owners' off switch while that road is // new, not a preference, so it stays in the environment. "CODEAF_PASSTHROUGH", + // CODEAF_REMOTE_CONTROL overrides the persisted remote_control row: it is a + // switch while the feature is new, and a row can set it too. + "CODEAF_REMOTE_CONTROL", + // CODEAF_REMOTE_DAILY_MB moves the live door's daily allowance of carrier + // bytes (internal/livedoor) off its built-in 256 MiB, for an operator + // measuring a relay. It is a safety rail's size, not a preference, so it + // stays in the environment. + "CODEAF_REMOTE_DAILY_MB", + // CODEAF_REMOTE_ROAD=relay keeps every remote view on the relay on the + // computer that sets it, and CODEAF_REMOTE_STUN replaces the public STUN + // servers a direct connection asks for this computer's address (a comma + // list, or "off" for none) (internal/directroad). Both are an operator's + // off switch and address book while the direct road is new, and the person + // has one switch, Remote control, so neither is a row. + "CODEAF_REMOTE_ROAD", + "CODEAF_REMOTE_STUN", } // Defaults the registry owns beyond the ones config.go already declares. @@ -1546,10 +1565,13 @@ const ( DefaultAttributionModel = true // DefaultIdleHandoff leaves an open chat's hold on the computer that - // holds it and keeps remote chats waiting for Continue here unless the + // holds it and keeps remote chats waiting for Move here unless the // person turns idle handoff on. DefaultIdleHandoff = false + // DefaultRemoteControl keeps remote control off until the person turns it on. + DefaultRemoteControl = false + // The divider clamps so neither pane can be set into uselessness. The TUI // reads these so the drag, the [ ] nudge, and the sheet agree. DefaultSplitPct = 80 @@ -2891,6 +2913,13 @@ func (s *Settings) build() []Setting { read: func() string { return formatBool(IdleHandoffAt(dir)) }, write: func(raw string) error { return writeBool(dir, KeyIdleHandoff, raw) }, }, + Setting{ + Key: KeyRemoteControl, Category: CategoryInterface, Kind: SettingBool, + Label: "Remote control", Env: "CODEAF_REMOTE_CONTROL", + Hint: RemoteControlHint, + read: func() string { return formatBool(RemoteControlAt(dir)) }, + write: func(raw string) error { return writeBool(dir, KeyRemoteControl, raw) }, + }, // The ssh carrier is local surface policy, so its overrides live beside // the other interface choices. Keeping them in the registry matters more // than their rarity: a network that drops idle TCP or rewrites DSCP is a @@ -3399,7 +3428,7 @@ func AssistedByModelAt(profileDir, model string) string { // shared chat goes idle with the row on, and what happens with it off. It never // says "pair": that word is how a person searching settings finds the Devices // tab, and a General row matching it took the search there instead. -const IdleHandoffHint = "On, an idle chat shared with your other computers releases its hold after upload and free shared chats open here without asking; off, open chats keep their hold and remote chats wait for Continue here." +const IdleHandoffHint = "On, an idle chat shared with your other computers releases its hold after upload and free shared chats open here without asking; off, open chats keep their hold and remote chats wait for Move here." // IdleHandoffAt resolves whether an idle chat on a paired computer releases its // hold to the relay after upload and whether free shared chats auto-open. A @@ -3417,6 +3446,105 @@ func IdleHandoffAt(profileDir string) bool { return DefaultIdleHandoff } +// RemoteControlHint is the `remote_control` row's hint: what turning remote +// control on allows another computer of the person's to do. +const RemoteControlHint = "lets another computer of yours open this computer's running chats and, if you allow it, type into them. Off until you turn it on." + +// RemoteControlOn reports whether another computer of this person's may open +// this computer's running chats and, when permitted, type into them. +func RemoteControlOn() bool { + return RemoteControlAt(ProfileDir()) +} + +// RemoteControlAt resolves KeyRemoteControl for profileDir with precedence: +// CODEAF_REMOTE_CONTROL (when a valid boolean) > persisted row > off. +func RemoteControlAt(profileDir string) bool { + if raw := strings.TrimSpace(env.Get("CODEAF_REMOTE_CONTROL")); raw != "" { + if value, err := parseBool(raw); err == nil { + return value + } + } + if value, ok := persistedBool(profileDir, KeyRemoteControl); ok { + return value + } + return DefaultRemoteControl +} + +// The two STUN servers a direct connection asks for this computer's public +// address by default. Cloudflare comes first because the same company already +// carries the hosted relay, and Google comes second so one dead server cannot +// silently turn off direct connections across two networks. A STUN server is +// told only that an app on some public address asked for its mapping. +const ( + DefaultRemoteSTUNPrimary = "stun:stun.cloudflare.com:3478" + DefaultRemoteSTUNSecondary = "stun:stun.l.google.com:19302" + + // remoteSTUNPort is the port a STUN entry without one means. + remoteSTUNPort = "3478" +) + +// RemoteRoadRelayOnly reports whether CODEAF_REMOTE_ROAD=relay keeps every +// remote view on the relay on this computer: it offers no direct connection, +// refuses any offer, and contacts no STUN server. Unset, or any other value, +// leaves the road automatic. It is operator plumbing and not a Settings row, +// because a person who wants less than direct has the Remote control switch. +func RemoteRoadRelayOnly() bool { + return strings.EqualFold(strings.TrimSpace(env.Get("CODEAF_REMOTE_ROAD")), "relay") +} + +// RemoteSTUN is the list of STUN server URLs a direct connection may ask, in +// the order to prefer them, each spelled stun:host:port. CODEAF_REMOTE_STUN +// replaces the defaults with a comma-separated list of host:port or stun: URLs, +// and the single word "off" means none, so only addresses on a shared network +// are offered. An entry that is not a usable STUN address is dropped, and a +// value with no usable entry at all is read as unset, so a typo cannot turn off +// direct connections across networks without saying "off". +// +// NO TURN SERVER IS EVER ACCEPTED HERE: a turn: or turns: entry is dropped. A +// relayed media server would carry the bytes of a person's chats through a third +// company, and the relay this program already has is the only road that does. +func RemoteSTUN() []string { + raw := strings.TrimSpace(env.Get("CODEAF_REMOTE_STUN")) + if strings.EqualFold(raw, "off") { + return []string{} + } + var servers []string + for _, entry := range strings.Split(raw, ",") { + if url, ok := remoteSTUNEntry(entry); ok && !slices.Contains(servers, url) { + servers = append(servers, url) + } + } + if len(servers) == 0 { + return []string{DefaultRemoteSTUNPrimary, DefaultRemoteSTUNSecondary} + } + return servers +} + +// remoteSTUNEntry normalises one entry of CODEAF_REMOTE_STUN to stun:host:port. +func remoteSTUNEntry(entry string) (string, bool) { + entry = strings.TrimSpace(entry) + if entry == "" || strings.ContainsAny(entry, " \t/?#@") { + return "", false + } + if scheme, rest, found := strings.Cut(entry, ":"); found && strings.EqualFold(scheme, "stun") { + entry = rest + } else if found && (strings.EqualFold(scheme, "turn") || strings.EqualFold(scheme, "turns") || strings.EqualFold(scheme, "stuns")) { + return "", false + } + host, port, err := net.SplitHostPort(entry) + if err != nil { + // A bare host, or a bare IPv6 address, means the default port. + host, port = strings.Trim(entry, "[]"), remoteSTUNPort + } + if host == "" || port == "" { + return "", false + } + if number, err := strconv.Atoi(port); err != nil || number < 1 || number > 65535 { + return "", false + } + return "stun:" + net.JoinHostPort(host, port), true +} + // HistoryEnabledAt resolves whether the v3 chat surface records what was typed // into ~/.codeaf/v3/history.jsonl. A malformed pin reads as the default // rather than refusing a launch over a recall list. diff --git a/internal/config/settings_presentation.go b/internal/config/settings_presentation.go index 0ab01edd27..bed5f2c948 100644 --- a/internal/config/settings_presentation.go +++ b/internal/config/settings_presentation.go @@ -14,6 +14,25 @@ type SettingPresentation struct { Activation string } +// THE RETIRED SPELLINGS THE SETTINGS SEARCH STILL ANSWERS TO, written in this one +// place. A person who learned "continue here" or "sync storage" types the word +// they remember into the search box and finds the row it named; the word is +// matched and NEVER DRAWN, so no screen says it. internal/wordlaw reads this +// file as its one exception to "no string a person reads says a retired +// spelling", and every other file that wants one of these words names it +// through this list. +const ( + // LegacyContinueHere is what carrying a chat from another computer to this + // one was called until 2026-11-23, when the act became "Move here". + LegacyContinueHere = "continue here" + // LegacySyncStorage is what the Devices row for the relay's storage was + // called until 2026-11-23, when it became "relay storage". + LegacySyncStorage = "sync storage" +) + +// LegacyWords lists every retired spelling the search accepts, in one slice. +var LegacyWords = []string{LegacyContinueHere, LegacySyncStorage} + // ChatPresentation is a pure view of a setting, never a configuration migration. // Empty Label or Description lets a surface retain its existing wording. Timing // is stated only where the consumer establishes it; no blanket "applies now". @@ -59,6 +78,12 @@ func (s Setting) ChatPresentation() SettingPresentation { case KeyTeamsShare: p.Scope = "This computer" p.Activation = "Applies immediately" + case KeyRemoteControl: + // IT SITS ON THE DEVICES TAB, beside the computers it is about, and not on + // General with the other interface rows its registry category would give it. + p.Category, p.Label = "Devices", "remote control" + p.Scope = "This computer" + p.Activation = "Applies immediately" case KeyTaskColumn: p.Label = "task sidebar" case KeyQuickSwitch: @@ -232,7 +257,9 @@ func (s Setting) ChatPresentation() SettingPresentation { case KeyHistoryEnabled, KeyDraftPersist: p.Aliases = append(p.Aliases, "privacy", "saved messages") case KeyIdleHandoff: - p.Aliases = append(p.Aliases, "handoff", "idle release", "continue here", "other computers", "sync") + p.Aliases = append(p.Aliases, "handoff", "idle release", "move here", LegacyContinueHere, "other computers", "sync") + case KeyRemoteControl: + p.Aliases = append(p.Aliases, "other computer", "type from another computer", "drive") } return p } diff --git a/internal/config/settings_presentation_test.go b/internal/config/settings_presentation_test.go index 1f3f05dfed..bdf2a3597b 100644 --- a/internal/config/settings_presentation_test.go +++ b/internal/config/settings_presentation_test.go @@ -90,7 +90,7 @@ func TestChatPresentationHasNoRowsForTheRemovedScheduler(t *testing.T) { } func TestChatPresentationKeepsAliasesAndEveryVisibleRowCategorized(t *testing.T) { - categories := []string{"General", "Models", "Memory", "Tasks", "AI teams", "Permissions", "Spending", "Connections", "Privacy"} + categories := []string{"General", "Models", "Memory", "Tasks", "AI teams", "Permissions", "Spending", "Connections", "Devices", "Privacy"} for _, row := range registry(t, t.TempDir()).Rows() { p := row.ChatPresentation() if !p.Hidden && !slices.Contains(categories, p.Category) { diff --git a/internal/config/settings_test.go b/internal/config/settings_test.go index f4e1ddbb2d..0d3df45d59 100644 --- a/internal/config/settings_test.go +++ b/internal/config/settings_test.go @@ -10,6 +10,7 @@ import ( "github.com/Agent-Field/codeaf/internal/automation" "github.com/Agent-Field/codeaf/internal/cell/celltest" + "github.com/Agent-Field/codeaf/internal/env" "github.com/Agent-Field/codeaf/internal/pool/poolcfg" "github.com/Agent-Field/codeaf/internal/taxonomy" ) @@ -376,6 +377,62 @@ func TestSettingEditorsRefuseNonsenseInPlainLanguage(t *testing.T) { } } +func TestRemoteControlIsOffByDefaultAndTheEnvironmentOverridesTheRow(t *testing.T) { + dir := t.TempDir() + t.Setenv("CODEAF_HOME", dir) + t.Setenv("CODEAF_REMOTE_CONTROL", "") + + rows := registry(t, dir) + row, ok := rows.Row(KeyRemoteControl) + if !ok { + t.Fatalf("%s is not registered", KeyRemoteControl) + } + if RemoteControlAt(dir) || RemoteControlOn() || row.Value() != "off" { + t.Fatalf("default remote_control = %v / %v / %q, want off", RemoteControlAt(dir), RemoteControlOn(), row.Value()) + } + + pres := row.ChatPresentation() + if pres.Label != "remote control" { + t.Fatalf("presentation label = %q, want %q", pres.Label, "remote control") + } + for _, wantAlias := range []string{"other computer", "type from another computer", "drive"} { + if !slices.Contains(pres.Aliases, wantAlias) { + t.Fatalf("presentation aliases %v missing %q", pres.Aliases, wantAlias) + } + } + + if err := row.Apply("on"); err != nil { + t.Fatalf("apply on: %v", err) + } + if !RemoteControlAt(dir) || !RemoteControlOn() || row.Value() != "on" { + t.Fatalf("row on remote_control = %v / %v / %q, want on", RemoteControlAt(dir), RemoteControlOn(), row.Value()) + } + + t.Setenv("CODEAF_REMOTE_CONTROL", "0") + if RemoteControlAt(dir) || RemoteControlOn() { + t.Fatalf("env 0 with row on should be off") + } + + t.Setenv("CODEAF_REMOTE_CONTROL", "maybe") + if !RemoteControlAt(dir) || !RemoteControlOn() { + t.Fatalf("env maybe with row on should be ignored and keep row on") + } + + t.Setenv("CODEAF_REMOTE_CONTROL", "") + if err := row.Apply("off"); err != nil { + t.Fatalf("apply off: %v", err) + } + t.Setenv("CODEAF_REMOTE_CONTROL", "1") + if !RemoteControlAt(dir) || !RemoteControlOn() { + t.Fatalf("env 1 with row off should be on") + } + + t.Setenv("CODEAF_REMOTE_CONTROL", "maybe") + if RemoteControlAt(dir) || RemoteControlOn() { + t.Fatalf("env maybe with row off should be ignored and keep row off") + } +} + // THE ATTRIBUTION ROW defaults on, turns signing off when requested, and obeys // the shell pin. func TestTheAttributionRowDefaultsOnAndTurnsSigningOff(t *testing.T) { @@ -1553,3 +1610,76 @@ func TestTheTaskModelRowSaysTheCrewPicksWhenBlank(t *testing.T) { t.Fatalf("the task model row's hint: %q", row.Hint) } } + +// V36 / D14 / D15: the road and STUN variables are read through the one +// environment door (so the legacy spelling still works the way every other +// codeaf variable's does), the road is relay-only only for the exact word +// "relay", and the STUN list is the default pair, a custom list, or none. +func TestTheRoadAndStunVariablesAreReadThroughTheEnvironmentDoor(t *testing.T) { + road, stun := "CODEAF_REMOTE_ROAD", "CODEAF_REMOTE_STUN" + t.Setenv(road, "") + t.Setenv(stun, "") + t.Setenv(env.Legacy(road), "") + t.Setenv(env.Legacy(stun), "") + + if RemoteRoadRelayOnly() { + t.Fatal("an unset CODEAF_REMOTE_ROAD kept the road on the relay") + } + for _, value := range []string{"relay", "RELAY", " Relay "} { + t.Setenv(road, value) + if !RemoteRoadRelayOnly() { + t.Fatalf("CODEAF_REMOTE_ROAD=%q did not keep the road on the relay", value) + } + } + for _, value := range []string{"auto", "direct", "relayed", "1", "off"} { + t.Setenv(road, value) + if RemoteRoadRelayOnly() { + t.Fatalf("CODEAF_REMOTE_ROAD=%q kept the road on the relay; only \"relay\" does", value) + } + } + // The retired spelling of the variable is still honoured through the door. + t.Setenv(road, "") + t.Setenv(env.Legacy(road), "relay") + if !RemoteRoadRelayOnly() { + t.Fatal("the door's fallback spelling of CODEAF_REMOTE_ROAD was not read") + } + t.Setenv(env.Legacy(road), "") + + defaults := []string{"stun:stun.cloudflare.com:3478", "stun:stun.l.google.com:19302"} + if got := RemoteSTUN(); !slices.Equal(got, defaults) { + t.Fatalf("the default STUN list = %v, want Cloudflare then Google %v", got, defaults) + } + for _, tc := range []struct { + name string + value string + want []string + }{ + {"off means none", "off", []string{}}, + {"off is case blind", " OFF ", []string{}}, + {"one host and port", "stun.example.org:3478", []string{"stun:stun.example.org:3478"}}, + {"a stun url", "stun:stun.example.org:19302", []string{"stun:stun.example.org:19302"}}, + {"a list keeps its order and drops repeats", "a.example.org:1, stun:b.example.org:2 ,a.example.org:1", []string{"stun:a.example.org:1", "stun:b.example.org:2"}}, + {"a bare host takes the standard port", "stun.example.org", []string{"stun:stun.example.org:3478"}}, + {"an ipv6 address", "[2001:db8::1]:3478", []string{"stun:[2001:db8::1]:3478"}}, + {"no turn server is ever accepted", "turn:relay.example.org:3478,turns:relay.example.org:5349", defaults}, + {"a bad port is dropped and the rest kept", "a.example.org:99999,b.example.org:3478", []string{"stun:b.example.org:3478"}}, + {"nothing usable reads as unset", "http://x.example.org/, ,", defaults}, + } { + t.Setenv(stun, tc.value) + if got := RemoteSTUN(); !slices.Equal(got, tc.want) { + t.Fatalf("%s: CODEAF_REMOTE_STUN=%q gave %v, want %v", tc.name, tc.value, got, tc.want) + } + } + // The off switch returns an empty list and never nil-versus-default: a + // caller has to be able to tell "none" from "unset". + t.Setenv(stun, "off") + if got := RemoteSTUN(); got == nil || len(got) != 0 { + t.Fatalf("off returned %#v, want an empty non-nil list", got) + } + // And the retired spelling works through the door here too. + t.Setenv(stun, "") + t.Setenv(env.Legacy(stun), "off") + if got := RemoteSTUN(); len(got) != 0 { + t.Fatalf("the door's fallback spelling of CODEAF_REMOTE_STUN was not read: %v", got) + } +} diff --git a/internal/config/testdata/profile-keys.ledger b/internal/config/testdata/profile-keys.ledger index f06ccb4b4e..294907da31 100644 --- a/internal/config/testdata/profile-keys.ledger +++ b/internal/config/testdata/profile-keys.ledger @@ -77,6 +77,7 @@ practice_idle prompt.profile propose_new_skills rail_state +remote_control reply.guard response.attempts response.lift_after diff --git a/internal/directory/client.go b/internal/directory/client.go index 1c49b7c0ce..3a4ef5b005 100644 --- a/internal/directory/client.go +++ b/internal/directory/client.go @@ -96,7 +96,7 @@ var ( ErrTooOld = errors.New("directory: this relay is too old for that") // ErrConditionalTake is the one feature an older service cannot offer // safely. It says what still works and the one thing to do instead. - ErrConditionalTake = errors.New(conditionalTakeFeature + " waits for a sync service update; all else works, so close it there and continue here") + ErrConditionalTake = errors.New(conditionalTakeFeature + " waits for a relay update; all else works, so close it there and move it here") ) // ReleaseQuiet distinguishes background preparation from quitting an open diff --git a/internal/directroad/answer.go b/internal/directroad/answer.go new file mode 100644 index 0000000000..5834464116 --- /dev/null +++ b/internal/directroad/answer.go @@ -0,0 +1,393 @@ +package directroad + +import ( + "context" + "io" + "sync" + "sync/atomic" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/pion/webrtc/v4" +) + +// Host manages incoming direct-road offers on the host computer, enforces +// per-device superseding and the host-wide livedoor.PendingOffers cap, and +// hands opened byte streams to the installed acceptor. +type Host struct { + cfg Config + + mu sync.Mutex + closed bool + acceptCtx context.Context + accept func(ctx context.Context, stream io.ReadWriteCloser) + stopCtxWatch chan struct{} + pending map[*hostSession]struct{} + pendingByDevice map[string]*hostSession + streams map[*byteStream]struct{} + + pendingWG sync.WaitGroup +} + +// New creates a Host with the given configuration. +func New(cfg Config) *Host { + return &Host{ + cfg: cfg, + pending: make(map[*hostSession]struct{}), + pendingByDevice: make(map[string]*hostSession), + streams: make(map[*byteStream]struct{}), + } +} + +// NewHost returns a new Host as a livedoor.DirectHost. +func NewHost(cfg Config) livedoor.DirectHost { + return New(cfg) +} + +// SetAcceptor installs the callback that receives each opened direct-road byte +// stream. When ctx ends, the host closes every pending session and every open +// stream. +func (h *Host) SetAcceptor(ctx context.Context, accept func(ctx context.Context, stream io.ReadWriteCloser)) { + if ctx == nil { + ctx = context.Background() + } + + h.mu.Lock() + if h.closed { + h.mu.Unlock() + return + } + if h.stopCtxWatch != nil { + close(h.stopCtxWatch) + h.stopCtxWatch = nil + } + h.acceptCtx = ctx + h.accept = accept + stopWatch := make(chan struct{}) + h.stopCtxWatch = stopWatch + h.mu.Unlock() + + guard.Go("directroad.host.ctx", func() { + select { + case <-ctx.Done(): + h.Close() + case <-stopWatch: + } + }) +} + +// Offered validates an incoming viewer offer synchronously on the relay link's +// reader goroutine, reserves a pending slot (superseding any earlier pending +// attempt from the same peer.Device), and spawns the WebRTC answer work on a +// guarded goroutine. Returning nil tells the caller to send a refuse signal. +func (h *Host) Offered(ctx context.Context, peer livedoor.Peer, offer []byte, s livedoor.Signaller) livedoor.DirectSession { + if ctx == nil { + ctx = context.Background() + } + if ctx.Err() != nil { + return nil + } + + sig, err := livedoor.DecodeSignal(offer) + if err != nil || sig.T != livedoor.SignalOffer || sig.ID == "" || sig.SDP == "" { + return nil + } + + h.mu.Lock() + if h.closed || h.accept == nil || h.acceptCtx == nil || h.acceptCtx.Err() != nil { + h.mu.Unlock() + return nil + } + + old := h.pendingByDevice[peer.Device] + if old == nil && len(h.pending) >= livedoor.PendingOffers { + h.mu.Unlock() + return nil + } + if old != nil { + delete(h.pending, old) + delete(h.pendingByDevice, peer.Device) + } + + hs := &hostSession{ + host: h, + ctx: ctx, + hostCtx: h.acceptCtx, + device: peer.Device, + offer: sig, + s: s, + inbox: make(chan []byte, livedoor.SignalRate), + cancelCh: make(chan struct{}), + } + h.pending[hs] = struct{}{} + h.pendingByDevice[peer.Device] = hs + h.pendingWG.Add(1) + h.mu.Unlock() + + if old != nil { + old.Close() + } + + guard.Go("directroad.host.answer", func() { + defer h.pendingWG.Done() + hs.run() + }) + + return hs +} + +// Close closes the host, every pending session, and every open stream, and +// waits for in-flight answer goroutines to finish. +func (h *Host) Close() { + h.mu.Lock() + if h.closed { + h.mu.Unlock() + h.pendingWG.Wait() + return + } + h.closed = true + if h.stopCtxWatch != nil { + close(h.stopCtxWatch) + h.stopCtxWatch = nil + } + + pendingList := make([]*hostSession, 0, len(h.pending)) + for hs := range h.pending { + pendingList = append(pendingList, hs) + } + clear(h.pending) + clear(h.pendingByDevice) + + streamList := make([]*byteStream, 0, len(h.streams)) + for st := range h.streams { + streamList = append(streamList, st) + } + clear(h.streams) + h.mu.Unlock() + + for _, hs := range pendingList { + hs.Close() + } + for _, st := range streamList { + _ = st.Close() + } + + h.pendingWG.Wait() +} + +// releasePending removes hs from the host's pending tables if it is still +// registered there. +func (h *Host) releasePending(hs *hostSession) { + h.mu.Lock() + delete(h.pending, hs) + if h.pendingByDevice[hs.device] == hs { + delete(h.pendingByDevice, hs.device) + } + h.mu.Unlock() +} + +// acceptStream registers an opened stream with the host and runs the installed +// acceptor on its own guarded goroutine, closing the stream when accept +// returns. +func (h *Host) acceptStream(st *byteStream) { + h.mu.Lock() + if h.closed || h.accept == nil || h.acceptCtx == nil || h.acceptCtx.Err() != nil { + h.mu.Unlock() + _ = st.Close() + return + } + acceptFn := h.accept + acceptCtx := h.acceptCtx + h.streams[st] = struct{}{} + h.mu.Unlock() + + guard.Go("directroad.host.accept", func() { + defer func() { + _ = st.Close() + h.mu.Lock() + delete(h.streams, st) + h.mu.Unlock() + }() + acceptFn(acceptCtx, st) + }) +} + +// hostSession is one pending direct-road attempt on the host. +type hostSession struct { + host *Host + ctx context.Context + hostCtx context.Context + device string + offer livedoor.Signal + s livedoor.Signaller + + inbox chan []byte + cancelCh chan struct{} + + mu sync.Mutex + sess *pcSession + handedOver bool + + closed atomic.Bool + closeOnce sync.Once +} + +// Deliver enqueues a signalling payload from the relay reader goroutine +// without blocking; overflowing the bounded queue ends the attempt. +func (hs *hostSession) Deliver(payload []byte) { + if hs.closed.Load() { + return + } + cp := append([]byte(nil), payload...) + select { + case hs.inbox <- cp: + default: + // A viewer that floods signalling frames beyond the bounded queue + // loses its pending attempt so the relay reader goroutine never blocks. + hs.Close() + } +} + +// Close releases the pending slot and tears down the peer connection if no +// stream has been handed over to the host acceptor yet. +func (hs *hostSession) Close() { + hs.closeOnce.Do(func() { + hs.closed.Store(true) + close(hs.cancelCh) + hs.host.releasePending(hs) + + hs.mu.Lock() + sess := hs.sess + handedOver := hs.handedOver + hs.mu.Unlock() + + if sess != nil && !handedOver { + sess.closePC() + } + }) +} + +// markHandedOver records that the session's data channel opened before the +// session was closed, transferring peer-connection ownership to the stream. +func (hs *hostSession) markHandedOver() bool { + hs.mu.Lock() + defer hs.mu.Unlock() + if hs.closed.Load() { + return false + } + hs.handedOver = true + return true +} + +// run executes the pion peer-connection setup, answer generation, candidate +// trickling, and OfferTTL wait off the relay reader goroutine. +func (hs *hostSession) run() { + defer hs.host.releasePending(hs) + + ttl := livedoor.OfferTTL + if ttl <= 0 { + ttl = time.Millisecond + } + ttlTimer := time.NewTimer(ttl) + defer ttlTimer.Stop() + + if hs.closed.Load() || hs.ctx.Err() != nil || hs.hostCtx.Err() != nil { + return + } + + sess, err := newPCSession(hs.offer.ID, hs.host.cfg, hs.s) + if err != nil { + return + } + + hs.mu.Lock() + if hs.closed.Load() { + hs.mu.Unlock() + sess.abort() + return + } + hs.sess = sess + hs.mu.Unlock() + + failSession := func(sendEndFrame bool) { + if sendEndFrame { + _ = sendEnd(hs.s, hs.offer.ID) + } + sess.abort() + } + + err = sess.setRemoteDescription(webrtc.SessionDescription{ + Type: webrtc.SDPTypeOffer, + SDP: hs.offer.SDP, + }) + if err != nil { + failSession(true) + return + } + + answerDesc, err := sess.pc.CreateAnswer(nil) + if err != nil { + failSession(true) + return + } + if err := sess.pc.SetLocalDescription(answerDesc); err != nil { + failSession(true) + return + } + if err := sendAnswer(hs.s, hs.offer.ID, answerDesc.SDP); err != nil { + failSession(false) + return + } + + for { + select { + case rawStream := <-sess.openCh: + st := rawStream.(*byteStream) + if !hs.markHandedOver() { + _ = st.Close() + sess.abort() + return + } + hs.host.releasePending(hs) + hs.host.acceptStream(st) + return + + case <-sess.errCh: + failSession(true) + return + + case <-ttlTimer.C: + failSession(true) + return + + case <-hs.cancelCh: + failSession(false) + return + + case <-hs.ctx.Done(): + failSession(true) + return + + case <-hs.hostCtx.Done(): + failSession(true) + return + + case payload := <-hs.inbox: + sig, err := livedoor.DecodeSignal(payload) + if err != nil || sig.ID != hs.offer.ID { + continue + } + switch sig.T { + case livedoor.SignalCandidate: + if err := sess.addCandidate(sig); err != nil { + failSession(true) + return + } + case livedoor.SignalEnd: + failSession(false) + return + } + } + } +} diff --git a/internal/directroad/blocked_test.go b/internal/directroad/blocked_test.go new file mode 100644 index 0000000000..e65c548f4c --- /dev/null +++ b/internal/directroad/blocked_test.go @@ -0,0 +1,236 @@ +package directroad + +import ( + "context" + "io" + "runtime" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/livedoor" +) + +// Contract V32: a blocked path never opens, Offer ends within its context +// bound, the host releases its pending slot, and no goroutines or peer +// connections leak. +func TestABlockedPathNeverOpensAndTheAttemptEndsWithinItsBound(t *testing.T) { + rig := newVNetRig(t) + rig.dropPeers.Store(true) + + baseGoroutines := runtime.NumGoroutine() + + hostCtx, hostCancel := context.WithCancel(context.Background()) + defer hostCancel() + + host := New(rig.hostConfig()) + defer host.Close() + + var accepted atomic.Int32 + host.SetAcceptor(hostCtx, func(_ context.Context, _ io.ReadWriteCloser) { + accepted.Add(1) + }) + + const attemptBound = 900 * time.Millisecond + offerCtx, offerCancel := context.WithTimeout(context.Background(), attemptBound) + defer offerCancel() + + peer := livedoor.Peer{Device: "device-blocked-v32"} + bridge := newSignalBridge(offerCtx, host, peer) + + start := time.Now() + stream, err := Offer(offerCtx, rig.viewerConfig(), bridge.viewerSignaller(), bridge.deliver()) + elapsed := time.Since(start) + + if err == nil { + _ = stream.Close() + t.Fatal("Offer succeeded across a completely blocked vnet path") + } + if stream != nil { + t.Fatalf("Offer returned non-nil stream on error: %v", stream) + } + if elapsed > attemptBound+1500*time.Millisecond { + t.Fatalf("Offer took %v, exceeding context bound %v", elapsed, attemptBound) + } + if got := accepted.Load(); got != 0 { + t.Fatalf("host acceptor called %d times on blocked path, want 0", got) + } + + // The end frame sent by Offer (or superseding) releases the host's pending + // slot so a second offer from the same device is accepted. + eventually(t, 2*time.Second, "host pending slot release after blocked offer", func() bool { + return host.pendingCount() == 0 + }) + + secondOfferPayload, encErr := livedoor.EncodeSignal(livedoor.Signal{ + T: livedoor.SignalOffer, + ID: "0123456789abcdef", + SDP: "v=0\r\n", + }) + if encErr != nil { + t.Fatalf("EncodeSignal: %v", encErr) + } + secondSess := host.Offered(hostCtx, peer, secondOfferPayload, fnSignaller(func([]byte) error { return nil })) + if secondSess == nil { + t.Fatal("host rejected second offer from the same device after first attempt ended") + } + secondSess.Close() + + host.Close() + eventually(t, 3*time.Second, "goroutines to return to baseline after host close", func() bool { + return runtime.NumGoroutine() <= baseGoroutines+4 + }) +} + +// Contract V33: a path that dies after opening closes the stream on BOTH ends +// within Disconnected + Failed plus a reasonable margin. +func TestABlockedPathAfterOpenClosesTheStreamWithinTheFailedTimeout(t *testing.T) { + rig := newVNetRig(t) + + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + + host := New(rig.hostConfig()) + defer host.Close() + + hostStreamCh := make(chan io.ReadWriteCloser, 1) + acceptDone := make(chan struct{}) + defer close(acceptDone) + + host.SetAcceptor(ctx, func(_ context.Context, stream io.ReadWriteCloser) { + hostStreamCh <- stream + <-acceptDone + }) + + bridge := newSignalBridge(ctx, host, livedoor.Peer{Device: "device-cut-v33"}) + viewerStream, err := Offer(ctx, rig.viewerConfig(), bridge.viewerSignaller(), bridge.deliver()) + if err != nil { + t.Fatalf("Offer over vnet failed: %v", err) + } + defer func() { _ = viewerStream.Close() }() + + var hostStream io.ReadWriteCloser + select { + case hostStream = <-hostStreamCh: + case <-ctx.Done(): + t.Fatal("timed out waiting for host stream over vnet") + } + + // Exchange one byte to verify the data channel is live before cutting the + // network. + if _, err := viewerStream.Write([]byte{'D'}); err != nil { + t.Fatalf("initial viewer Write: %v", err) + } + var one [1]byte + if _, err := io.ReadFull(hostStream, one[:]); err != nil { + t.Fatalf("initial host ReadFull: %v", err) + } + + // Cut all UDP packets between the peers and time how long both blocked + // reads take to fail. + rig.dropPeers.Store(true) + cutAt := time.Now() + + viewerErrCh := make(chan error, 1) + hostErrCh := make(chan error, 1) + + go func() { + var b [1]byte + _, rerr := viewerStream.Read(b[:]) + viewerErrCh <- rerr + }() + go func() { + var b [1]byte + _, rerr := hostStream.Read(b[:]) + hostErrCh <- rerr + }() + + const maxFailWait = 3500 * time.Millisecond + + select { + case verr := <-viewerErrCh: + if verr == nil { + t.Fatal("viewer Read returned nil error after path died") + } + case <-time.After(maxFailWait): + t.Fatalf("viewer Read did not fail within %v after path died", maxFailWait) + } + + select { + case herr := <-hostErrCh: + if herr == nil { + t.Fatal("host Read returned nil error after path died") + } + case <-time.After(maxFailWait): + t.Fatalf("host Read did not fail within %v after path died", maxFailWait) + } + + if elapsed := time.Since(cutAt); elapsed > maxFailWait { + t.Fatalf("streams closed in %v, want <= %v", elapsed, maxFailWait) + } +} + +// Contract security: when a viewer vanishes without closing its stream, the +// host's ICE agent reaches Failed and closes the host's stream so the acceptor +// goroutine exits promptly. +func TestAHostDropsADirectTunnelWhenTheViewerVanishes(t *testing.T) { + rig := newVNetRig(t) + + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + + host := New(rig.hostConfig()) + defer host.Close() + + acceptorEntered := make(chan struct{}) + acceptorExited := make(chan time.Duration, 1) + var hostStreamRef atomic.Pointer[byteStream] + + host.SetAcceptor(ctx, func(_ context.Context, stream io.ReadWriteCloser) { + if bs, ok := stream.(*byteStream); ok { + hostStreamRef.Store(bs) + } + close(acceptorEntered) + var buf [64]byte + for { + if _, err := stream.Read(buf[:]); err != nil { + return + } + } + }) + + bridge := newSignalBridge(ctx, host, livedoor.Peer{Device: "device-vanish"}) + viewerStream, err := Offer(ctx, rig.viewerConfig(), bridge.viewerSignaller(), bridge.deliver()) + if err != nil { + t.Fatalf("Offer over vnet failed: %v", err) + } + defer func() { _ = viewerStream.Close() }() + + select { + case <-acceptorEntered: + case <-ctx.Done(): + t.Fatal("timed out waiting for host acceptor to start") + } + + // The viewer's network disappears without viewerStream.Close() being + // called. + vanishedAt := time.Now() + rig.dropPeers.Store(true) + + go func() { + eventually(t, 3500*time.Millisecond, "host stream to close after viewer vanishes", func() bool { + bs := hostStreamRef.Load() + return bs != nil && bs.closed.Load() && host.streamCount() == 0 + }) + acceptorExited <- time.Since(vanishedAt) + }() + + select { + case elapsed := <-acceptorExited: + if elapsed > 3500*time.Millisecond { + t.Fatalf("host took %v to drop vanished viewer tunnel, want <= 3.5s", elapsed) + } + case <-time.After(4 * time.Second): + t.Fatal("timed out waiting for host acceptor goroutine to exit after viewer vanished") + } +} diff --git a/internal/directroad/config.go b/internal/directroad/config.go new file mode 100644 index 0000000000..ec0ceb9eb3 --- /dev/null +++ b/internal/directroad/config.go @@ -0,0 +1,218 @@ +// Package directroad opens a peer-to-peer WebRTC data channel between two of a +// person's own computers and hands back an ordinary io.ReadWriteCloser byte +// stream. +// +// The road contract (D20) is fixed so any endpoint, including a phone, can +// interoperate without sharing this package: +// - The viewer is always the SDP offerer and the host is always the answerer. +// - Exactly one m=application data channel is used, pre-negotiated at id 0 +// with label "codeaf-live", ordered and reliable (MaxRetransmits and +// MaxPacketLifeTime are left unset). +// - Signalling frames (offer, answer, trickled ICE candidates, end, refuse) +// travel as opaque livedoor.Signal JSON payloads up to livedoor.SignalMax +// bytes over an already-authenticated relay tunnel owned by the caller. +// - Once the data channel opens, the first byte on the stream is the intent +// byte 'D', followed by a Noise_IK handshake and 2-byte-length-prefixed +// records; NOTHING IN THIS PACKAGE KNOWS ABOUT NOISE OR THE INTENT BYTE, +// which run in the caller above the returned io.ReadWriteCloser. +// - DATA CHANNEL MESSAGES ARE NOT RECORD-ALIGNED, so a reader must treat the +// channel as a continuous byte stream; senders cut writes into messages of +// at most 16 KiB and receivers accept messages up to 64 KiB. +// - ICE servers are STUN only; TURN is never configured or dialled. +package directroad + +import ( + "io" + "strings" + "time" + + "github.com/pion/ice/v4" + "github.com/pion/logging" + "github.com/pion/transport/v5" + "github.com/pion/webrtc/v4" +) + +const ( + // dataChannelLabel is the single pre-negotiated WebRTC data channel label + // shared by the viewer offerer and the host answerer. + dataChannelLabel = "codeaf-live" + + // dataChannelID is the pre-negotiated SCTP stream identifier so neither side + // waits on an in-band DCEP open handshake. + dataChannelID uint16 = 0 + + // Production defaults for ICETimers when a caller leaves a field unset. + defaultICEDisconnected = 3 * time.Second + defaultICEFailed = 5 * time.Second + defaultICEKeepalive = 1 * time.Second + defaultICEGatherTimeout = 3 * time.Second +) + +// droppedInterfacePrefixes lists container and virtual-machine bridge prefixes +// whose addresses are unreachable from another computer and would only add +// dead candidate pairs to ICE checks. +var droppedInterfacePrefixes = []string{ + "docker", + "veth", + "br-", + "virbr", + "vmnet", + "vboxnet", + "cni", + "flannel", + "cali", + "kube", +} + +// ICETimers are the ICE agent's liveness bounds. A zero field means the +// production default. +type ICETimers struct { + Disconnected time.Duration // default 3 s: no inbound for this long -> state Disconnected + Failed time.Duration // default 5 s more: Disconnected this long -> state Failed + Keepalive time.Duration // default 1 s: pion's consent-freshness STUN binding interval + GatherTimeout time.Duration // default 3 s: STUN gathering gives up after this +} + +// withDefaults fills any non-positive timer with its production default so +// callers and tests can override individual timers without zeroing the rest. +func (t ICETimers) withDefaults() ICETimers { + if t.Disconnected <= 0 { + t.Disconnected = defaultICEDisconnected + } + if t.Failed <= 0 { + t.Failed = defaultICEFailed + } + if t.Keepalive <= 0 { + t.Keepalive = defaultICEKeepalive + } + if t.GatherTimeout <= 0 { + t.GatherTimeout = defaultICEGatherTimeout + } + return t +} + +// Config controls candidate gathering, virtual networking, and liveness timers +// for both the viewer Offer call and the host answerer. +type Config struct { + STUN []string // "stun:host:port" URLs, tried in parallel; empty = host candidates only, and NO STUN packet is ever sent + Loopback bool // tests only: also offer loopback candidates + Net transport.Net // tests only: pion vnet; nil = the real network (do not call SetNet) + ICE ICETimers + InterfaceFilter func(name string) bool // nil = the built-in filter below +} + +// defaultInterfaceFilter returns the built-in interface filter. It excludes +// local container and VM bridges that another machine can never reach and +// drops the kernel loopback interface unless loopback candidates were +// requested for a local test. +func defaultInterfaceFilter(includeLoopback bool) func(string) bool { + return func(name string) bool { + if !includeLoopback && (name == "lo" || name == "lo0" || name == "lo0String") { + return false + } + for _, prefix := range droppedInterfacePrefixes { + if strings.HasPrefix(name, prefix) { + return false + } + } + return true + } +} + +// silentLoggerFactory returns a logger factory that discards every line. PION +// MUST NEVER WRITE TO STDOUT OR STDERR because codeaf owns a terminal surface +// and any background log line would tear through the active screen. +func silentLoggerFactory() logging.LoggerFactory { + return &logging.DefaultLoggerFactory{ + Writer: io.Discard, + DefaultLogLevel: logging.LogLevelDisabled, + } +} + +// sanitizeSTUNURLs keeps only plain stun: URLs so a turn: or turns: server can +// never reach pion even if misconfigured by a caller. +func sanitizeSTUNURLs(urls []string) []string { + var clean []string + for _, raw := range urls { + u := strings.TrimSpace(raw) + if strings.HasPrefix(strings.ToLower(u), "stun:") { + clean = append(clean, u) + } + } + return clean +} + +// newPeerConnection builds a pion PeerConnection and the single pre-negotiated +// data channel with identical settings on both the viewer and the host. +func newPeerConnection(cfg Config) (*webrtc.PeerConnection, *webrtc.DataChannel, error) { + var se webrtc.SettingEngine + + // PION MUST NEVER WRITE TO STDOUT OR STDERR because the program runs a + // terminal UI and any warning line would draw over it. + se.LoggerFactory = silentLoggerFactory() + + // Detach the data channel so OnOpen yields an io.ReadWriteCloser rather than + // starting pion's internal callback read loop. + se.DetachDataChannels() + + // EnableDataChannelBlockWrite forwards sctp.WithBlockWrite(true) to the SCTP + // association when DetachDataChannels is enabled, so Stream.Write blocks + // once a message is in pendingQueue until popPendingDataChunksToSend moves + // it into the CWND/RWND-bounded inflightQueue instead of buffering without + // bound against a slow reader. + se.EnableDataChannelBlockWrite(true) + + timers := cfg.ICE.withDefaults() + se.SetICETimeouts(timers.Disconnected, timers.Failed, timers.Keepalive) + se.SetSTUNGatherTimeout(timers.GatherTimeout) + + // mDNS candidates are disabled because both peers are the person's own + // computers and real addresses are the point of the direct road. + se.SetICEMulticastDNSMode(ice.MulticastDNSModeDisabled) + + // Direct paths travel over UDP4 and UDP6 only; ICE-TCP is never used. + se.SetNetworkTypes([]webrtc.NetworkType{ + webrtc.NetworkTypeUDP4, + webrtc.NetworkTypeUDP6, + }) + + se.SetIncludeLoopbackCandidate(cfg.Loopback) + + filter := cfg.InterfaceFilter + if filter == nil { + filter = defaultInterfaceFilter(cfg.Loopback) + } + se.SetInterfaceFilter(filter) + + if cfg.Net != nil { + se.SetNet(cfg.Net) + } + + // Certificate fingerprint verification stays at its default (enabled); + // DisableCertificateFingerprintVerification is NEVER called. + var rtcCfg webrtc.Configuration + if stunURLs := sanitizeSTUNURLs(cfg.STUN); len(stunURLs) > 0 { + rtcCfg.ICEServers = []webrtc.ICEServer{ + {URLs: stunURLs}, + } + } + + api := webrtc.NewAPI(webrtc.WithSettingEngine(se)) + pc, err := api.NewPeerConnection(rtcCfg) + if err != nil { + return nil, nil, err + } + + negotiated := true + id := dataChannelID + dc, err := pc.CreateDataChannel(dataChannelLabel, &webrtc.DataChannelInit{ + Negotiated: &negotiated, + ID: &id, + }) + if err != nil { + _ = pc.Close() + return nil, nil, err + } + + return pc, dc, nil +} diff --git a/internal/directroad/fingerprint_test.go b/internal/directroad/fingerprint_test.go new file mode 100644 index 0000000000..8f37aeacaa --- /dev/null +++ b/internal/directroad/fingerprint_test.go @@ -0,0 +1,149 @@ +package directroad + +import ( + "context" + "go/ast" + "go/parser" + "go/token" + "io" + "os" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/livedoor" +) + +// bogusSHA256Fingerprint is a syntactically valid SHA-256 SDP fingerprint line +// that will never match the ephemeral certificate generated by the host. +const bogusSHA256Fingerprint = "a=fingerprint:sha-256 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF" + +// Contract security: the DTLS fingerprint in the answer SDP is verified by +// pion during the DTLS handshake, and DisableCertificateFingerprintVerification +// is never referenced in non-test package source. +func TestTheDTLSFingerprintInTheAnswerIsVerified(t *testing.T) { + // 1. Scan every non-test Go file in this directory to prove that + // DisableCertificateFingerprintVerification is never called. + entries, err := os.ReadDir(".") + if err != nil { + t.Fatalf("os.ReadDir: %v", err) + } + fset := token.NewFileSet() + scanned := 0 + for _, entry := range entries { + name := entry.Name() + if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + scanned++ + fileAST, err := parser.ParseFile(fset, name, nil, 0) + if err != nil { + t.Fatalf("parser.ParseFile(%s): %v", name, err) + } + ast.Inspect(fileAST, func(n ast.Node) bool { + if ident, ok := n.(*ast.Ident); ok { + if ident.Name == "DisableCertificateFingerprintVerification" || + ident.Name == "disableCertificateFingerprintVerification" { + t.Fatalf("%s references forbidden identifier %s", name, ident.Name) + } + } + return true + }) + } + if scanned == 0 { + t.Fatal("expected to scan non-test Go source files, found 0") + } + + // 2. The control: the same rig with nothing rewritten opens a stream, so the + // failure below is the tampered fingerprint and not a broken rig. + t.Run("an untampered answer opens a stream", func(t *testing.T) { + rig := newVNetRig(t) + host := New(rig.hostConfig()) + defer host.Close() + hostCtx, hostCancel := context.WithCancel(context.Background()) + defer hostCancel() + opened := make(chan struct{}, 1) + host.SetAcceptor(hostCtx, func(ctx context.Context, stream io.ReadWriteCloser) { + opened <- struct{}{} + <-ctx.Done() + _ = stream.Close() + }) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + bridge := newSignalBridge(ctx, host, livedoor.Peer{Device: "device-control"}) + stream, err := Offer(ctx, rig.viewerConfig(), bridge.viewerSignaller(), bridge.deliver()) + if err != nil { + t.Fatalf("the control Offer failed, so the tampered case proves nothing: %v", err) + } + defer func() { _ = stream.Close() }() + select { + case <-opened: + case <-ctx.Done(): + t.Fatal("the control host never received its stream") + } + }) + + // 3. Tamper with the answer SDP's a=fingerprint: line on the wire and verify + // that Offer refuses to return a stream and the host keeps no open stream. + rig := newVNetRig(t) + + hostCtx, hostCancel := context.WithCancel(context.Background()) + defer hostCancel() + + host := New(rig.hostConfig()) + defer host.Close() + + var hostStreamOpened atomic.Bool + host.SetAcceptor(hostCtx, func(_ context.Context, stream io.ReadWriteCloser) { + hostStreamOpened.Store(true) + _ = stream.Close() + }) + + offerCtx, offerCancel := context.WithTimeout(context.Background(), 2*time.Second) + defer offerCancel() + + bridge := newSignalBridge(offerCtx, host, livedoor.Peer{Device: "device-fingerprint"}) + var tampered atomic.Bool + bridge.hostHook = func(payload []byte) ([]byte, bool) { + sig, err := livedoor.DecodeSignal(payload) + if err != nil || sig.T != livedoor.SignalAnswer { + return payload, true + } + lines := strings.Split(sig.SDP, "\n") + for i, line := range lines { + trimmed := strings.TrimRight(line, "\r") + if strings.HasPrefix(trimmed, "a=fingerprint:") { + lines[i] = bogusSHA256Fingerprint + "\r" + tampered.Store(true) + } + } + sig.SDP = strings.Join(lines, "\n") + rewritten, err := livedoor.EncodeSignal(sig) + if err != nil { + t.Errorf("EncodeSignal tampered answer: %v", err) + return payload, false + } + return rewritten, true + } + + stream, err := Offer(offerCtx, rig.viewerConfig(), bridge.viewerSignaller(), bridge.deliver()) + if !tampered.Load() { + t.Fatal("answer SDP contained no a=fingerprint: line to rewrite") + } + if err == nil { + _ = stream.Close() + t.Fatal("Offer succeeded despite a tampered DTLS fingerprint in the answer SDP") + } + t.Logf("the tampered Offer ended with: %v", err) + if stream != nil { + t.Fatalf("Offer returned non-nil stream on DTLS fingerprint failure: %v", stream) + } + + eventually(t, 2*time.Second, "host to release pending session and hold no open streams", func() bool { + return host.pendingCount() == 0 && host.streamCount() == 0 + }) + if hostStreamOpened.Load() && host.streamCount() != 0 { + t.Fatal("host kept an open stream after DTLS fingerprint verification failed") + } +} diff --git a/internal/directroad/host_test.go b/internal/directroad/host_test.go new file mode 100644 index 0000000000..6a91f8f168 --- /dev/null +++ b/internal/directroad/host_test.go @@ -0,0 +1,209 @@ +package directroad + +import ( + "context" + "errors" + "fmt" + "io" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/livedoor" +) + +// sampleOfferSDP returns a valid data-channel offer SDP generated once from a +// real PeerConnection so host policy tests can submit well-formed offers. +func sampleOfferSDP(t *testing.T) string { + t.Helper() + pc, _, err := newPeerConnection(loopbackConfig()) + if err != nil { + t.Fatalf("newPeerConnection: %v", err) + } + defer func() { _ = pc.Close() }() + + offer, err := pc.CreateOffer(nil) + if err != nil { + t.Fatalf("CreateOffer: %v", err) + } + return offer.SDP +} + +func mustEncodeOffer(t *testing.T, id, sdp string) []byte { + t.Helper() + payload, err := livedoor.EncodeSignal(livedoor.Signal{ + T: livedoor.SignalOffer, + ID: id, + SDP: sdp, + }) + if err != nil { + t.Fatalf("EncodeSignal: %v", err) + } + return payload +} + +// Contract: Host.Offered enforces synchronous admission policy: +// - returns nil before SetAcceptor or on invalid/non-offer payloads; +// - supersedes an existing pending offer from the same peer.Device (closing +// the old session and accepting the new one); +// - caps concurrent pending offers at livedoor.PendingOffers across distinct +// devices; +// - releases pending attempts that produce no stream within livedoor.OfferTTL. +func TestAnOfferFromTheSameDeviceSupersedesItsPendingOneAndTheCapsHold(t *testing.T) { + sdp := sampleOfferSDP(t) + noopSignaller := fnSignaller(func([]byte) error { return nil }) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + rig := newVNetRig(t) + host := New(rig.hostConfig()) + defer host.Close() + + // 1. Before SetAcceptor is called, Offered must refuse (return nil). + validOffer := mustEncodeOffer(t, "0000000000000001", sdp) + if sess := host.Offered(ctx, livedoor.Peer{Device: "dev-1"}, validOffer, noopSignaller); sess != nil { + sess.Close() + t.Fatal("Offered succeeded before SetAcceptor was installed") + } + + host.SetAcceptor(ctx, func(_ context.Context, stream io.ReadWriteCloser) { + _ = stream.Close() + }) + + // 2. Invalid payloads, wrong signal kind, empty ID, and empty SDP all + // return nil synchronously without taking a slot. + if sess := host.Offered(ctx, livedoor.Peer{Device: "dev-1"}, []byte("{not-json"), noopSignaller); sess != nil { + t.Fatal("Offered accepted undecodable payload") + } + endFrame, _ := livedoor.EncodeSignal(livedoor.Signal{T: livedoor.SignalEnd, ID: "0000000000000001"}) + if sess := host.Offered(ctx, livedoor.Peer{Device: "dev-1"}, endFrame, noopSignaller); sess != nil { + t.Fatal("Offered accepted non-offer signal") + } + emptyID, _ := livedoor.EncodeSignal(livedoor.Signal{T: livedoor.SignalOffer, ID: "", SDP: sdp}) + if sess := host.Offered(ctx, livedoor.Peer{Device: "dev-1"}, emptyID, noopSignaller); sess != nil { + t.Fatal("Offered accepted offer with empty ID") + } + emptySDP, _ := livedoor.EncodeSignal(livedoor.Signal{T: livedoor.SignalOffer, ID: "0000000000000001", SDP: ""}) + if sess := host.Offered(ctx, livedoor.Peer{Device: "dev-1"}, emptySDP, noopSignaller); sess != nil { + t.Fatal("Offered accepted offer with empty SDP") + } + if got := host.pendingCount(); got != 0 { + t.Fatalf("pendingCount after invalid offers = %d, want 0", got) + } + + // 3. A second offer from the SAME peer.Device supersedes and closes the + // first session rather than refusing as busy. + firstSess := host.Offered(ctx, livedoor.Peer{Device: "dev-1"}, mustEncodeOffer(t, "1111111111111111", sdp), noopSignaller) + if firstSess == nil { + t.Fatal("first offer from dev-1 was refused") + } + secondSess := host.Offered(ctx, livedoor.Peer{Device: "dev-1"}, mustEncodeOffer(t, "2222222222222222", sdp), noopSignaller) + if secondSess == nil { + t.Fatal("superseding offer from dev-1 was refused") + } + if !firstSess.(*hostSession).closed.Load() { + t.Fatal("first pending session from dev-1 was not closed when superseded") + } + if got := host.pendingCount(); got != 1 { + t.Fatalf("pendingCount after superseding same device = %d, want 1", got) + } + + // 4. Fill remaining slots up to livedoor.PendingOffers from distinct + // devices; the (livedoor.PendingOffers + 1)th distinct device must get nil. + sessions := []livedoor.DirectSession{secondSess} + for i := 2; i <= livedoor.PendingOffers; i++ { + dev := fmt.Sprintf("dev-%d", i) + id := fmt.Sprintf("%016x", i) + s := host.Offered(ctx, livedoor.Peer{Device: dev}, mustEncodeOffer(t, id, sdp), noopSignaller) + if s == nil { + t.Fatalf("offer %d (within PendingOffers=%d) was refused", i, livedoor.PendingOffers) + } + sessions = append(sessions, s) + } + if got := host.pendingCount(); got != livedoor.PendingOffers { + t.Fatalf("pendingCount = %d, want %d", got, livedoor.PendingOffers) + } + + overflowDev := fmt.Sprintf("dev-%d", livedoor.PendingOffers+1) + if overflow := host.Offered(ctx, livedoor.Peer{Device: overflowDev}, mustEncodeOffer(t, "ffffffffffffffff", sdp), noopSignaller); overflow != nil { + overflow.Close() + t.Fatalf("offer %d beyond livedoor.PendingOffers=%d was accepted", livedoor.PendingOffers+1, livedoor.PendingOffers) + } + + // Even when all livedoor.PendingOffers slots are full, a new offer from an + // already-pending device still supersedes its own slot. + replaced := host.Offered(ctx, livedoor.Peer{Device: "dev-1"}, mustEncodeOffer(t, "3333333333333333", sdp), noopSignaller) + if replaced == nil { + t.Fatal("superseding offer from dev-1 was refused when host was at PendingOffers cap") + } + sessions[0] = replaced + + for _, s := range sessions { + s.Close() + } + if got := host.pendingCount(); got != 0 { + t.Fatalf("pendingCount after closing all sessions = %d, want 0", got) + } + + // 5. Shrink livedoor.OfferTTL and verify that a pending attempt with no + // stream is automatically closed and releases its slot after OfferTTL. + origTTL := livedoor.OfferTTL + livedoor.OfferTTL = 150 * time.Millisecond + t.Cleanup(func() { + livedoor.OfferTTL = origTTL + }) + + ttlSess := host.Offered(ctx, livedoor.Peer{Device: "dev-ttl"}, mustEncodeOffer(t, "4444444444444444", sdp), noopSignaller) + if ttlSess == nil { + t.Fatal("TTL test offer was refused") + } + if got := host.pendingCount(); got != 1 { + t.Fatalf("pendingCount = %d, want 1", got) + } + + eventually(t, 2*time.Second, "pending offer to expire after OfferTTL", func() bool { + return host.pendingCount() == 0 + }) +} + +// Contract: when the host answers an offer with a refuse signal, Offer returns +// *RefusedError carrying the reason promptly and leaks nothing. +func TestARefusalEndsOfferWithARefusedError(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + + // A host without SetAcceptor returns nil from Offered, causing the bridge + // (acting as the router) to send a refuse signal with RefuseBusy. + host := New(loopbackConfig()) + defer host.Close() + + bridge := newSignalBridge(ctx, host, livedoor.Peer{Device: "viewer-refused"}) + bridge.refuseOnNil = livedoor.RefuseBusy + + start := time.Now() + stream, err := Offer(ctx, loopbackConfig(), bridge.viewerSignaller(), bridge.deliver()) + elapsed := time.Since(start) + + if err == nil { + _ = stream.Close() + t.Fatal("Offer succeeded when host refused") + } + if stream != nil { + t.Fatalf("Offer returned non-nil stream on refusal: %v", stream) + } + + var refused *RefusedError + if !errors.As(err, &refused) { + t.Fatalf("Offer error = %T (%v), want *RefusedError", err, err) + } + if refused.Reason != livedoor.RefuseBusy { + t.Fatalf("RefusedError.Reason = %q, want %q", refused.Reason, livedoor.RefuseBusy) + } + wantText := "directroad: the host refused the offer: " + livedoor.RefuseBusy + if refused.Error() != wantText { + t.Fatalf("RefusedError.Error() = %q, want %q", refused.Error(), wantText) + } + if elapsed > 2*time.Second { + t.Fatalf("Refused Offer took %v, expected prompt return", elapsed) + } +} diff --git a/internal/directroad/loop_test.go b/internal/directroad/loop_test.go new file mode 100644 index 0000000000..a2d4119087 --- /dev/null +++ b/internal/directroad/loop_test.go @@ -0,0 +1,149 @@ +package directroad + +import ( + "bytes" + "context" + "encoding/binary" + "io" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/livedoor" +) + +// Contract V30: a direct road opens between two computers over loopback and +// carries bytes across message boundaries in both directions. +func TestTwoPeersConnectOverLoopbackAndEchoBytesAcrossMessageBoundaries(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + + cfg := loopbackConfig() + host := New(cfg) + defer host.Close() + + var acceptedCount atomic.Int32 + hostStreamCh := make(chan io.ReadWriteCloser, 1) + acceptDone := make(chan struct{}) + defer close(acceptDone) + + host.SetAcceptor(ctx, func(_ context.Context, stream io.ReadWriteCloser) { + acceptedCount.Add(1) + hostStreamCh <- stream + <-acceptDone + }) + + bridge := newSignalBridge(ctx, host, livedoor.Peer{Device: "viewer-loopback"}) + + viewerStream, err := Offer(ctx, cfg, bridge.viewerSignaller(), bridge.deliver()) + if err != nil { + t.Fatalf("Offer failed: %v", err) + } + defer func() { _ = viewerStream.Close() }() + + var hostStream io.ReadWriteCloser + select { + case hostStream = <-hostStreamCh: + case <-ctx.Done(): + t.Fatal("timed out waiting for host acceptor to receive stream") + } + + if got := acceptedCount.Load(); got != 1 { + t.Fatalf("host acceptor received %d streams, want 1", got) + } + + // Build the three writes: 1 intent byte, 2-byte prefix + body, and 100 KiB. + intent := []byte{'D'} + recordBody := bytes.Repeat([]byte("handshake-and-record-"), 60) + prefixed := make([]byte, 2+len(recordBody)) + binary.BigEndian.PutUint16(prefixed[:2], uint16(len(recordBody))) + copy(prefixed[2:], recordBody) + + large := make([]byte, 100<<10) + for i := range large { + large[i] = byte((i*29 + 11) & 0xff) + } + + hostErrCh := make(chan error, 1) + go func() { + totalLen := len(intent) + len(prefixed) + len(large) + buf := make([]byte, totalLen) + if _, err := io.ReadFull(hostStream, buf); err != nil { + hostErrCh <- err + return + } + if _, err := hostStream.Write(buf); err != nil { + hostErrCh <- err + return + } + hostErrCh <- nil + }() + + if _, err := viewerStream.Write(intent); err != nil { + t.Fatalf("viewer Write(1 byte): %v", err) + } + if _, err := viewerStream.Write(prefixed); err != nil { + t.Fatalf("viewer Write(prefixed): %v", err) + } + if _, err := viewerStream.Write(large); err != nil { + t.Fatalf("viewer Write(100 KiB): %v", err) + } + + var gotIntent [1]byte + if _, err := io.ReadFull(viewerStream, gotIntent[:]); err != nil { + t.Fatalf("viewer ReadFull(1 byte): %v", err) + } + if gotIntent[0] != intent[0] { + t.Fatalf("echoed intent byte = %q, want %q", gotIntent[0], intent[0]) + } + + var gotHdr [2]byte + if _, err := io.ReadFull(viewerStream, gotHdr[:]); err != nil { + t.Fatalf("viewer ReadFull(2-byte prefix): %v", err) + } + gotBodyLen := int(binary.BigEndian.Uint16(gotHdr[:])) + if gotBodyLen != len(recordBody) { + t.Fatalf("echoed prefix length = %d, want %d", gotBodyLen, len(recordBody)) + } + gotBody := make([]byte, gotBodyLen) + if _, err := io.ReadFull(viewerStream, gotBody); err != nil { + t.Fatalf("viewer ReadFull(body): %v", err) + } + if !bytes.Equal(gotBody, recordBody) { + t.Fatal("echoed record body mismatch") + } + + gotLarge := make([]byte, len(large)) + if _, err := io.ReadFull(viewerStream, gotLarge); err != nil { + t.Fatalf("viewer ReadFull(100 KiB): %v", err) + } + if !bytes.Equal(gotLarge, large) { + t.Fatal("echoed 100 KiB payload mismatch") + } + + if err := <-hostErrCh; err != nil { + t.Fatalf("host echo goroutine failed: %v", err) + } + + // Closing the viewer's stream must end the host's next read with an + // error/EOF. + if err := viewerStream.Close(); err != nil { + t.Fatalf("viewerStream.Close: %v", err) + } + + closeReadCh := make(chan error, 1) + go func() { + var b [1]byte + _, err := hostStream.Read(b[:]) + closeReadCh <- err + }() + + select { + case err := <-closeReadCh: + if err == nil { + t.Fatal("expected host Read after viewer Close to return an error/EOF, got nil") + } + case <-ctx.Done(): + t.Fatal("timed out waiting for host Read to end after viewer Close") + } +} diff --git a/internal/directroad/net_test_helpers_test.go b/internal/directroad/net_test_helpers_test.go new file mode 100644 index 0000000000..9f4e6d7fbd --- /dev/null +++ b/internal/directroad/net_test_helpers_test.go @@ -0,0 +1,295 @@ +package directroad + +import ( + "context" + "net" + "runtime" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/pion/transport/v5/vnet" +) + +const ( + testViewerIP = "10.0.0.1" + testHostIP = "10.0.0.2" + testSTUNIP = "10.0.0.3" +) + +// testICETimers returns fast ICE liveness timers suitable for deterministic +// unit tests over loopback and vnet. +func testICETimers() ICETimers { + return ICETimers{ + Disconnected: 300 * time.Millisecond, + Failed: 600 * time.Millisecond, + Keepalive: 100 * time.Millisecond, + GatherTimeout: 300 * time.Millisecond, + } +} + +// loopbackConfig returns a Config that gathers real loopback candidates with +// no STUN servers. +func loopbackConfig() Config { + return Config{ + Loopback: true, + ICE: testICETimers(), + } +} + +// eventually polls cond without sleeping until it returns true or timeout +// expires. +func eventually(t *testing.T, timeout time.Duration, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(timeout) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out after %v waiting for %s", timeout, what) + } + runtime.Gosched() + } +} + +// fnSignaller adapts a function into a livedoor.Signaller. +type fnSignaller func(payload []byte) error + +func (f fnSignaller) Send(payload []byte) error { + return f(payload) +} + +// signalBridge wires a viewer Offer call to a Host in memory, recording every +// signalling payload in both directions and allowing tests to inspect, modify, +// or drop frames via optional hooks. +type signalBridge struct { + ctx context.Context + host *Host + peer livedoor.Peer + viewerDeliver chan []byte + + mu sync.Mutex + session livedoor.DirectSession + viewerPayloads [][]byte + hostPayloads [][]byte + viewerHook func(payload []byte) ([]byte, bool) + hostHook func(payload []byte) ([]byte, bool) + refuseOnNil string +} + +// newSignalBridge constructs a bridge between one viewer attempt and host. +func newSignalBridge(ctx context.Context, host *Host, peer livedoor.Peer) *signalBridge { + if peer.Device == "" { + peer.Device = "viewer-device-1" + } + return &signalBridge{ + ctx: ctx, + host: host, + peer: peer, + viewerDeliver: make(chan []byte, 256), + } +} + +// viewerSignaller returns the Signaller passed to Offer. +func (b *signalBridge) viewerSignaller() livedoor.Signaller { + return fnSignaller(func(payload []byte) error { + cp := append([]byte(nil), payload...) + + b.mu.Lock() + b.viewerPayloads = append(b.viewerPayloads, cp) + hook := b.viewerHook + b.mu.Unlock() + + if hook != nil { + var keep bool + cp, keep = hook(cp) + if !keep { + return nil + } + } + + sig, err := livedoor.DecodeSignal(cp) + if err == nil && sig.T == livedoor.SignalOffer { + var sess livedoor.DirectSession + if b.host != nil { + sess = b.host.Offered(b.ctx, b.peer, cp, b.hostSignaller()) + } + b.mu.Lock() + b.session = sess + reason := b.refuseOnNil + b.mu.Unlock() + + if sess == nil && reason != "" { + _ = sendSignal(b.hostSignaller(), livedoor.Signal{ + T: livedoor.SignalRefuse, + ID: sig.ID, + Reason: reason, + }) + } + return nil + } + + b.mu.Lock() + sess := b.session + b.mu.Unlock() + if sess != nil { + sess.Deliver(cp) + } + return nil + }) +} + +// hostSignaller returns the Signaller passed to Host.Offered. +func (b *signalBridge) hostSignaller() livedoor.Signaller { + return fnSignaller(func(payload []byte) error { + cp := append([]byte(nil), payload...) + + b.mu.Lock() + b.hostPayloads = append(b.hostPayloads, cp) + hook := b.hostHook + b.mu.Unlock() + + if hook != nil { + var keep bool + cp, keep = hook(cp) + if !keep { + return nil + } + } + + select { + case b.viewerDeliver <- cp: + default: + } + return nil + }) +} + +// deliver returns the viewer's inbound signalling channel. +func (b *signalBridge) deliver() <-chan []byte { + return b.viewerDeliver +} + +// vnetRig hosts an in-memory pion vnet router with separate virtual NICs for +// the viewer, the host, and an optional fake STUN server. +type vnetRig struct { + router *vnet.Router + viewerNet *vnet.Net + hostNet *vnet.Net + stunNet *vnet.Net + + dropPeers atomic.Bool + + mu sync.Mutex + chunksByDstIP map[string]int64 +} + +// newVNetRig builds and starts a virtual network router on 10.0.0.0/24 and +// registers router shutdown with t.Cleanup. +func newVNetRig(t *testing.T) *vnetRig { + t.Helper() + + router, err := vnet.NewRouter(&vnet.RouterConfig{ + CIDR: "10.0.0.0/24", + LoggerFactory: silentLoggerFactory(), + }) + if err != nil { + t.Fatalf("vnet.NewRouter: %v", err) + } + + viewerNet, err := vnet.NewNet(&vnet.NetConfig{ + StaticIPs: []string{testViewerIP}, + }) + if err != nil { + t.Fatalf("vnet.NewNet viewer: %v", err) + } + hostNet, err := vnet.NewNet(&vnet.NetConfig{ + StaticIPs: []string{testHostIP}, + }) + if err != nil { + t.Fatalf("vnet.NewNet host: %v", err) + } + stunNet, err := vnet.NewNet(&vnet.NetConfig{ + StaticIPs: []string{testSTUNIP}, + }) + if err != nil { + t.Fatalf("vnet.NewNet stun: %v", err) + } + + if err := router.AddNet(viewerNet); err != nil { + t.Fatalf("router.AddNet viewer: %v", err) + } + if err := router.AddNet(hostNet); err != nil { + t.Fatalf("router.AddNet host: %v", err) + } + if err := router.AddNet(stunNet); err != nil { + t.Fatalf("router.AddNet stun: %v", err) + } + + rig := &vnetRig{ + router: router, + viewerNet: viewerNet, + hostNet: hostNet, + stunNet: stunNet, + chunksByDstIP: make(map[string]int64), + } + + router.AddChunkFilter(func(c vnet.Chunk) bool { + if dst, ok := c.DestinationAddr().(*net.UDPAddr); ok && dst.IP != nil { + ipStr := dst.IP.String() + rig.mu.Lock() + rig.chunksByDstIP[ipStr]++ + rig.mu.Unlock() + } + if rig.dropPeers.Load() { + return false + } + return true + }) + + if err := router.Start(); err != nil { + t.Fatalf("router.Start: %v", err) + } + t.Cleanup(func() { + _ = router.Stop() + }) + + return rig +} + +// viewerConfig returns a directroad Config bound to the viewer's vnet NIC. +func (r *vnetRig) viewerConfig() Config { + return Config{ + Net: r.viewerNet, + ICE: testICETimers(), + } +} + +// hostConfig returns a directroad Config bound to the host's vnet NIC. +func (r *vnetRig) hostConfig() Config { + return Config{ + Net: r.hostNet, + ICE: testICETimers(), + } +} + +// chunksTo returns the number of routed UDP chunks addressed to ip. +func (r *vnetRig) chunksTo(ip string) int64 { + r.mu.Lock() + defer r.mu.Unlock() + return r.chunksByDstIP[ip] +} + +// pendingCount reports how many attempts are currently pending on h. +func (h *Host) pendingCount() int { + h.mu.Lock() + defer h.mu.Unlock() + return len(h.pending) +} + +// streamCount reports how many open streams are currently tracked on h. +func (h *Host) streamCount() int { + h.mu.Lock() + defer h.mu.Unlock() + return len(h.streams) +} diff --git a/internal/directroad/offer.go b/internal/directroad/offer.go new file mode 100644 index 0000000000..af031e27f6 --- /dev/null +++ b/internal/directroad/offer.go @@ -0,0 +1,132 @@ +package directroad + +import ( + "context" + "errors" + "fmt" + "io" + + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/pion/webrtc/v4" +) + +// RefusedError is returned by Offer when the host answers the offer with a +// refuse signal. +type RefusedError struct { + Reason string +} + +// Error formats the refusal reason with the fixed package prefix. +func (e *RefusedError) Error() string { + return "directroad: the host refused the offer: " + e.Reason +} + +// Offer runs the viewer side of a direct-road attempt. It creates an offer, +// exchanges signalling over s and deliver until the pre-negotiated data +// channel opens and is detached, and returns the resulting byte stream. +// +// ctx bounds the connection attempt only; cancelling ctx after Offer succeeds +// does not close the returned stream. +func Offer(ctx context.Context, cfg Config, s livedoor.Signaller, deliver <-chan []byte) (io.ReadWriteCloser, error) { + if ctx == nil { + ctx = context.Background() + } + if err := ctx.Err(); err != nil { + return nil, err + } + + id, err := newAttemptID() + if err != nil { + return nil, err + } + + sess, err := newPCSession(id, cfg, s) + if err != nil { + return nil, err + } + + offerDesc, err := sess.pc.CreateOffer(nil) + if err != nil { + sess.abort() + return nil, err + } + if err := sess.pc.SetLocalDescription(offerDesc); err != nil { + sess.abort() + return nil, err + } + if err := sendOffer(s, id, offerDesc.SDP); err != nil { + sess.abort() + return nil, err + } + + failAttempt := func(cause error) (io.ReadWriteCloser, error) { + _ = sendEnd(s, id) + sess.abort() + return nil, cause + } + + answerApplied := false + for { + select { + case stream := <-sess.openCh: + return stream, nil + case err := <-sess.errCh: + return failAttempt(err) + case <-ctx.Done(): + return failAttempt(fmt.Errorf("directroad: offer timed out: %w", ctx.Err())) + case payload, ok := <-deliver: + if !ok { + return failAttempt(errors.New("directroad: signal delivery channel closed")) + } + sig, err := livedoor.DecodeSignal(payload) + if err != nil { + // Payloads that do not decode are ignored here because the + // underlying relay link polices wire framing. + continue + } + + switch sig.T { + case livedoor.SignalRefuse: + if sig.ID != "" && sig.ID != id { + continue + } + sess.abort() + return nil, &RefusedError{Reason: sig.Reason} + + case livedoor.SignalEnd: + if sig.ID != id { + continue + } + sess.abort() + return nil, errors.New("directroad: host ended the attempt") + + case livedoor.SignalAnswer: + if sig.ID != id { + continue + } + if sig.SDP == "" { + return failAttempt(errors.New("directroad: empty answer SDP")) + } + if answerApplied { + continue + } + answerApplied = true + err := sess.setRemoteDescription(webrtc.SessionDescription{ + Type: webrtc.SDPTypeAnswer, + SDP: sig.SDP, + }) + if err != nil { + return failAttempt(err) + } + + case livedoor.SignalCandidate: + if sig.ID != id { + continue + } + if err := sess.addCandidate(sig); err != nil { + return failAttempt(err) + } + } + } + } +} diff --git a/internal/directroad/session.go b/internal/directroad/session.go new file mode 100644 index 0000000000..87cb71f3c8 --- /dev/null +++ b/internal/directroad/session.go @@ -0,0 +1,194 @@ +package directroad + +import ( + "errors" + "io" + "sync" + + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/pion/webrtc/v4" +) + +// errConnectionFailed is reported when the peer connection reaches Failed or +// Closed before or after the data channel opens. +var errConnectionFailed = errors.New("directroad: peer connection failed") + +// pcSession wraps a pion PeerConnection and its single pre-negotiated data +// channel for either the viewer offerer or the host answerer. It queues remote +// ICE candidates that arrive before the remote description is applied and +// guarantees idempotent teardown of both the stream and the peer connection. +type pcSession struct { + id string + pc *webrtc.PeerConnection + dc *webrtc.DataChannel + s livedoor.Signaller + + openCh chan io.ReadWriteCloser + errCh chan error + + mu sync.Mutex + remoteReady bool + pendingCand []webrtc.ICECandidateInit + stream *byteStream + closed bool + closeOnce sync.Once +} + +// newPCSession constructs the peer connection and registers trickle-ICE, +// connection-state, and data-channel open callbacks. +func newPCSession(id string, cfg Config, s livedoor.Signaller) (*pcSession, error) { + pc, dc, err := newPeerConnection(cfg) + if err != nil { + return nil, err + } + + sess := &pcSession{ + id: id, + pc: pc, + dc: dc, + s: s, + openCh: make(chan io.ReadWriteCloser, 1), + errCh: make(chan error, 1), + } + + pc.OnICECandidate(sess.onLocalCandidate) + pc.OnConnectionStateChange(sess.onConnectionState) + dc.OnOpen(sess.onChannelOpen) + + return sess, nil +} + +// onLocalCandidate trickles each gathered local candidate to the peer as soon +// as pion produces it; a send failure ends the attempt. +func (p *pcSession) onLocalCandidate(cand *webrtc.ICECandidate) { + p.mu.Lock() + closed := p.closed + p.mu.Unlock() + if closed { + return + } + if err := sendCandidate(p.s, p.id, cand); err != nil { + p.fail(err) + } +} + +// onConnectionState closes the byte stream or fails the pending attempt when +// the peer connection reaches Failed or Closed. Disconnected is ignored +// because a briefly interrupted path can recover before the failed timeout. +func (p *pcSession) onConnectionState(state webrtc.PeerConnectionState) { + if state != webrtc.PeerConnectionStateFailed && state != webrtc.PeerConnectionStateClosed { + return + } + p.mu.Lock() + st := p.stream + p.mu.Unlock() + if st != nil { + _ = st.Close() + } + p.fail(errConnectionFailed) +} + +// onChannelOpen detaches the opened data channel, wraps it in a byteStream, +// and delivers it on openCh at most once. +func (p *pcSession) onChannelOpen() { + raw, err := p.dc.Detach() + if err != nil { + p.fail(err) + return + } + + st := newByteStream(raw, p.closePC) + + p.mu.Lock() + if p.closed || p.stream != nil { + p.mu.Unlock() + _ = st.Close() + return + } + p.stream = st + p.mu.Unlock() + + if state := p.pc.ConnectionState(); state == webrtc.PeerConnectionStateFailed || state == webrtc.PeerConnectionStateClosed { + _ = st.Close() + p.fail(errConnectionFailed) + return + } + + select { + case p.openCh <- st: + default: + } +} + +// setRemoteDescription applies desc to the peer connection and flushes any +// trickled remote candidates that arrived ahead of it, in order. +func (p *pcSession) setRemoteDescription(desc webrtc.SessionDescription) error { + if err := p.pc.SetRemoteDescription(desc); err != nil { + return err + } + + p.mu.Lock() + p.remoteReady = true + queued := p.pendingCand + p.pendingCand = nil + p.mu.Unlock() + + for _, cand := range queued { + if err := p.pc.AddICECandidate(cand); err != nil { + return err + } + } + return nil +} + +// addCandidate either queues a remote candidate that arrived before the remote +// description or adds it directly to the peer connection. +func (p *pcSession) addCandidate(sig livedoor.Signal) error { + init, ok := candidateInitFromSignal(sig) + if !ok { + return nil + } + + p.mu.Lock() + if !p.remoteReady { + p.pendingCand = append(p.pendingCand, init) + p.mu.Unlock() + return nil + } + p.mu.Unlock() + + return p.pc.AddICECandidate(init) +} + +// fail records the first fatal error for a connecting attempt. +func (p *pcSession) fail(err error) { + select { + case p.errCh <- err: + default: + } +} + +// closePC closes the underlying pion PeerConnection at most once. +func (p *pcSession) closePC() { + p.closeOnce.Do(func() { + p.mu.Lock() + p.closed = true + p.mu.Unlock() + _ = p.pc.Close() + }) +} + +// abort tears down a connecting attempt and waits for pion's internal worker +// goroutines to exit so failed attempts never leak resources. +func (p *pcSession) abort() { + p.mu.Lock() + p.closed = true + st := p.stream + p.mu.Unlock() + + if st != nil { + _ = st.Close() + } + p.closePC() + _ = p.pc.GracefulClose() +} diff --git a/internal/directroad/signal.go b/internal/directroad/signal.go new file mode 100644 index 0000000000..ded8dcfac1 --- /dev/null +++ b/internal/directroad/signal.go @@ -0,0 +1,111 @@ +package directroad + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "io" + + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/pion/webrtc/v4" +) + +// attemptIDBytes is the byte length of the random attempt identifier (8 bytes +// encode to 16 lowercase hexadecimal digits). +const attemptIDBytes = 8 + +// newAttemptID returns 16 lowercase hexadecimal digits from crypto/rand so +// every direct-road attempt carries a fresh identifier on the relay link. +func newAttemptID() (string, error) { + var raw [attemptIDBytes]byte + if _, err := io.ReadFull(rand.Reader, raw[:]); err != nil { + return "", err + } + return hex.EncodeToString(raw[:]), nil +} + +// sendSignal encodes sig with livedoor.EncodeSignal (enforcing +// livedoor.SignalMax) and hands it to the relay Signaller. +func sendSignal(s livedoor.Signaller, sig livedoor.Signal) error { + if s == nil { + return errors.New("directroad: nil signaller") + } + sig.V = livedoor.SignalVersion + payload, err := livedoor.EncodeSignal(sig) + if err != nil { + return err + } + return s.Send(payload) +} + +// sendOffer sends a viewer offer SDP for attempt id. +func sendOffer(s livedoor.Signaller, id, sdp string) error { + return sendSignal(s, livedoor.Signal{ + T: livedoor.SignalOffer, + ID: id, + SDP: sdp, + }) +} + +// sendAnswer sends a host answer SDP for attempt id. +func sendAnswer(s livedoor.Signaller, id, sdp string) error { + return sendSignal(s, livedoor.Signal{ + T: livedoor.SignalAnswer, + ID: id, + SDP: sdp, + }) +} + +// sendCandidate sends one trickled local ICE candidate, or an end-of-candidates +// marker when cand is nil. +func sendCandidate(s livedoor.Signaller, id string, cand *webrtc.ICECandidate) error { + if cand == nil { + return sendSignal(s, livedoor.Signal{ + T: livedoor.SignalCandidate, + ID: id, + End: true, + }) + } + init := cand.ToJSON() + mid := "" + if init.SDPMid != nil { + mid = *init.SDPMid + } + idx := 0 + if init.SDPMLineIndex != nil { + idx = int(*init.SDPMLineIndex) + } + return sendSignal(s, livedoor.Signal{ + T: livedoor.SignalCandidate, + ID: id, + C: init.Candidate, + Mid: mid, + Idx: idx, + }) +} + +// sendEnd best-effort notifies the peer that attempt id has been abandoned. +func sendEnd(s livedoor.Signaller, id string) error { + return sendSignal(s, livedoor.Signal{ + T: livedoor.SignalEnd, + ID: id, + }) +} + +// candidateInitFromSignal converts a received cand signal into pion's +// ICECandidateInit, returning false for an end-of-candidates marker. +func candidateInitFromSignal(sig livedoor.Signal) (webrtc.ICECandidateInit, bool) { + if sig.End || sig.C == "" { + return webrtc.ICECandidateInit{}, false + } + mid := sig.Mid + var idx uint16 + if sig.Idx >= 0 && sig.Idx <= 0xffff { + idx = uint16(sig.Idx) + } + return webrtc.ICECandidateInit{ + Candidate: sig.C, + SDPMid: &mid, + SDPMLineIndex: &idx, + }, true +} diff --git a/internal/directroad/stream.go b/internal/directroad/stream.go new file mode 100644 index 0000000000..f0c9c8086d --- /dev/null +++ b/internal/directroad/stream.go @@ -0,0 +1,174 @@ +package directroad + +import ( + "errors" + "fmt" + "io" + "sync" + "sync/atomic" + "time" +) + +const ( + // maxReadMessageBytes is the 64 KiB receive buffer capacity required by the + // road contract; any single data-channel message larger than this is a + // protocol violation that terminates the stream. + maxReadMessageBytes = 64 << 10 + + // maxWriteMessageBytes caps each outbound data-channel message at 16 KiB so + // large writes are sliced into bounded SCTP messages well under the + // receiver's 64 KiB ceiling. + maxWriteMessageBytes = 16 << 10 +) + +// errMessageTooLarge reports an inbound data-channel message that exceeded +// maxReadMessageBytes; it deliberately does not wrap io.ErrShortBuffer because +// Read on the byte stream must never report a short buffer to callers. +var errMessageTooLarge = fmt.Errorf("directroad: inbound message exceeds %d-byte limit", maxReadMessageBytes) + +// messageConn is the minimal message-oriented read/write/close interface +// satisfied by pion's detached data channel and by test fakes. +type messageConn interface { + Read(p []byte) (int, error) + Write(p []byte) (int, error) + Close() error +} + +// byteStream adapts a message-oriented data channel into a continuous +// io.ReadWriteCloser byte pipe. +type byteStream struct { + raw messageConn + closeFn func() + + readMu sync.Mutex + readBuf [maxReadMessageBytes]byte + readOff int + readEnd int + fatalErr error + + writeMu sync.Mutex + + closed atomic.Bool + closeOnce sync.Once + closeErr error +} + +// newByteStream wraps raw in a byte-stream adapter that invokes closeFn once +// after closing raw. +func newByteStream(raw messageConn, closeFn func()) *byteStream { + return &byteStream{ + raw: raw, + closeFn: closeFn, + } +} + +// Read serves bytes from the unread tail of the current message or pulls the +// next non-empty message into the 64 KiB staging buffer, never exposing +// message boundaries or io.ErrShortBuffer to the caller. +func (s *byteStream) Read(p []byte) (int, error) { + s.readMu.Lock() + defer s.readMu.Unlock() + + if s.closed.Load() { + if s.fatalErr != nil { + return 0, s.fatalErr + } + return 0, io.EOF + } + + if s.readOff < s.readEnd { + n := copy(p, s.readBuf[s.readOff:s.readEnd]) + s.readOff += n + return n, nil + } + + if len(p) == 0 { + return 0, nil + } + + for { + if s.closed.Load() { + if s.fatalErr != nil { + return 0, s.fatalErr + } + return 0, io.EOF + } + + n, err := s.raw.Read(s.readBuf[:]) + if errors.Is(err, io.ErrShortBuffer) { + // A message over 64 KiB violates the road contract; record a plain + // error and close the stream so neither side continues on a torn + // message boundary. + s.fatalErr = errMessageTooLarge + _ = s.Close() + return 0, errMessageTooLarge + } + if err != nil { + if s.closed.Load() && s.fatalErr == nil { + return 0, io.EOF + } + return 0, err + } + if n == 0 { + // Zero-length data-channel messages carry no stream bytes and must + // never surface as an ambiguous (0, nil) read. + continue + } + + copied := copy(p, s.readBuf[:n]) + s.readOff = copied + s.readEnd = n + return copied, nil + } +} + +// Write slices p into messages of at most maxWriteMessageBytes (16 KiB) and +// serialises concurrent writers with a mutex. +func (s *byteStream) Write(p []byte) (int, error) { + if s.closed.Load() { + return 0, io.ErrClosedPipe + } + if len(p) == 0 { + return 0, nil + } + + s.writeMu.Lock() + defer s.writeMu.Unlock() + + total := 0 + for len(p) > 0 { + if s.closed.Load() { + return total, io.ErrClosedPipe + } + chunk := p + if len(chunk) > maxWriteMessageBytes { + chunk = p[:maxWriteMessageBytes] + } + n, err := s.raw.Write(chunk) + total += n + if err != nil { + return total, err + } + p = p[len(chunk):] + } + return total, nil +} + +// Close closes the underlying message channel and then the peer connection +// exactly once, waking any blocked Read or Write immediately. +func (s *byteStream) Close() error { + s.closeOnce.Do(func() { + s.closed.Store(true) + if d, ok := s.raw.(interface{ SetReadDeadline(time.Time) error }); ok { + _ = d.SetReadDeadline(time.Now()) + } + if d, ok := s.raw.(interface{ SetWriteDeadline(time.Time) error }); ok { + _ = d.SetWriteDeadline(time.Now()) + } + s.closeErr = s.raw.Close() + if s.closeFn != nil { + s.closeFn() + } + }) + return s.closeErr +} diff --git a/internal/directroad/stream_test.go b/internal/directroad/stream_test.go new file mode 100644 index 0000000000..633297a991 --- /dev/null +++ b/internal/directroad/stream_test.go @@ -0,0 +1,270 @@ +package directroad + +import ( + "bytes" + "encoding/binary" + "errors" + "io" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/pion/webrtc/v4" +) + +// fakeMessageConn emulates pion's detached data channel: each Read pops one +// whole message and returns io.ErrShortBuffer (discarding the unread remainder +// of that message) if the caller's buffer is smaller than the message. +type fakeMessageConn struct { + mu sync.Mutex + cond *sync.Cond + inbox [][]byte + written [][]byte + closed bool + closeCalls int +} + +func newFakeMessageConn() *fakeMessageConn { + f := &fakeMessageConn{} + f.cond = sync.NewCond(&f.mu) + return f +} + +func (f *fakeMessageConn) enqueue(msg []byte) { + f.mu.Lock() + cp := append([]byte(nil), msg...) + f.inbox = append(f.inbox, cp) + f.cond.Signal() + f.mu.Unlock() +} + +func (f *fakeMessageConn) Read(p []byte) (int, error) { + f.mu.Lock() + defer f.mu.Unlock() + + for len(f.inbox) == 0 && !f.closed { + f.cond.Wait() + } + if len(f.inbox) == 0 { + return 0, io.EOF + } + + msg := f.inbox[0] + f.inbox[0] = nil + f.inbox = f.inbox[1:] + + if len(p) < len(msg) { + n := copy(p, msg) + return n, io.ErrShortBuffer + } + n := copy(p, msg) + return n, nil +} + +func (f *fakeMessageConn) Write(p []byte) (int, error) { + f.mu.Lock() + defer f.mu.Unlock() + + if f.closed { + return 0, io.ErrClosedPipe + } + cp := append([]byte(nil), p...) + f.written = append(f.written, cp) + return len(cp), nil +} + +func (f *fakeMessageConn) Close() error { + f.mu.Lock() + f.closed = true + f.closeCalls++ + f.cond.Broadcast() + f.mu.Unlock() + return nil +} + +// Contract: stream adapter turns a message-oriented detached data channel into +// a byte pipe that slices writes at 16 KiB, stages reads up to 64 KiB, skips +// empty messages, rejects >64 KiB messages as a protocol violation without +// returning io.ErrShortBuffer, and closes idempotently on Close or connection +// state Failed. +func TestAStreamAdapterServesABytePipeFromMessages(t *testing.T) { + // 1. A 100 KiB Write is sliced into <=16 KiB messages whose concatenation + // equals the input, and an empty Write sends nothing. + t.Run("write_slicing_and_one_byte_reads", func(t *testing.T) { + fc := newFakeMessageConn() + var closeFnCalls atomic.Int32 + s := newByteStream(fc, func() { closeFnCalls.Add(1) }) + + if n, err := s.Write(nil); err != nil || n != 0 { + t.Fatalf("empty Write = (%d, %v), want (0, nil)", n, err) + } + if len(fc.written) != 0 { + t.Fatalf("empty Write sent %d messages, want 0", len(fc.written)) + } + + const writeSize = 100 << 10 + input := make([]byte, writeSize) + for i := range input { + input[i] = byte((i*31 + 7) & 0xff) + } + + n, err := s.Write(input) + if err != nil || n != len(input) { + t.Fatalf("Write(100 KiB) = (%d, %v), want (%d, nil)", n, err, len(input)) + } + if len(fc.written) < 2 { + t.Fatalf("expected multiple messages for 100 KiB write, got %d", len(fc.written)) + } + var joined []byte + for i, msg := range fc.written { + if len(msg) == 0 || len(msg) > maxWriteMessageBytes { + t.Fatalf("message %d has length %d, want 1..%d", i, len(msg), maxWriteMessageBytes) + } + joined = append(joined, msg...) + } + if !bytes.Equal(joined, input) { + t.Fatal("concatenated outbound messages do not match 100 KiB input") + } + + // Queue 70,000 bytes across messages (as produced by a sender or up to + // 64 KiB chunks) and read them back one byte at a time in order. + const streamTotal = 70_000 + want := make([]byte, streamTotal) + for i := range want { + want[i] = byte((i*17 + 3) & 0xff) + } + fc.enqueue(want[:maxReadMessageBytes]) + fc.enqueue(want[maxReadMessageBytes:]) + + got := make([]byte, streamTotal) + var one [1]byte + for i := range streamTotal { + rn, rerr := s.Read(one[:]) + if errors.Is(rerr, io.ErrShortBuffer) { + t.Fatalf("byte %d: Read returned io.ErrShortBuffer", i) + } + if rerr != nil || rn != 1 { + t.Fatalf("byte %d: Read = (%d, %v), want (1, nil)", i, rn, rerr) + } + got[i] = one[0] + } + if !bytes.Equal(got, want) { + t.Fatal("70,000 one-byte reads did not match queued bytes in order") + } + }) + + // 2. Noise reader pattern: 2-byte big-endian length prefix followed by the + // body in a single data-channel message, with a zero-length message before + // it that must be skipped transparently. + t.Run("prefix_then_body_and_skip_zero_length", func(t *testing.T) { + fc := newFakeMessageConn() + s := newByteStream(fc, nil) + + body := bytes.Repeat([]byte("noise-record-payload-"), 120) + frame := make([]byte, 2+len(body)) + binary.BigEndian.PutUint16(frame[:2], uint16(len(body))) + copy(frame[2:], body) + + fc.enqueue([]byte{}) + fc.enqueue(frame) + + var hdr [2]byte + if _, err := io.ReadFull(s, hdr[:]); err != nil { + t.Fatalf("io.ReadFull header: %v", err) + } + gotLen := int(binary.BigEndian.Uint16(hdr[:])) + if gotLen != len(body) { + t.Fatalf("header length = %d, want %d", gotLen, len(body)) + } + + gotBody := make([]byte, gotLen) + if _, err := io.ReadFull(s, gotBody); err != nil { + t.Fatalf("io.ReadFull body: %v", err) + } + if !bytes.Equal(gotBody, body) { + t.Fatal("body read after 2-byte prefix does not match") + } + }) + + // 3. A single message over 64 KiB (e.g. 70,000 bytes in one message) causes + // the underlying channel to report io.ErrShortBuffer, which the adapter + // turns into a non-ErrShortBuffer protocol violation error and closes the + // stream idempotently. + t.Run("oversized_message_violation_and_idempotent_close", func(t *testing.T) { + fc := newFakeMessageConn() + var closeFnCalls atomic.Int32 + s := newByteStream(fc, func() { closeFnCalls.Add(1) }) + + fc.enqueue(make([]byte, 70_000)) + + buf := make([]byte, 32) + _, err := s.Read(buf) + if err == nil { + t.Fatal("expected error reading >64 KiB message, got nil") + } + if errors.Is(err, io.ErrShortBuffer) { + t.Fatalf("Read leaked io.ErrShortBuffer on oversized message: %v", err) + } + + // Subsequent Close calls must be idempotent. + if err := s.Close(); err != nil { + t.Fatalf("first explicit Close: %v", err) + } + if err := s.Close(); err != nil { + t.Fatalf("second explicit Close: %v", err) + } + if got := closeFnCalls.Load(); got != 1 { + t.Fatalf("closeFn called %d times, want 1", got) + } + fc.mu.Lock() + rawCloses := fc.closeCalls + fc.mu.Unlock() + if rawCloses != 1 { + t.Fatalf("raw.Close called %d times, want 1", rawCloses) + } + }) + + // 4. A PeerConnectionStateFailed callback closes the stream and wakes a + // blocked Read immediately. + t.Run("failed_state_callback_wakes_blocked_read", func(t *testing.T) { + fc := newFakeMessageConn() + var closeFnCalls atomic.Int32 + st := newByteStream(fc, func() { closeFnCalls.Add(1) }) + + sess := &pcSession{ + openCh: make(chan io.ReadWriteCloser, 1), + errCh: make(chan error, 1), + stream: st, + } + + readErrCh := make(chan error, 1) + go func() { + var b [16]byte + _, err := st.Read(b[:]) + readErrCh <- err + }() + + // Disconnected must NOT close the stream because ICE can recover. + sess.onConnectionState(webrtc.PeerConnectionStateDisconnected) + select { + case err := <-readErrCh: + t.Fatalf("Disconnected state should not close stream, got Read err: %v", err) + default: + } + + // Failed MUST close the stream and wake the blocked Read. + sess.onConnectionState(webrtc.PeerConnectionStateFailed) + select { + case err := <-readErrCh: + if err == nil { + t.Fatal("expected blocked Read to return an error on Failed state, got nil") + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for Failed state callback to wake blocked Read") + } + if got := closeFnCalls.Load(); got != 1 { + t.Fatalf("closeFn called %d times after Failed state, want 1", got) + } + }) +} diff --git a/internal/directroad/stun_test.go b/internal/directroad/stun_test.go new file mode 100644 index 0000000000..a822e672e0 --- /dev/null +++ b/internal/directroad/stun_test.go @@ -0,0 +1,177 @@ +package directroad + +import ( + "context" + "io" + "net" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/pion/stun/v4" + "github.com/pion/transport/v5/vnet" +) + +// fakeSTUNServer listens on a vnet Net at :3478, counts incoming STUN Binding +// requests, and replies with the sender's address in XOR-MAPPED-ADDRESS. +type fakeSTUNServer struct { + conn net.PacketConn + requests atomic.Int64 + done chan struct{} +} + +func startFakeSTUNServer(t *testing.T, nw *vnet.Net) *fakeSTUNServer { + t.Helper() + conn, err := nw.ListenPacket("udp4", testSTUNIP+":3478") + if err != nil { + t.Fatalf("stun ListenPacket: %v", err) + } + srv := &fakeSTUNServer{ + conn: conn, + done: make(chan struct{}), + } + go srv.serve() + t.Cleanup(func() { + _ = conn.Close() + <-srv.done + }) + return srv +} + +func (s *fakeSTUNServer) serve() { + defer close(s.done) + buf := make([]byte, 1500) + for { + n, addr, err := s.conn.ReadFrom(buf) + if err != nil { + return + } + var req stun.Message + if err := stun.Decode(buf[:n], &req); err != nil { + continue + } + if req.Type != stun.BindingRequest { + continue + } + s.requests.Add(1) + + udpAddr, ok := addr.(*net.UDPAddr) + if !ok { + continue + } + resp, err := stun.Build(&req, stun.BindingSuccess, &stun.XORMappedAddress{ + IP: udpAddr.IP, + Port: udpAddr.Port, + }) + if err != nil { + continue + } + _, _ = s.conn.WriteTo(resp.Raw, addr) + } +} + +// Contract V36: when Config.STUN is empty, zero STUN packets are sent across a +// full connect; when Config.STUN is configured on the same rig, the fake STUN +// server receives Binding requests. +// +// The "road is relay" half of V36 lives one layer up: a relay-only computer +// never constructs this package's objects (internal/syncsetup pins that). +func TestNoSTUNRequestIsMadeWhenTheRoadIsRelayOrStunIsOff(t *testing.T) { + // Part A: with Config.STUN empty, a full connect and byte transfer sends + // zero packets to the STUN server address. + t.Run("stun_empty_sends_zero_stun_packets", func(t *testing.T) { + rig := newVNetRig(t) + stunSrv := startFakeSTUNServer(t, rig.stunNet) + + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + defer cancel() + + host := New(rig.hostConfig()) + defer host.Close() + + hostStreamCh := make(chan io.ReadWriteCloser, 1) + acceptDone := make(chan struct{}) + defer close(acceptDone) + + host.SetAcceptor(ctx, func(_ context.Context, stream io.ReadWriteCloser) { + hostStreamCh <- stream + <-acceptDone + }) + + bridge := newSignalBridge(ctx, host, livedoor.Peer{Device: "device-no-stun"}) + viewerStream, err := Offer(ctx, rig.viewerConfig(), bridge.viewerSignaller(), bridge.deliver()) + if err != nil { + t.Fatalf("Offer with STUN off failed: %v", err) + } + defer func() { _ = viewerStream.Close() }() + + var hostStream io.ReadWriteCloser + select { + case hostStream = <-hostStreamCh: + case <-ctx.Done(): + t.Fatal("timed out waiting for host stream") + } + + if _, err := viewerStream.Write([]byte("ping")); err != nil { + t.Fatalf("viewer Write: %v", err) + } + var echo [4]byte + if _, err := io.ReadFull(hostStream, echo[:]); err != nil { + t.Fatalf("host ReadFull: %v", err) + } + + if got := stunSrv.requests.Load(); got != 0 { + t.Fatalf("fake STUN server received %d Binding requests with STUN empty, want 0", got) + } + if got := rig.chunksTo(testSTUNIP); got != 0 { + t.Fatalf("vnet router routed %d chunks to STUN IP %s with STUN empty, want 0", got, testSTUNIP) + } + }) + + // Part B: with a STUN URL configured on the same rig, the gatherer DOES + // send Binding requests to the fake STUN server (while ignoring any non-stun + // turn: entry), proving the rig detects STUN traffic. + t.Run("stun_configured_reaches_fake_server", func(t *testing.T) { + rig := newVNetRig(t) + stunSrv := startFakeSTUNServer(t, rig.stunNet) + + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + defer cancel() + + stunURL := "stun:" + testSTUNIP + ":3478" + vCfg := rig.viewerConfig() + vCfg.STUN = []string{stunURL, "turn:" + testSTUNIP + ":3478"} + hCfg := rig.hostConfig() + hCfg.STUN = []string{stunURL} + + host := New(hCfg) + defer host.Close() + + hostStreamCh := make(chan io.ReadWriteCloser, 1) + acceptDone := make(chan struct{}) + defer close(acceptDone) + + host.SetAcceptor(ctx, func(_ context.Context, stream io.ReadWriteCloser) { + hostStreamCh <- stream + <-acceptDone + }) + + bridge := newSignalBridge(ctx, host, livedoor.Peer{Device: "device-with-stun"}) + viewerStream, err := Offer(ctx, vCfg, bridge.viewerSignaller(), bridge.deliver()) + if err != nil { + t.Fatalf("Offer with STUN configured failed: %v", err) + } + defer func() { _ = viewerStream.Close() }() + + select { + case <-hostStreamCh: + case <-ctx.Done(): + t.Fatal("timed out waiting for host stream with STUN configured") + } + + eventually(t, 2*time.Second, "fake STUN server to receive Binding request", func() bool { + return stunSrv.requests.Load() > 0 && rig.chunksTo(testSTUNIP) > 0 + }) + }) +} diff --git a/internal/e2e/displaced_continuation_e2e_test.go b/internal/e2e/displaced_continuation_e2e_test.go index bd04c5eef7..c3b8ce825f 100644 --- a/internal/e2e/displaced_continuation_e2e_test.go +++ b/internal/e2e/displaced_continuation_e2e_test.go @@ -155,7 +155,7 @@ func TestDisplacedWindowsContinueWithoutBranchesOrLostDrafts(t *testing.T) { if !selected { t.Fatalf("Home did not list the used chat:\n%s", b.capture()) } - if screen := b.waitFor(10*time.Second, "Continue this chat here?"); !strings.Contains(screen, "Continue this chat here?") { + if screen := b.waitFor(10*time.Second, say(t, "moveAsk")); !strings.Contains(screen, say(t, "moveAsk")) { t.FailNow() } b.keys("1", "Enter") @@ -173,7 +173,7 @@ func TestDisplacedWindowsContinueWithoutBranchesOrLostDrafts(t *testing.T) { turn.window.lit(turn.draft) before := requests.Load() turn.window.keys("Enter") - turn.window.waitFor(10*time.Second, "Continue this chat here?") + turn.window.waitFor(10*time.Second, say(t, "moveAsk")) turn.window.keys("1", "Enter") screen := turn.window.waitFor(35*time.Second, "Moved from "+turn.from) if strings.Contains(screen, "were kept as") { diff --git a/internal/e2e/pairjourney_e2e_test.go b/internal/e2e/pairjourney_e2e_test.go index 2bdf9aa1c5..ad9633cc26 100644 --- a/internal/e2e/pairjourney_e2e_test.go +++ b/internal/e2e/pairjourney_e2e_test.go @@ -151,7 +151,7 @@ func startRelayAt(t *testing.T, store string) string { build := exec.Command("go", "build", "-o", bin, "./cmd/relay") build.Dir = repoRoot(t) if out, err := build.CombinedOutput(); err != nil { - t.Fatalf("build the sync service: %v\n%s", err, out) + t.Fatalf("build the relay: %v\n%s", err, out) } ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { @@ -170,7 +170,7 @@ func startRelayAt(t *testing.T, store string) string { return "http://" + addr } } - t.Fatal("the sync service never listened") + t.Fatal("the relay never listened") return "" } diff --git a/internal/e2e/pairjourney_steps_e2e_test.go b/internal/e2e/pairjourney_steps_e2e_test.go index a763fe1664..4fd8b33906 100644 --- a/internal/e2e/pairjourney_steps_e2e_test.go +++ b/internal/e2e/pairjourney_steps_e2e_test.go @@ -161,7 +161,7 @@ func journeyRun(j *journey, env []string, homeA, homeB, wsA, wsB string, online a.lit("/home") a.keys("Enter") a.keys("M-m") - _, ok := waitPlain(a, 8*time.Second, "Continue this chat here?") + _, ok := waitPlain(a, 8*time.Second, say(t, "moveAsk")) j.require(ok, "alt+m offered no continuation for the online holder") j.see(a) return @@ -187,17 +187,17 @@ func journeyRun(j *journey, env []string, homeA, homeB, wsA, wsB string, online }) moved := false - j.step("6a A: Continue here on B's chat", false, func() { + j.step("6a A: Move here on B's chat", false, func() { if !online { a.keys("M-c") } else { - screen, ok := waitPlain(a, 8*time.Second, "Continue this chat here?") + screen, ok := waitPlain(a, 8*time.Second, say(t, "moveAsk")) if !j.require(ok, "no takeover question for B's running chat") { j.see(a) return } j.see(a) - j.check(strings.Contains(screen, "continue here"), "the question does not offer 'continue here'") + j.check(strings.Contains(screen, "move here"), "the question does not offer 'move here'") a.keys("1") a.keys("Enter") } @@ -208,7 +208,7 @@ func journeyRun(j *journey, env []string, homeA, homeB, wsA, wsB string, online return } if !online { - j.check(!strings.Contains(after, "Continue this chat here?"), "one-key arrival from an asleep computer asked for another key") + j.check(!strings.Contains(after, say(t, "moveAsk")), "one-key arrival from an asleep computer asked for another key") } j.check(regexp.MustCompile(`Moved from \S+ in [0-9.]+m?s`).MatchString(after), "the banner does not say how long the move took") j.see(a) diff --git a/internal/e2e/quiet_e2e_test.go b/internal/e2e/quiet_e2e_test.go index a7e8fb6b5d..1a73dba8e5 100644 --- a/internal/e2e/quiet_e2e_test.go +++ b/internal/e2e/quiet_e2e_test.go @@ -63,7 +63,7 @@ func TestFreshInstallSendsNothingToTheSyncService(t *testing.T) { } time.Sleep(5 * time.Second) if got := count.seen(); len(got) != 0 { - t.Fatalf("a fresh install reached the sync service %d times: %s", len(got), strings.Join(got, "; ")) + t.Fatalf("a fresh install reached the relay %d times: %s", len(got), strings.Join(got, "; ")) } app.kill() @@ -75,7 +75,7 @@ func TestFreshInstallSendsNothingToTheSyncService(t *testing.T) { t.Fatalf("the card is gone on the second launch:\n%s", plain(app)) } if got := count.seen(); len(got) != 0 { - t.Fatalf("a second quiet launch reached the sync service: %s", strings.Join(got, "; ")) + t.Fatalf("a second quiet launch reached the relay: %s", strings.Join(got, "; ")) } app.keys("M-d") deadline := time.Now().Add(15 * time.Second) @@ -83,6 +83,6 @@ func TestFreshInstallSendsNothingToTheSyncService(t *testing.T) { time.Sleep(500 * time.Millisecond) } if len(count.seen()) == 0 { - t.Fatal("opening the add-machine card never reached the sync service") + t.Fatal("opening the add-machine card never reached the relay") } } diff --git a/internal/e2e/quit_continuation_e2e_test.go b/internal/e2e/quit_continuation_e2e_test.go index 4471c34240..693485d5b2 100644 --- a/internal/e2e/quit_continuation_e2e_test.go +++ b/internal/e2e/quit_continuation_e2e_test.go @@ -189,7 +189,7 @@ func TestQuitContinuationFirstSend(t *testing.T) { deadline := time.Now().Add(35 * time.Second) for { screen := b.capture() - if strings.Contains(screen, "Continue this chat here?") { + if strings.Contains(screen, say(t, "moveAsk")) { t.Fatalf("first send raised the continuation card:\n%s", screen) } if strings.Contains(screen, "This copy is read-only and may be behind") { diff --git a/internal/e2e/remote_control_e2e_test.go b/internal/e2e/remote_control_e2e_test.go new file mode 100644 index 0000000000..0763dc9378 --- /dev/null +++ b/internal/e2e/remote_control_e2e_test.go @@ -0,0 +1,1627 @@ +//go:build e2e + +package e2e + +// remote_control_e2e_test.go is THE KEYLESS PROOF OF REMOTE CONTROL, DRIVEN AS A +// PERSON WOULD DRIVE IT: the real binary in real terminals, two or three paired +// computers on one machine, a relay in the middle, and a model that is a script. +// +// A chat another of the person's computers is running opens LIVE: the other +// computer keeps running it, the person watches it happen, types into it, and +// can carry it to this computer with Move here. Every scenario below is one line +// of that promise, named for the contract it checks (the V ids are the lines of +// the validation contract in the remote control design). +// +// IT NEEDS NO PROVIDER KEY AND NO NETWORK. The model is an httptest server that +// answers by what the typed words say: a prompt with `slow` in it is held open +// until the test releases a gate, so a turn is RUNNING while a viewer attaches; +// any other prompt answers at once, with `host reply` or `laptop reply` according +// to the computer the words were typed on. The relay is the product's own, behind +// a proxy that writes down every request, refuses every store write with the +// answer the hosted service gives when storage is off, and fails the scenario if +// one was ever tried. Sync storage is off on every home, so what these scenarios +// prove is the live road alone: nothing a viewer does here may need an upload. +// +// NO WINDOW OF THIS SUITE EVER ASKS A STUN SERVER. Every home runs with +// CODEAF_REMOTE_STUN=off, so the direct road is offered with host candidates only: +// two computers of one machine connect over the machine's own network address, and +// a machine with no such address skips the scenarios that need the road and says +// why. The road is automatic, so the phase 1 scenarios below run over whichever +// road the view is on when they look, which is the promise a person is given. +// +// IT SKIPS RATHER THAN FAILS without tmux or bin/codeaf, like every scenario in +// this package, and it is meant to be run ONE SUBTEST AT A TIME: +// +// go test -tags e2e -count=1 -run 'TestRemoteControlE2E/' -v ./internal/e2e/ +// +// Every subtest builds its own homes, relay, proxy and model, so none depends on +// another having run. The first start of each window is slow; the waits say how +// long the contract allows and add only the margin a real clock needs. + +import ( + "bufio" + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "net/http/httputil" + "net/url" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "sync" + "sync/atomic" + "syscall" + "testing" + "time" + + "github.com/charmbracelet/x/ansi" + + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/devname" + "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/relay" + "github.com/Agent-Field/codeaf/internal/syncsetup" +) + +// The names the scenarios give their computers. A device name is what a person +// reads on Home and in every banner, so these are the words the needles meet. +const ( + rcHostName = "desktop" + rcViewerName = "laptop" + rcSecondName = "tablet" +) + +// The words the scripted model answers with. They are distinct from anything the +// product writes itself, so a token on a screen is the model's and nobody else's. +const ( + rcHostReply = "host reply" + rcLaptopReply = "laptop reply" + // rcPrimeReply answers the first turn of a chat that goes on to hold a slow + // one. It is not rcHostReply, because the scenarios that hold a turn look for + // that word to tell whether the held turn has ended. + rcPrimeReply = "host primed" + // rcPartial is what a held turn has already said when a viewer attaches. + rcPartial = "host partial" + // rcMark is in every prompt the scenarios type, and it is how the model tells + // a chat turn of the scenario from a title or a summary the product asks for. + rcMark = "rc-" +) + +// The prompts the scenarios type. `slow` holds the turn at the model; `laptop` +// makes the reply the laptop's. Nothing else in them is read. +const ( + rcSlowAsk = "rc-host slow question" + rcHostAsk = "rc-host quick question" + rcPrimeAsk = "rc-host prime question" + rcLaptopAsk = "rc-laptop typed on the viewer" +) + +// How long the contract lets each thing take, with a real clock's margin on the +// ones the contract bounds. +const ( + // rcRowWithin is how long Home may take to list a chat another computer runs. + rcRowWithin = 60 * time.Second + // rcOpenWithin is how long a view may take to open after enter. + rcOpenWithin = 25 * time.Second + // rcReplyWithin is how long a scripted reply may take to reach a screen. + rcReplyWithin = 40 * time.Second + // rcOfflineWithin is the contract's ten seconds for a view to say the host + // went offline, plus two for the poll and the process kill. + rcOfflineWithin = 12 * time.Second + // rcPermitWithin is how long a change to what a computer may do may take to + // reach a view that is already open. + rcPermitWithin = 12 * time.Second + // rcDirectWithin is how long a view that has painted may take to say it is on + // the direct road: the half second the first attempt waits so the paint never + // does, an ICE exchange between two processes of one machine, and the polls. + rcDirectWithin = 45 * time.Second + // rcRelayStaysWithin is how long a view that must stay on the relay is watched + // for the direct road coming up anyway. A direct attempt between two processes + // of this machine ends in a couple of seconds, so a road that was going to + // come up has long since. + rcRelayStaysWithin = 15 * time.Second +) + +// The most and the least a typed turn may cost the relay's live tunnel, in bytes +// of the viewer's own carrier. On a direct view the tunnel is a silent standby +// and the turn travels the direct road, so what it costs there is what the +// carrier says on its own (a keepalive at most); on a view held to the relay the +// same turn is the whole of the traffic. They are measured, and are far enough +// apart that neither is a close call. +const ( + rcDirectRelayAtMost = 2048 + rcRelayCarriesAtLeast = 1024 +) + +// ── the whole test ─────────────────────────────────────────────────────────── + +// TestRemoteControlE2E proves, through the shipped terminal, that a chat another +// computer runs can be opened, worked in and moved from here, with sync storage +// off. Each subtest is one contract line and runs alone. +func TestRemoteControlE2E(t *testing.T) { + rcRequire(t) + for _, sub := range []struct { + name string + run func(*testing.T) + }{ + {"opens_live_and_shows_the_running_turn", rcOpensLiveAndShowsTheRunningTurn}, + {"typing_reaches_the_host_and_both_screens_agree", rcTypingReachesTheHost}, + {"two_viewers_one_keyboard", rcTwoViewersOneKeyboard}, + {"watch_only_cannot_type", rcWatchOnlyCannotType}, + {"host_goes_away_and_comes_back", rcHostGoesAwayAndComesBack}, + {"offline_copy_when_nobody_holds_it", rcOfflineCopyWhenNobodyHoldsIt}, + {"move_here_from_the_live_view", rcMoveHereFromTheLiveView}, + {"removing_a_device_closes_its_view", rcRemovingADeviceClosesItsView}, + {"removing_a_device_closes_its_direct_view", rcRemovingADeviceClosesItsDirectView}, + {"pairing_default_is_drive_on", rcPairingDefaultIsDriveOn}, + {"old_flags_still_work", rcOldFlagsStillWork}, + {"direct-road-comes-up", rcDirectRoadComesUp}, + {"relay-only-stays-on-relay", rcRelayOnlyStaysOnTheRelay}, + } { + t.Run(sub.name, sub.run) + } +} + +// rcRequire skips the scenario unless it can be run honestly: tmux to drive the +// terminal and the built binary to drive. It asks for no key, because the model +// is a script. +func rcRequire(t *testing.T) { + t.Helper() + if _, err := exec.LookPath("tmux"); err != nil { + t.Skip("no tmux on PATH: this suite drives the real binary in a real terminal") + } + binary(t) +} + +// rcRequireDirectRoad skips a scenario that needs the direct road on a machine +// that cannot make one: the road is offered with the machine's own network +// addresses and never with the loopback one, so a machine with no other IPv4 +// address has nothing two homes could connect over. +func rcRequireDirectRoad(t *testing.T) { + t.Helper() + rcRequire(t) + addrs, err := net.InterfaceAddrs() + if err != nil { + t.Skipf("this machine's network addresses cannot be read (%v): the direct road has nothing to connect over", err) + } + for _, addr := range addrs { + if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil { + return + } + } + t.Skip("this machine has no non-loopback IPv4 address: the direct road is never offered over loopback, so two homes here have nothing to connect over") +} + +// ── the scenarios ──────────────────────────────────────────────────────────── + +// rcOpensLiveAndShowsTheRunningTurn is V1, V2 and V5 (and the class header of +// V21): a turn is running on the host when the viewer opens its chat, the viewer +// sees the words as they are said before the turn ends, and nothing moved. +func rcOpensLiveAndShowsTheRunningTurn(t *testing.T) { + rc := newRCRig(t, rcOptions{viewers: 1}) + host := rc.startHost() + rc.primeHost(host) + host.lit(rcSlowAsk) + host.keys("Enter") + host.waitFor(30*time.Second, rcPartial) + rc.abortIfFailed() + + viewer := rc.startViewer(0) + screen := rc.openLive(viewer) + if strings.Contains(screen, say(t, "moveAsk")) { + t.Errorf("enter on a chat another computer is running asked to move it instead of opening it live:\n%s", screen) + } + // V2: the turn is still held at the model, so what is on the viewer's screen + // is a reply that has not ended. + viewer.waitFor(rcOpenWithin, rcPartial) + if strings.Contains(viewer.capture(), rcHostReply) { + t.Errorf("the viewer shows the end of a turn the model is still holding:\n%s", viewer.capture()) + } + rc.abortIfFailed() + + rc.model.open() + viewer.waitFor(rcReplyWithin, rcHostReply) + host.waitFor(rcReplyWithin, rcHostReply, "idle") + // V1: nothing moved. The host's window is still the chat's own, and Home on + // the viewer still says the chat is on the host. + if strings.Contains(host.capture(), "may be behind") { + t.Errorf("opening the chat live turned the host's own window into a stale copy:\n%s", host.capture()) + } + rc.goHome(viewer) + rc.waitForRow(viewer, rcHeldRowWords()...) + rc.assertLiveDial() +} + +// rcTypingReachesTheHost is V3 (and V23 by observation): a line typed on the +// viewer runs on the host, the reply shows on both screens, and neither shows the +// line twice nor does the model get asked twice. +func rcTypingReachesTheHost(t *testing.T) { + rc := newRCRig(t, rcOptions{viewers: 1}) + host := rc.startHost() + rc.hostAsk(host, rcHostAsk, rcHostReply) + viewer := rc.startViewer(0) + rc.openLive(viewer) + // The host typed last, so the viewer is not the one typing yet. Once it is, its + // empty box says where the words will go. + rc.takeKeyboard(viewer) + viewer.waitFor(rcOpenWithin, say(t, "liveMessageHint")+rcHostName) + rc.abortIfFailed() + + rc.send(viewer, rcLaptopAsk) + viewer.waitFor(rcReplyWithin, rcLaptopReply) + host.waitFor(rcReplyWithin, rcLaptopReply) + rc.abortIfFailed() + for name, window := range map[string]*rig{"host": host, "viewer": viewer} { + if n := rcLinesWith(window.capture(), rcLaptopAsk); n != 1 { + t.Errorf("the %s shows the typed line on %d lines, want exactly one:\n%s", name, n, window.capture()) + } + } + if n := rc.model.count(rcLaptopAsk); n != 1 { + t.Errorf("the model was asked the typed line %d times, want once", n) + } + // The line ran where the chat lives and nowhere else: the viewer holds no copy + // of the conversation, only its own last-seen view. + if rcTranscriptsWith(t, rc.host.home, rcLaptopAsk) == 0 { + t.Errorf("the host's own transcript never recorded the line the viewer typed") + } + if n := rcTranscriptsWith(t, rc.viewers[0].home, rcLaptopAsk); n != 0 { + t.Errorf("the viewer wrote %d transcripts holding the line it typed into somebody else's chat", n) + } + rc.assertLiveDial() +} + +// rcTwoViewersOneKeyboard is V6: with two computers on one chat one holds the +// keyboard, the other says who, and pressing enter there takes it. +func rcTwoViewersOneKeyboard(t *testing.T) { + rc := newRCRig(t, rcOptions{viewers: 2}) + host := rc.startHost() + rc.hostAsk(host, rcHostAsk, rcHostReply) + first := rc.startViewer(0) + rc.openLive(first) + // The first viewer takes the keyboard by typing a line through. + rc.send(first, rcLaptopAsk) + first.waitFor(rcReplyWithin, rcLaptopReply) + + second := rc.startViewer(1) + rc.openLive(second) + screen := second.waitFor(rcOpenWithin, say(t, "liveWatching"), rcViewerName) + if !strings.Contains(screen, say(t, "liveWatching")) { + t.FailNow() + } + // Enter is the documented way to take it, and the one that held it is told. + second.keys("Enter") + first.waitFor(rcOpenWithin, say(t, "liveWatching"), rcSecondName) + const typed = "rc-laptop typed on the second viewer" + rc.send(second, typed) + // The first line's reply is already on both screens, so the second one is read + // as a second reply. + for name, window := range map[string]*rig{"first viewer": first, "second viewer": second} { + if !waitUntil(rcReplyWithin, func() bool { return strings.Count(window.capture(), rcLaptopReply) >= 2 }) { + t.Errorf("the %s never showed the reply to the line typed on the other viewer:\n%s", name, window.capture()) + } + } + if n := rc.model.count(typed); n != 1 { + t.Errorf("the model was asked the second viewer's line %d times, want once", n) + } + rc.assertLiveDial() +} + +// rcWatchOnlyCannotType is V11: the host takes a computer's typing away while its +// view is open, and within seconds the view says why it cannot type and sends +// nothing. The view draws no box while it says so, so what the scenario can read +// is the sentence and the model's silence. +func rcWatchOnlyCannotType(t *testing.T) { + rc := newRCRig(t, rcOptions{viewers: 1}) + host := rc.startHost() + rc.hostAsk(host, rcHostAsk, rcHostReply) + viewer := rc.startViewer(0) + rc.openLive(viewer) + // While typing is allowed it works, which is what makes the refusal below a + // change and not a fixture that never could. + rc.send(viewer, rcLaptopAsk) + viewer.waitFor(rcReplyWithin, rcLaptopReply) + rc.abortIfFailed() + + rc.hostCLI("devices", "permit", rcViewerName, "--drive", "off") + screen := viewer.waitFor(rcPermitWithin, say(t, "liveWatchOnly")) + if !strings.Contains(screen, say(t, "liveWatchOnly")) { + t.FailNow() + } + const nope = "rc-laptop words that must not be sent" + viewer.lit(nope) + viewer.keys("Enter") + time.Sleep(3 * time.Second) + if n := rc.model.count(nope); n != 0 { + t.Errorf("a computer that may only watch got its typing to the model %d times", n) + } + if after := viewer.capture(); !strings.Contains(after, say(t, "liveWatchOnly")) { + t.Errorf("the view stopped saying why it cannot type once somebody tried:\n%s", after) + } + if strings.Contains(host.capture(), nope) { + t.Errorf("the host shows words a watch-only computer typed:\n%s", host.capture()) + } + rc.assertLiveDial() +} + +// rcHostGoesAwayAndComesBack is V7a and V29: the host dies in the middle of a +// turn, the viewer says so within the bound and keeps both the last view and the +// words in its box, and when the host returns the view resumes with the chat +// shown once. +func rcHostGoesAwayAndComesBack(t *testing.T) { + rc := newRCRig(t, rcOptions{viewers: 1}) + host := rc.startHost() + rc.primeHost(host) + host.lit(rcSlowAsk) + host.keys("Enter") + host.waitFor(30*time.Second, rcPartial) + viewer := rc.startViewer(0) + rc.openLive(viewer) + viewer.waitFor(rcOpenWithin, rcPartial) + // The host has the keyboard, and a box that is not on the frame takes no + // characters, so the viewer takes it before it types the words it will keep. + rc.takeKeyboard(viewer) + const draft = "rc-laptop draft kept across the drop" + viewer.lit(draft) + rc.abortIfFailed() + + host.loseLid() + screen := viewer.waitFor(rcOfflineWithin, say(t, "liveWentOffline")) + if !strings.Contains(screen, rcPartial) { + t.Errorf("the view lost what it showed when the host went away:\n%s", screen) + } + rc.abortIfFailed() + + // The host comes back the way a person brings it back, by starting codeaf in + // the same folder, and the gate is open so a turn it takes up again ends. + rc.model.open() + rc.startHost() + if !waitUntil(90*time.Second, func() bool { + s := viewer.capture() + return strings.Contains(s, say(t, "liveLegend")) && !strings.Contains(s, say(t, "liveWentOffline")) + }) { + t.Fatalf("the view never resumed after the host came back:\n%s", viewer.capture()) + } + after := viewer.capture() + if n := rcLinesWith(after, rcSlowAsk); n != 1 { + t.Errorf("after the resume the question is on %d lines, want one:\n%s", n, after) + } + // The box is the viewer's again once it has the keyboard, and the words it held + // through the drop are in it. + rc.takeKeyboardAfterAReturn(viewer) + if after = viewer.capture(); !strings.Contains(after, draft) { + t.Errorf("the words in the box did not survive the resume:\n%s", after) + } + // The resumed view is a working one, and the line sent from it is asked once. + viewer.keys("Enter") + viewer.waitFor(rcReplyWithin, rcLaptopReply) + if n := rc.model.count(draft); n != 1 { + t.Errorf("the draft was asked of the model %d times, want once", n) + } + rc.assertLiveDial() +} + +// rcOfflineCopyWhenNobodyHoldsIt is V27: with the host gone for good and storage +// off, the viewer opens the same chat from its own last-seen copy, read-only with +// a dated banner, and what it types goes nowhere. +func rcOfflineCopyWhenNobodyHoldsIt(t *testing.T) { + rc := newRCRig(t, rcOptions{viewers: 1}) + host := rc.startHost() + rc.hostAsk(host, rcHostAsk, rcHostReply) + viewer := rc.startViewer(0) + rc.openLive(viewer) + // The copy is made from what the view showed, so the viewer waits until it + // has shown the reply and a moment longer for the copy to reach its disk. + viewer.waitFor(rcOpenWithin, rcHostReply) + time.Sleep(3 * time.Second) + rc.goHome(viewer) + + host.loseLid() + rc.waitForRow(viewer, rcHostName+" offline") + rc.openRow(viewer, rcHostName+" offline") + screen := viewer.waitFor(rcOpenWithin, "last seen", rcHostReply) + if !rcSeenAt.MatchString(screen) { + t.Errorf("the banner of a copy does not carry the time it was last seen:\n%s", screen) + } + rc.abortIfFailed() + + // Whatever is typed into a copy goes nowhere: the host is not there to take it, + // and no computer starts a chat on another's behalf. + const words = "rc-laptop words typed into a copy" + viewer.lit(words) + viewer.keys("Enter") + time.Sleep(3 * time.Second) + after := viewer.capture() + if strings.Contains(after, rcLaptopReply) || rc.model.count(words) != 0 { + t.Errorf("a read-only copy of a chat nobody runs sent what was typed into it:\n%s", after) + } + if !strings.Contains(after, "last seen") { + t.Errorf("the copy stopped saying it is a copy once somebody tried to type into it:\n%s", after) + } +} + +// rcMoveHereFromTheLiveView is V8 and V9: alt+m in a live view asks, a move that +// cannot reach the host leaves the viewer in the live view with nothing lost, and +// a move that can shows Moving here and then runs the chat on the viewer. +func rcMoveHereFromTheLiveView(t *testing.T) { + rc := newRCRig(t, rcOptions{viewers: 1}) + host := rc.startHost() + rc.hostAsk(host, rcHostAsk, rcHostReply) + viewer := rc.startViewer(0) + rc.openLive(viewer) + + // V9, first: the relay refuses to hand the chat over, so the move cannot finish. + // (A move is the relay's decision, not the host's: a frozen host does not stop + // one, which is why the failure is injected where the move is decided.) The card + // is answered while the relay refuses, and the viewer must end up back in the + // live view of the host with nothing lost. + rc.audit.refuseAcquire.Store(true) + viewer.keys("M-m") + viewer.waitFor(rcOpenWithin, say(t, "moveAsk")) + rc.abortIfFailed() + viewer.keys("1", "Enter") + // The move starts before it fails, so the viewer is first given a moment to + // say it is on its way; only then is "back in the live view" a change. + waitUntilFast(10*time.Second, func() bool { return strings.Contains(viewer.capture(), say(t, "movingHere")) }) + if !waitUntil(100*time.Second, func() bool { + s := viewer.capture() + return !strings.Contains(s, say(t, "movingHere")) && !strings.Contains(s, say(t, "moveAsk")) && + strings.Contains(s, say(t, "moveFailed")) && strings.Contains(s, say(t, "liveLegend")) + }) { + t.Fatalf("a move the relay refused did not put the viewer back in the live view:\n%s", viewer.capture()) + } + if strings.Contains(viewer.capture(), "Moved from") { + t.Errorf("a move the relay refused claims the chat arrived:\n%s", viewer.capture()) + } + rc.audit.refuseAcquire.Store(false) + rc.abortIfFailed() + + // V8: the same move with the host answering. The sentence is short-lived, so + // the screen is read quickly from the answer on, and the arrival is what the + // scenario insists on. + // + // A move on one machine is over in a fraction of a second, which is shorter + // than a screen poll, so the relay is told to take two seconds over the + // decision: the sentence is then true for two seconds, and the scenario + // can insist on it being there while the chat is on its way without racing + // the clock. + rc.audit.slowAcquire.Store(2000) + viewer.keys("M-m") + viewer.waitFor(rcOpenWithin, say(t, "moveAsk")) + viewer.keys("1", "Enter") + sawMoving := false + if !waitUntilFast(rcReplyWithin+30*time.Second, func() bool { + s := viewer.capture() + sawMoving = sawMoving || strings.Contains(s, say(t, "movingHere")) + return strings.Contains(s, "Moved from "+rcHostName) + }) { + t.Fatalf("the chat never arrived on the viewer (moving seen: %v):\n%s", sawMoving, viewer.capture()) + } + rc.audit.slowAcquire.Store(0) + if !sawMoving { + t.Errorf("the viewer never said %q while the chat was on its way", say(t, "movingHere")) + } + // The chat runs on the viewer now: a turn typed here is answered by the + // viewer's own engine, in the viewer's own window. What the stub model + // answers is not the point (it picks its words from the newest typed message + // it was handed), so a second reply line under the typed words is the proof, + // and the request the model saw is logged for the day that proof is missing. + rc.send(viewer, rcLaptopAsk) + if !waitUntil(rcReplyWithin, func() bool { + s := viewer.capture() + return rcLinesWith(s, rcLaptopAsk) == 1 && rcLinesWith(s, rcHostReply)+rcLinesWith(s, rcLaptopReply) >= 2 + }) { + t.Fatalf("a chat moved here did not answer the turn typed on the viewer. The model was handed: %s\n%s", + rc.model.lastRequest(), viewer.capture()) + } + t.Logf("after the move the model was handed: %s", rc.model.lastRequest()) + if strings.Contains(viewer.capture(), say(t, "liveLegend")) { + t.Errorf("the chat runs on the viewer now, and its window still calls itself a live view:\n%s", viewer.capture()) + } + // The host's own window of the chat becomes a live view of the new holder. + host.waitFor(rcReplyWithin, say(t, "liveLegend")) +} + +// rcRemovingADeviceClosesItsView is V10: taking a computer off the person's list +// on the host closes that computer's open view within the bound, and Home there +// stops listing the host's chats. +func rcRemovingADeviceClosesItsView(t *testing.T) { + rcRemoveTheViewerWhileItWatches(t, rcOptions{viewers: 1}, "") +} + +// rcRemovingADeviceClosesItsDirectView is V10 for a view on the direct road: the +// two computers talk to each other and the relay's tunnel is a silent standby, so +// the removal has to be heard and obeyed on the road that is carrying the view, +// not only on the one that was idle. +func rcRemovingADeviceClosesItsDirectView(t *testing.T) { + rcRequireDirectRoad(t) + rcRemoveTheViewerWhileItWatches(t, rcOptions{viewers: 1}, "direct") +} + +// rcRemoveTheViewerWhileItWatches is the body of both: the viewer opens the host's +// chat (and, when a road is named, waits for the view to say it is on it), the host +// removes the viewer, and the view closes and Home stops listing the host's chats. +func rcRemoveTheViewerWhileItWatches(t *testing.T, opts rcOptions, road string) { + rc := newRCRig(t, opts) + host := rc.startHost() + rc.hostAsk(host, rcHostAsk, rcHostReply) + viewer := rc.startViewer(0) + rc.openLive(viewer) + if road != "" { + rc.waitForRoad(viewer, road, rcDirectWithin) + } + + rc.hostCLI("devices", "revoke", rcViewerName) + if !waitUntil(rcPermitWithin, func() bool { return !strings.Contains(viewer.capture(), say(t, "liveLegend")) }) { + t.Fatalf("the removed computer's view stayed open:\n%s", viewer.capture()) + } + if !waitUntil(30*time.Second, func() bool { + s := viewer.capture() + for _, words := range append(rcHeldRowWords(), rcHostName+" offline") { + if strings.Contains(s, words) { + return false + } + } + return true + }) { + t.Errorf("Home on the removed computer still lists the host's chats:\n%s", viewer.capture()) + } +} + +// rcPairingDefaultIsDriveOn is V25 for the code path: two fresh homes pair with +// `codeaf pair --code`, the approving screen says the new computer can also see +// and control the chats, and the new computer can type into one with no further +// step. +func rcPairingDefaultIsDriveOn(t *testing.T) { + rc := newRCRig(t, rcOptions{viewers: 1, unpaired: true}) + if _, err := devname.Set(rc.host.home, rcHostName); err != nil { + t.Fatal(err) + } + offer := startCommand(t, rc.env(), "rc-offer", rc.host.home, rc.host.work, "pair", "--code") + var code string + if !waitUntil(30*time.Second, func() bool { + code = rcCodeShape.FindString(offer.capture()) + return code != "" + }) { + t.Fatalf("pair --code never showed a code:\n%s", offer.capture()) + } + join := startCommand(t, rc.env(), "rc-join", rc.viewers[0].home, rc.viewers[0].work, "pair", "--name", rcViewerName, code) + offer.waitFor(30*time.Second, "wants your chats") + rc.abortIfFailed() + offer.lit("y") + offer.keys("Enter") + screen := offer.waitFor(30*time.Second, say(t, "pairedControlLine")) + if !strings.Contains(screen, say(t, "pairedControlLine")) { + t.FailNow() + } + join.waitFor(30*time.Second, "Paired") + rc.abortIfFailed() + rc.settlePairing() + + host := rc.startHost() + rc.hostAsk(host, rcHostAsk, rcHostReply) + viewer := rc.startViewer(0) + rc.openLive(viewer) + // No toggle, no card, no key beyond the one that takes the keyboard. + rc.send(viewer, rcLaptopAsk) + viewer.waitFor(rcReplyWithin, rcLaptopReply) + host.waitFor(rcReplyWithin, rcLaptopReply) + rc.assertLiveDial() +} + +// rcOldFlagsStillWork is V14: with remote control on, `codeaf serve` and +// `codeaf chat --at` behave as they always did, and nothing about a live view +// shows on either screen. +func rcOldFlagsStillWork(t *testing.T) { + rc := newRCRig(t, rcOptions{viewers: 1}) + serve := rcStartPlain(t, rc.env(), "rc-serve", rc.host, 120, 40, "serve", "--via", rc.address) + var name, code string + if !waitUntil(30*time.Second, func() bool { + s := serve.capture() + if m := rcReachName.FindStringSubmatch(s); m != nil { + name = m[1] + } + if m := rcServeCode.FindStringSubmatch(s); m != nil { + code = m[1] + } + return name != "" && code != "" + }) { + t.Fatalf("codeaf serve never showed its name and code:\n%s", serve.capture()) + } + at := rcStartPlain(t, rc.env(), "rc-at", rc.viewers[0], 180, 55, "chat", "--at", name) + at.waitFor(30*time.Second, "enter the code shown on") + at.lit(code) + at.keys("Enter") + serve.waitFor(30*time.Second, "wants to use this machine") + serve.lit("y") + serve.keys("Enter") + if hit, _ := at.waitForAny(60*time.Second, say(t, "placeRestWord"), say(t, "landingKeysWord"), + say(t, "welcomeStarterKeysWord"), say(t, "starterTaskWord")); hit == "" { + t.FailNow() + } + at.lit(rcLaptopAsk) + at.keys("Enter") + at.waitFor(rcReplyWithin, rcLaptopReply) + for _, window := range []*rig{serve, at} { + screen := window.capture() + for _, word := range []string{say(t, "liveLegend"), say(t, "liveWentOffline"), say(t, "liveWatchOnly"), say(t, "liveWatching")} { + if strings.Contains(screen, word) { + t.Errorf("an older door shows %q, a word of live control:\n%s", word, screen) + } + } + } +} + +// rcDirectRoadComesUp is V30, V31 and V37 through the shipped terminal: a view +// opens on the relay, so its first paint never waits on anything else, then says +// `live · direct` once the two computers have connected to each other; a line +// typed after that is answered once on both screens, and the relay's live tunnel +// carries none of it. +func rcDirectRoadComesUp(t *testing.T) { + rcRequireDirectRoad(t) + rc := newRCRig(t, rcOptions{viewers: 1}) + host := rc.startHost() + rc.hostAsk(host, rcHostAsk, rcHostReply) + viewer := rc.startViewer(0) + // V30: the view opened and painted the chat before anything said it was + // direct, which is what openLive waits for. + rc.openLive(viewer) + rc.waitForRoad(viewer, "direct", rcDirectWithin) + if screen := viewer.capture(); strings.Contains(screen, "reconnecting") || strings.Contains(screen, say(t, "liveWentOffline")) { + t.Errorf("the swap to the direct road showed a notice of its own:\n%s", screen) + } + + // V31: a line typed on the direct road is answered once, on both screens, and + // is in the host's own transcript once. + rc.settleCarrier() + before := rc.audit.liveBytes() + rc.send(viewer, rcLaptopAsk) + viewer.waitFor(rcReplyWithin, rcLaptopReply) + host.waitFor(rcReplyWithin, rcLaptopReply) + rc.abortIfFailed() + for name, window := range map[string]*rig{"host": host, "viewer": viewer} { + if n := rcLinesWith(window.capture(), rcLaptopAsk); n != 1 { + t.Errorf("the %s shows the typed line on %d lines, want exactly one:\n%s", name, n, window.capture()) + } + } + if n := rc.model.count(rcLaptopAsk); n != 1 { + t.Errorf("the model was asked the typed line %d times over the direct road, want once", n) + } + // V37: the turn did not travel the relay. Read after the reply is on both + // screens, so a frame that was going to cross it has. + carried := rc.audit.liveBytes() - before + t.Logf("the relay's live tunnel carried %d bytes of a turn typed on a direct view (limit %d)", carried, rcDirectRelayAtMost) + if carried > rcDirectRelayAtMost { + t.Errorf("the relay's live tunnel carried %d bytes of a turn typed on a direct view, want at most %d", carried, rcDirectRelayAtMost) + } + if got := rc.roadNow(viewer); got != "direct" { + t.Errorf("after the turn the view says %q, want it still direct:\n%s", got, viewer.capture()) + } + rc.assertLiveDial() +} + +// rcRelayOnlyStaysOnTheRelay is V36 and V38 through the shipped terminal: with +// CODEAF_REMOTE_ROAD=relay on the host, a view never leaves the relay however +// long it is watched, and a line typed on it travels the relay's tunnel. +func rcRelayOnlyStaysOnTheRelay(t *testing.T) { + rcRequireDirectRoad(t) + rc := newRCRig(t, rcOptions{viewers: 1, hostEnv: []string{"CODEAF_REMOTE_ROAD=relay"}}) + host := rc.startHost() + rc.hostAsk(host, rcHostAsk, rcHostReply) + viewer := rc.startViewer(0) + rc.openLive(viewer) + // The same machine would connect in a couple of seconds, so a view that is + // still on the relay after several times that has been held there. + deadline := time.Now().Add(rcRelayStaysWithin) + for { + if got := rc.roadNow(viewer); got != "relay" { + t.Fatalf("a view of a host held to the relay says %q, want live · relay:\n%s", got, viewer.capture()) + } + if time.Now().After(deadline) { + break + } + } + + before := rc.audit.liveBytes() + rc.send(viewer, rcLaptopAsk) + viewer.waitFor(rcReplyWithin, rcLaptopReply) + host.waitFor(rcReplyWithin, rcLaptopReply) + rc.abortIfFailed() + if n := rc.model.count(rcLaptopAsk); n != 1 { + t.Errorf("the model was asked the typed line %d times, want once", n) + } + carried := rc.audit.liveBytes() - before + t.Logf("the relay's live tunnel carried %d bytes of a turn typed on a view held to the relay (floor %d)", carried, rcRelayCarriesAtLeast) + if carried < rcRelayCarriesAtLeast { + t.Errorf("the relay's live tunnel carried %d bytes of a turn typed on a view held to the relay, want at least %d: the audit is not seeing the tunnel", carried, rcRelayCarriesAtLeast) + } + if got := rc.roadNow(viewer); got != "relay" { + t.Errorf("after the turn the view says %q, want live · relay:\n%s", got, viewer.capture()) + } + rc.assertLiveDial() +} + +// ── the rig ────────────────────────────────────────────────────────────────── + +// rcOptions says what a scenario's computers start as. +type rcOptions struct { + // viewers is how many viewing computers there are, one or two. + viewers int + // unpaired leaves every home with no identity, for the scenario that pairs + // them through the product's own pairing and reads what that grants. + unpaired bool + // relay holds every window of the rig to the relay's road. The default leaves + // the road automatic, which is what a person's two computers run: a view opens + // on the relay and the swap to the direct road is a planned redial that can land + // half a second to a few seconds after it opens. That redial used to drop what + // the window had only ever written locally, such as the sentence a refused move + // leaves, so the scenarios were all held to the relay; they are not any more, + // because the road swap is invisible except the strip's road word. A scenario + // that wants to read one road with nothing else going on can still ask for this. + relay bool + // hostEnv is added to the environment of the host's windows alone, for the + // scenario that sets a switch on one computer and not the other. + hostEnv []string +} + +// rcHome is one computer of the rig: its state root, the project it works in, and +// its device id once it is paired. +type rcHome struct { + name, home, work, device string +} + +// rcRig is one scenario's world: a short root under /tmp, the scripted model, the +// auditing relay, and the paired homes. It is built by [newRCRig] and owned by +// the one subtest that built it. +type rcRig struct { + t *testing.T + root string + model *rcModel + audit *rcAudit + address string + identity string + host rcHome + viewers []rcHome + windows int + hostEnv []string + relay bool +} + +// newRCRig builds a scenario's world and leaves every window to the scenario. +// +// THE ROOT IS SHORT AND UNDER /tmp. A unix socket's path may not pass 103 bytes +// and the engine's lives under the state root, so a root under a long temporary +// folder would make every chat fall back to the in-process road this scenario is +// not about. +func newRCRig(t *testing.T, opt rcOptions) *rcRig { + t.Helper() + rcRequire(t) + if opt.viewers < 1 { + opt.viewers = 1 + } + root, err := os.MkdirTemp("/tmp", "rc-e2e-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(root) }) + t.Setenv("CODEAF_TELEMETRY", "off") + t.Setenv("DO_NOT_TRACK", "1") + + rc := &rcRig{t: t, root: root, model: startRCModel(t), hostEnv: opt.hostEnv, relay: opt.relay} + rc.address, rc.audit = startAuditedRelay(t, root) + t.Setenv(syncsetup.URLVar, rc.address) + + names := []string{rcViewerName, rcSecondName} + rc.host = rcHome{name: rcHostName, home: filepath.Join(root, "h"), work: filepath.Join(root, "hw")} + for i := 0; i < opt.viewers; i++ { + suffix := fmt.Sprint(i) + rc.viewers = append(rc.viewers, rcHome{name: names[i], home: filepath.Join(root, "v"+suffix), work: filepath.Join(root, "vw"+suffix)}) + } + for _, h := range rc.homes() { + if err := os.MkdirAll(h.home, 0o700); err != nil { + t.Fatal(err) + } + workspaceAt(t, h.work, false) + rc.writeConfig(h.home) + } + // Engines belong to these temporary homes, including any a move brings along. + t.Cleanup(func() { + pids := engineDaemonsUnder(root) + for _, pid := range pids { + _ = syscall.Kill(pid, syscall.SIGTERM) + } + deadline := time.Now().Add(10 * time.Second) + for _, pid := range pids { + for !terminalProcessExited(pid) && time.Now().Before(deadline) { + time.Sleep(20 * time.Millisecond) + } + if !terminalProcessExited(pid) { + _ = syscall.Kill(pid, syscall.SIGKILL) + } + } + }) + if opt.unpaired { + // The product's own pairing makes the identity, the roster and the + // storage answer, so nothing is written here, and the audit stays quiet + // until the scenario has settled them. + rc.audit.armed.Store(false) + return rc + } + rc.pairDirectly() + return rc +} + +// homes is every computer of the rig, the host first. +func (rc *rcRig) homes() []rcHome { return append([]rcHome{rc.host}, rc.viewers...) } + +// writeConfig gives a home the rows every scenario here wants: a stub key, the +// scripted model in every tier, no approval prompts, the plain marks and a setup +// that has been seen. +func (rc *rcRig) writeConfig(home string) { + rc.t.Helper() + rows := map[string]any{"api_key": "stub-key", "model.talk": automationStubModel, "memory.enabled": false, "tools.approvalMode": "allow", "setup_seen_at": time.Now().UTC().Format(time.RFC3339), config.KeyIcons: config.IconsPlain} + for _, key := range []string{config.KeyTaskModel, config.KeyTierWorkerModel, config.KeyTierLowModel, config.KeyTierHighModel, config.KeyTierReflexModel, config.KeyTierMastermindModel} { + rows[key] = automationStubModel + } + raw, _ := json.Marshal(rows) + if err := os.WriteFile(filepath.Join(home, "config.json"), raw, 0o600); err != nil { + rc.t.Fatal(err) + } +} + +// pairDirectly pairs the homes without driving the pairing screens: one identity, +// every other home adopting it with a key of its own, each computer named and +// registered in the directory, and sync storage off on all of them. Then it +// writes the host's explicit permit for each viewer, because a computer on the +// roster before the host first reads its book would be an older pairing, and an +// older pairing cannot type. +func (rc *rcRig) pairDirectly() { + t := rc.t + t.Helper() + id, err := identity.Ensure(rc.host.home) + if err != nil { + t.Fatal(err) + } + for _, v := range rc.viewers { + if _, err := identity.Adopt(v.home, id, false); err != nil { + t.Fatal(err) + } + } + for _, h := range rc.homes() { + if _, err := devname.Set(h.home, h.name); err != nil { + t.Fatal(err) + } + s, ok, err := syncsetup.Open(h.home) + if err != nil || !ok { + t.Fatalf("paired home %s: %v %v", h.name, ok, err) + } + if err := syncsetup.PutOwnDevice(t.Context(), s.Dir, s.Identity, s.Device, h.name); err != nil { + t.Fatal(err) + } + if err := syncsetup.SaveStorage(h.home, rc.address, s.Identity.ID(), "off"); err != nil { + t.Fatal(err) + } + rc.identity = s.Identity.ID() + switch { + case h.home == rc.host.home: + rc.host.device = s.Device.ID() + default: + for i := range rc.viewers { + if rc.viewers[i].home == h.home { + rc.viewers[i].device = s.Device.ID() + } + } + } + } + for _, h := range rc.homes() { + rcStampJoin(t, h.home, rc.identity) + } + for _, v := range rc.viewers { + rcGrant(t, rc.host.home, rc.identity, v.device, true, true) + } +} + +// settlePairing is what a scenario that paired through the product does before +// its first window: it reads the identity the pairing made, turns sync storage +// off on every home (a self-hosted relay answers on, and the point here is the +// live road alone), and only then starts holding the relay to its no-store law. +func (rc *rcRig) settlePairing() { + t := rc.t + t.Helper() + id, err := identity.Load(rc.host.home) + if err != nil { + t.Fatalf("the pairing left the host with no identity: %v", err) + } + rc.identity = id.ID() + for _, h := range rc.homes() { + if err := syncsetup.SaveStorage(h.home, rc.address, rc.identity, "off"); err != nil { + t.Fatal(err) + } + } + rc.audit.armed.Store(true) +} + +// env is what every window and command of the rig runs with. The key is a string +// and not a secret: nothing behind the model asks for one. +func (rc *rcRig) env() []string { + env := []string{config.APIKeyEnv + "=stub-key", "CODEAF_BASE_URL=" + rc.model.server.URL + "/api/v1", "CODEAF_PROFILE_DIR=", + syncsetup.URLVar + "=" + rc.address, "CODEAF_SYNC_INTERVAL_MS=100", "CODEAF_TELEMETRY=off", "DO_NOT_TRACK=1", + "CODEAF_NO_UPDATE_CHECK=1", "CODEAF_NO_AUTOMATIONS=1", "CODEAF_REMOTE_CONTROL=1", + // No window of this suite asks a STUN server: the direct road is offered + // with this machine's own addresses and nothing else. + "CODEAF_REMOTE_STUN=off"} + if rc.relay { + env = append(env, "CODEAF_REMOTE_ROAD=relay") + } + return env +} + +// window opens one terminal on a computer. Names are numbered so a window that +// comes back (the host after it was lost) never collides with the one it replaces. +func (rc *rcRig) window(name string, h rcHome) *rig { + rc.t.Helper() + rc.windows++ + env := rc.env() + if h.home == rc.host.home { + env = append(env, rc.hostEnv...) + } + return startWithEnv(rc.t, env, fmt.Sprintf("rc-%s-%d", name, rc.windows), h.home, h.work, 180, 55) +} + +func (rc *rcRig) startHost() *rig { return rc.window("host", rc.host) } + +func (rc *rcRig) startViewer(i int) *rig { return rc.window("viewer", rc.viewers[i]) } + +// abortIfFailed ends a scenario once something it stands on has failed, so a +// missing view does not cost a wait for every step behind it. +func (rc *rcRig) abortIfFailed() { + rc.t.Helper() + if rc.t.Failed() { + rc.t.FailNow() + } +} + +// hostKnowsItsOthers waits until the host's window has read the roster and written +// down that another computer is paired. A chat that finishes a turn before that is +// kept on the host for want of a second computer to share it with, and is on no +// other computer's Home until a later turn ends, which is a fact about how soon +// after starting a person asks and not about anything this suite checks. The wait +// is soft: a host that never learns it goes on, and the scenario fails where it +// needed the chat. +func (rc *rcRig) hostKnowsItsOthers() { + rc.t.Helper() + waitUntil(30*time.Second, func() bool { + found, _ := filepath.Glob(filepath.Join(rc.host.home, "v3", "sync", "others", "*")) + return len(found) > 0 + }) +} + +// hostAsk has the host's own window ask one question and waits for the reply, and +// then for the chat to be on the relay's directory. The second wait is what a +// person does without noticing: the desktop's turn ends, and a minute later the +// laptop is opened. Starting the viewer the moment the reply shows would put its one +// look at the directory before the desktop had written the chat there, and Home +// asks again only on a slow beat, so a scenario would then wait out the beat. +func (rc *rcRig) hostAsk(w *rig, words, reply string) { + rc.t.Helper() + rc.hostKnowsItsOthers() + before := rc.audit.cellCreates() + w.lit(words) + w.keys("Enter") + w.waitFor(rcReplyWithin, reply, "idle") + rc.abortIfFailed() + if before == 0 { + waitUntil(150*time.Second, func() bool { return rc.audit.cellCreates() > 0 }) + } +} + +// primeHost has the host's window finish one quick turn before the scenario +// holds a slow one. A chat is on the other computers' Home only once its first +// turn has been written down, so a chat whose very first turn is still running +// is not there to open yet: the scenarios that hold a turn at the model hold the +// second turn of a chat, which is also the commoner thing for a person to watch. +func (rc *rcRig) primeHost(w *rig) { + rc.t.Helper() + rc.hostAsk(w, rcPrimeAsk, rcPrimeReply) +} + +// goHome opens Home from wherever the window is, with the chord that does it in +// every state of a conversation, a live view included. +func (rc *rcRig) goHome(r *rig) { + rc.t.Helper() + r.keys("M-1") + r.waitFor(15*time.Second, say(rc.t, "placeRestWord")) + rc.abortIfFailed() +} + +// rcHeldRowWords are the two ways Home says a chat another computer holds is +// there to open: a turn running, or the chat held with nothing running. +func rcHeldRowWords() []string { + return []string{"working on " + rcHostName, "held on " + rcHostName} +} + +// waitForRow waits until Home shows a line saying one of the words. +func (rc *rcRig) waitForRow(r *rig, words ...string) { + rc.t.Helper() + if hit, _ := r.waitForAny(rcRowWithin, words...); hit == "" { + rc.t.FailNow() + } +} + +// openRow points at the Home row that says one of the words, and presses enter on +// it. The pointer is moved onto the row and not clicked, because what is under +// test is enter, which acts on the row the pointer last selected. +func (rc *rcRig) openRow(r *rig, words ...string) { + rc.t.Helper() + deadline := time.Now().Add(rcRowWithin) + for time.Now().Before(deadline) { + for y, line := range strings.Split(r.capture(), "\n") { + for _, word := range words { + if at := strings.Index(line, word); at >= 0 { + r.mouseTo(ansi.StringWidth(line[:at])+2, y+1) + r.keys("Enter") + return + } + } + } + time.Sleep(pollEvery) + } + rc.t.Fatalf("Home never listed a row saying any of %q. The screen was:\n%s", words, r.capture()) +} + +// openLive opens, from a viewer's Home, the chat the host holds, and answers the +// screen it opened on. It fails the scenario when the view does not say it is +// live, which is the one thing every scenario here stands on. +func (rc *rcRig) openLive(v *rig) string { + rc.t.Helper() + rc.goHome(v) + rc.openRow(v, rcHeldRowWords()...) + screen := v.waitFor(rcOpenWithin, say(rc.t, "liveLegend"), rcHostName) + rc.abortIfFailed() + return screen +} + +// rcRoadSaid is the road the newest `road` line of a screen names: "direct", +// "relay", or "" when the screen has none. The two words are chatlist's own, read +// through the table, so a respelling moves one row and not this function. +func rcRoadSaid(t *testing.T, screen string) string { + t.Helper() + direct, relayWord := say(t, "liveRoadDirect"), say(t, "liveRoadRelay") + said := "" + for _, line := range strings.Split(screen, "\n") { + if !strings.Contains(line, "road") { + continue + } + switch { + case strings.Contains(line, direct): + said = "direct" + case strings.Contains(line, relayWord): + said = "relay" + } + } + return said +} + +// roadNow asks /status, the one place a view says its road, and answers what the +// newest `road` line says. The note is local to the window and answers at once, +// so a second and a half is the margin a real terminal needs to draw it. +func (rc *rcRig) roadNow(r *rig) string { + rc.t.Helper() + rc.takeKeyboard(r) + r.lit("/status") + r.keys("Enter") + time.Sleep(1500 * time.Millisecond) + return rcRoadSaid(rc.t, r.capture()) +} + +// waitForRoad asks /status once a second until the view says it is on the road, +// and fails the scenario with the screen when it never does. +func (rc *rcRig) waitForRoad(r *rig, want string, within time.Duration) { + rc.t.Helper() + deadline := time.Now().Add(within) + got := "" + for time.Now().Before(deadline) { + if got = rc.roadNow(r); got == want { + return + } + time.Sleep(time.Second) + } + rc.t.Fatalf("the view never said it was on the %s road within %s (last said %q). The screen was:\n%s", want, within, got, r.capture()) +} + +// settleCarrier waits for the relay's live tunnel to go quiet: the channels the +// swap closed have ended and nothing is being written to it, so a count taken +// now is the baseline of what a later turn costs it. +func (rc *rcRig) settleCarrier() { + rc.t.Helper() + last, still := rc.audit.liveBytes(), 0 + for still < 4 { + time.Sleep(500 * time.Millisecond) + if now := rc.audit.liveBytes(); now != last { + last, still = now, 0 + } else { + still++ + } + } +} + +// takeKeyboard makes this window the one that types, the way the view says to: +// when it reads `typing from now` another computer has the keyboard, no +// character typed reaches a box that is not on the frame, and enter takes the +// keyboard and brings the box back with whatever was in it. A window that +// already has the keyboard is left alone. +func (rc *rcRig) takeKeyboard(r *rig) { + rc.t.Helper() + if !strings.Contains(r.capture(), say(rc.t, "liveWatching")) { + return + } + r.keys("Enter") + if !waitUntil(10*time.Second, func() bool { return !strings.Contains(r.capture(), say(rc.t, "liveWatching")) }) { + rc.t.Errorf("enter did not take the keyboard:\n%s", r.capture()) + } +} + +// takeKeyboardAfterAReturn is takeKeyboard for the moment a host has just come +// back. The keyboard follows the newest window, and the window the host started +// again is newer than the one that was typing, so the contract says the view that +// comes back does NOT hold it and must say so. It waits for that line, where +// takeKeyboard reads the screen once and takes a box it has not seen the line for +// to be the typing one, and then takes the keyboard and waits for the line to go +// before the scenario sends anything. +func (rc *rcRig) takeKeyboardAfterAReturn(r *rig) { + rc.t.Helper() + if !waitUntil(10*time.Second, func() bool { return strings.Contains(r.capture(), say(rc.t, "liveWatching")) }) { + rc.t.Fatalf("the view that came back never said another computer has the keyboard:\n%s", r.capture()) + } + rc.takeKeyboard(r) +} + +// send types words into a window and sends them. +func (rc *rcRig) send(r *rig, words string) { + rc.t.Helper() + rc.takeKeyboard(r) + r.lit(words) + r.keys("Enter") +} + +// submit sends what is already in the box. +func (rc *rcRig) submit(r *rig) { + rc.t.Helper() + rc.takeKeyboard(r) + r.keys("Enter") +} + +// hostCLI runs one of the product's own commands on the host, as a person would +// from a terminal on that computer, and answers what it printed. +func (rc *rcRig) hostCLI(args ...string) string { + rc.t.Helper() + ctx, cancel := context.WithTimeout(rc.t.Context(), time.Minute) + defer cancel() + env := append(os.Environ(), rc.env()...) + env = append(env, "CODEAF_HOME="+rc.host.home, "TERM=xterm-256color") + cmd := guardedCommand(rc.t, ctx, rc.host.home, env, binary(rc.t), args...) + cmd.Dir = rc.host.work + out, err := cmd.CombinedOutput() + if err != nil { + rc.t.Fatalf("codeaf %s: %v\n%s", strings.Join(args, " "), err, out) + } + return string(out) +} + +// assertLiveDial holds the relay to the one thing every scenario that opens a +// view must show it: at least one dial that said it was a live one. +func (rc *rcRig) assertLiveDial() { + rc.t.Helper() + if n := rc.audit.dials(relay.DoorLive); n == 0 { + rc.t.Errorf("the relay saw no dial that said %s: %s", relay.HeaderDoor+": "+relay.DoorLive, rc.audit.summary()) + } +} + +// rcStartPlain opens a command that asks a question on a plain terminal before it +// draws anything, which is how `serve` and the first `chat --at` begin. The +// package's door waits for a surface the command has not drawn yet, so the verb is +// marked headless for the one launch and put back. +func rcStartPlain(t *testing.T, env []string, name string, h rcHome, cols, rows int, args ...string) *rig { + t.Helper() + verb := firstWord(args) + was, had := headlessVerbs[verb] + headlessVerbs[verb] = true + defer func() { + if had { + headlessVerbs[verb] = was + } else { + delete(headlessVerbs, verb) + } + }() + return startWithEnv(t, env, name, h.home, h.work, cols, rows, args...) +} + +// ── the scripted model ─────────────────────────────────────────────────────── + +// rcModel is the scripted model: an endpoint that answers a chat turn by what the +// typed words say, and holds a turn whose words say `slow` until the gate opens. +type rcModel struct { + server *httptest.Server + gate chan struct{} + once sync.Once + mu sync.Mutex + asked []string + // requests is, for every turn the model answered, the messages it was handed + // (role and the opening of the text), so a scenario that is answered with the + // wrong words can say what the model was actually asked. + requests []string +} + +func startRCModel(t *testing.T) *rcModel { + t.Helper() + m := &rcModel{gate: make(chan struct{})} + brain := &automationBrain{} + mux := http.NewServeMux() + mux.HandleFunc("/api/v1/models", brain.serveCatalog) + mux.HandleFunc("/api/v1/chat/completions", m.complete) + m.server = httptest.NewServer(mux) + t.Cleanup(func() { + m.open() + m.server.Close() + }) + return m +} + +// open lets every held turn finish. It is idempotent. +func (m *rcModel) open() { m.once.Do(func() { close(m.gate) }) } + +// lastRequest is what the newest answered turn was handed. +func (m *rcModel) lastRequest() string { + m.mu.Lock() + defer m.mu.Unlock() + if len(m.requests) == 0 { + return "(no turn yet)" + } + return m.requests[len(m.requests)-1] +} + +// count is how many chat turns asked the model about words. +func (m *rcModel) count(words string) int { + m.mu.Lock() + defer m.mu.Unlock() + n := 0 + for _, ask := range m.asked { + if strings.Contains(ask, words) { + n++ + } + } + return n +} + +// rcMessageText is the text of one chat message, whether the endpoint was handed +// a plain string or a list of parts. +func rcMessageText(raw json.RawMessage) string { + var plain string + if json.Unmarshal(raw, &plain) == nil { + return plain + } + var parts []struct { + Text string `json:"text"` + } + if json.Unmarshal(raw, &parts) != nil { + return "" + } + var all []string + for _, part := range parts { + all = append(all, part.Text) + } + return strings.Join(all, "\n") +} + +func (m *rcModel) complete(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + var body struct { + Messages []struct { + Role string `json:"role"` + Content json.RawMessage `json:"content"` + } `json:"messages"` + Tools []json.RawMessage `json:"tools"` + } + _ = json.Unmarshal(raw, &body) + // The question being answered is the newest message that carries the marker + // every typed prompt has, because a conversation's history is sent each time. + ask := "" + for i := len(body.Messages) - 1; i >= 0 && ask == ""; i-- { + if !strings.EqualFold(body.Messages[i].Role, "user") { + continue + } + if text := rcMessageText(body.Messages[i].Content); strings.Contains(text, rcMark) { + ask = text + } + } + send, ok := automationStream(w) + if !ok { + return + } + // A request that offers no tools is the product naming or summarising the + // chat. It is answered with one word that no scenario waits for. + if ask == "" || len(body.Tools) == 0 { + send(`{"content":"ok"}`, "") + send(`{}`, "stop") + send("", "[DONE]") + return + } + var seen []string + for _, msg := range body.Messages { + text := strings.Join(strings.Fields(rcMessageText(msg.Content)), " ") + if len(text) > 90 { + text = text[:90] + "..." + } + seen = append(seen, msg.Role+": "+text) + } + m.mu.Lock() + m.asked = append(m.asked, ask) + m.requests = append(m.requests, strings.Join(seen, " | ")) + m.mu.Unlock() + if strings.Contains(ask, "slow") { + send(fmt.Sprintf(`{"content":%q}`, rcPartial), "") + // A held answer still keeps the line alive: a stream that says nothing for + // ten seconds is read as a dead path and asked again, so the hold writes + // the comment a busy router writes, once a second. + beat := time.NewTicker(time.Second) + defer beat.Stop() + stop := time.After(2 * time.Minute) + held: + for { + select { + case <-m.gate: + break held + case <-stop: + break held + case <-r.Context().Done(): + return + case <-beat.C: + keepalive(w) + } + } + send(fmt.Sprintf(`{"content":%q}`, " "+rcHostReply), "") + send(`{}`, "stop") + send("", "[DONE]") + return + } + reply := rcHostReply + switch { + case strings.Contains(ask, "laptop"): + reply = rcLaptopReply + case strings.Contains(ask, "prime"): + reply = rcPrimeReply + } + send(fmt.Sprintf(`{"content":%q}`, reply), "") + send(`{}`, "stop") + send("", "[DONE]") +} + +// ── the auditing relay ─────────────────────────────────────────────────────── + +// rcCall is one request the proxy saw. +type rcCall struct{ method, path, door string } + +// rcAudit writes down every request that passes through the relay's proxy and +// holds the relay to the law of this suite: with sync storage off, no one asks it +// to store anything. +type rcAudit struct { + mu sync.Mutex + calls []rcCall + armed atomic.Bool + storeWrites atomic.Int32 + // refuseAcquire makes the relay answer every request to take a chat's lease + // with a server error, which is how a move that cannot finish is made. + refuseAcquire atomic.Bool + // slowAcquire holds every request to take a chat's lease for that many + // milliseconds before the relay answers it. A move is a fraction of a second + // on one machine, and a sentence that is true for exactly as long as the move + // runs ("Moving here") is then on screen for less than a screen poll, so the + // scenario that checks the sentence makes the move last. + slowAcquire atomic.Int64 + // live is every byte, in both directions, that crossed the carrier of a dial + // that said it was a live one. It is how a scenario sees that a view on the + // direct road leaves the relay's tunnel silent. + live atomic.Int64 +} + +// liveBytes is the bytes the live dials' carriers have carried so far. +func (a *rcAudit) liveBytes() int64 { return a.live.Load() } + +// rcCountedWriter counts what crosses a connection the proxy takes over. The +// reverse proxy hijacks the response writer to carry an upgraded stream, so the +// hijacked connection is the one place every byte of it passes. +type rcCountedWriter struct { + http.ResponseWriter + total *atomic.Int64 +} + +func (w *rcCountedWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + conn, rw, err := http.NewResponseController(w.ResponseWriter).Hijack() + if err != nil { + return nil, nil, err + } + return &rcCountedConn{Conn: conn, total: w.total}, rw, nil +} + +type rcCountedConn struct { + net.Conn + total *atomic.Int64 +} + +func (c *rcCountedConn) Read(p []byte) (int, error) { + n, err := c.Conn.Read(p) + c.total.Add(int64(n)) + return n, err +} + +func (c *rcCountedConn) Write(p []byte) (int, error) { + n, err := c.Conn.Write(p) + c.total.Add(int64(n)) + return n, err +} + +// startAuditedRelay starts the product's own relay and a proxy in front of it. +// The proxy answers a store write the way the hosted service answers it while +// storage is off, and the scenario fails if one arrived. +func startAuditedRelay(t *testing.T, root string) (string, *rcAudit) { + t.Helper() + upstream, err := url.Parse(quitContinuationRelay(t, root)) + if err != nil { + t.Fatal(err) + } + proxy := httputil.NewSingleHostReverseProxy(upstream) + audit := &rcAudit{} + audit.armed.Store(true) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + audit.mu.Lock() + audit.calls = append(audit.calls, rcCall{method: r.Method, path: r.URL.Path, door: r.Header.Get(relay.HeaderDoor)}) + audit.mu.Unlock() + // The hosted service says, on every reading of the account's storage, that + // it is off. A self-hosted relay would answer on, and a computer that + // believes that tries an upload, is refused, and tries again, which is a + // property of the fixture and not of the live road. + if r.Method == http.MethodGet && r.URL.Path == "/v1/store/stats" { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"storage":"off","puts":0,"gets":0,"has":0,"bytes_in":0,"bytes_out":0}`)) + return + } + if r.Method == http.MethodPost && strings.HasPrefix(r.URL.Path, "/v1/dir/cells/") && strings.HasSuffix(r.URL.Path, "/acquire") { + if hold := audit.slowAcquire.Load(); hold > 0 { + time.Sleep(time.Duration(hold) * time.Millisecond) + } + } + if r.Method == http.MethodPost && audit.refuseAcquire.Load() && + strings.HasPrefix(r.URL.Path, "/v1/dir/cells/") && strings.HasSuffix(r.URL.Path, "/acquire") { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusServiceUnavailable) + _, _ = w.Write([]byte(`{"error":"unavailable"}`)) + return + } + // An upload is the only request that stores something: a Has or a Locate + // asks what the relay holds and writes nothing. + if r.Method == http.MethodPost && r.URL.Path == "/v1/store/frames" { + if audit.armed.Load() { + audit.storeWrites.Add(1) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"error":"storage_off"}`)) + return + } + if r.Header.Get(relay.HeaderDoor) == relay.DoorLive { + w = &rcCountedWriter{ResponseWriter: w, total: &audit.live} + } + proxy.ServeHTTP(w, r) + })) + t.Cleanup(server.Close) + t.Cleanup(func() { + if n := audit.storeWrites.Load(); n > 0 { + t.Errorf("the relay was asked to store something %d times with sync storage off: %s", n, audit.summary()) + } + }) + return server.URL, audit +} + +// cellCreates is how many chats have been written to the relay's directory so far: +// each is one POST to a cell's own path and nothing after it. +func (a *rcAudit) cellCreates() int { + a.mu.Lock() + defer a.mu.Unlock() + n := 0 + for _, call := range a.calls { + rest, ok := strings.CutPrefix(call.path, "/v1/dir/cells/") + if call.method == http.MethodPost && ok && rest != "" && !strings.Contains(rest, "/") { + n++ + } + } + return n +} + +// dials counts the requests that claimed a class of dial. +func (a *rcAudit) dials(class string) int { + a.mu.Lock() + defer a.mu.Unlock() + n := 0 + for _, call := range a.calls { + if call.door == class { + n++ + } + } + return n +} + +// summary is the paths the proxy saw, counted, for a failure to quote. +func (a *rcAudit) summary() string { + a.mu.Lock() + defer a.mu.Unlock() + counts := map[string]int{} + for _, call := range a.calls { + key := call.method + " " + call.path + if call.door != "" { + key += " [" + call.door + "]" + } + counts[key]++ + } + var lines []string + for key, n := range counts { + lines = append(lines, fmt.Sprintf("%s x%d", key, n)) + } + return strings.Join(lines, "; ") +} + +// ── reading a screen ───────────────────────────────────────────────────────── + +var ( + // rcCodeShape is a pairing code as the two doors show it, nameplate and six + // digits. + rcCodeShape = regexp.MustCompile(`\b\d{1,4}-\d{3}-\d{3}\b`) + // rcServeCode is the code `codeaf serve` shows, as two groups of three digits. + rcServeCode = regexp.MustCompile(`with code\s+(\d{3}\s\d{3})`) + // rcReachName is the name `codeaf serve` says the machine is reachable as. + rcReachName = regexp.MustCompile(`reachable as\s+(\S+)`) + // rcSeenAt is the time on the banner of a copy nobody is running. + rcSeenAt = regexp.MustCompile(`last seen (?:\d{1,2} \w{3} )?\d{1,2}:\d{2}`) +) + +// rcLinesWith is how many lines of a screen hold the words. +func rcLinesWith(screen, words string) int { + n := 0 + for _, line := range strings.Split(screen, "\n") { + if strings.Contains(line, words) { + n++ + } + } + return n +} + +// rcTranscriptsWith is how many conversations a home wrote that hold the words. +func rcTranscriptsWith(t *testing.T, home, words string) int { + t.Helper() + n := 0 + for _, text := range sessionTranscripts(t, home) { + if strings.Contains(text, words) { + n++ + } + } + return n +} + +// waitUntilFast is [waitUntil] for a state that is on the screen for a moment: it +// reads the screen every fifty milliseconds instead of every quarter second. +func waitUntilFast(within time.Duration, fact func() bool) bool { + deadline := time.Now().Add(within) + for { + if fact() { + return true + } + if time.Now().After(deadline) { + return false + } + time.Sleep(50 * time.Millisecond) + } +} diff --git a/internal/e2e/remote_control_permit_e2e_test.go b/internal/e2e/remote_control_permit_e2e_test.go new file mode 100644 index 0000000000..de5c4061e1 --- /dev/null +++ b/internal/e2e/remote_control_permit_e2e_test.go @@ -0,0 +1,51 @@ +//go:build e2e + +package e2e + +import ( + "os" + "path/filepath" + "testing" + + "github.com/Agent-Field/codeaf/internal/pair" +) + +// rcGrant writes the host's explicit permit row for one paired computer, before +// the host starts, and it is the only place this suite touches the host's own +// book of what each paired computer may do. +// +// THE ROW HAS TO BE EXPLICIT. A computer that is already on the roster when the +// host first reads its book is an older pairing, and an older pairing watches +// but cannot type, which is the right default and the wrong fixture for a +// scenario that is about typing. Writing the row first, through the host's own +// book rather than through a wire method, also keeps the scenarios honest about +// where that switch lives: on the computer that runs the chats and nowhere else. +// +// It is a file of its own because the book is a package the live-control work +// adds, and everything else in this suite stands without it. +func rcGrant(t *testing.T, hostHome, identityID, device string, watch, drive bool) { + t.Helper() + dir := filepath.Join(hostHome, "v3", "remote") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatalf("the host's remote folder: %v", err) + } + if err := pair.PermitsAt(filepath.Join(dir, "permits.json")).Set(identityID, device, &watch, &drive, "test"); err != nil { + t.Fatalf("writing the permit for %s: %v", device, err) + } +} + +// rcStampJoin is what joining an identity does to a computer's own book, so that +// every computer it meets afterwards is a new pairing and not an older one: the +// computer is not asked, once, whether the others may type into its chats. The +// rig pairs by writing the files a pairing would leave, so it writes this one too; +// leaving it out would put the one-time question over every Home in the suite. +func rcStampJoin(t *testing.T, home, identityID string) { + t.Helper() + dir := filepath.Join(home, "v3", "remote") + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatalf("a computer's remote folder: %v", err) + } + if err := pair.PermitsAt(filepath.Join(dir, "permits.json")).SnapshotLegacy(identityID, nil); err != nil { + t.Fatalf("stamping the join in %s: %v", home, err) + } +} diff --git a/internal/e2e/resume_e2e_test.go b/internal/e2e/resume_e2e_test.go index 3933bfcf29..223dac9d90 100644 --- a/internal/e2e/resume_e2e_test.go +++ b/internal/e2e/resume_e2e_test.go @@ -64,7 +64,7 @@ func TestResumeBriefAfterTakeover(t *testing.T) { b.keys("Up") t.Logf("after up:\n%s", b.capture()) b.keys("Enter") - b.waitFor(30*time.Second, "Continue this chat here?") + b.waitFor(30*time.Second, say(t, "moveAsk")) // Answer by the option's own key, then enter. Under home the up arrow is home's and // disarms the row, so walking the pointer would close the card. b.keys("1", "Enter") diff --git a/internal/e2e/storage_lifecycle_e2e_test.go b/internal/e2e/storage_lifecycle_e2e_test.go index abe92b44b4..fbfe384b06 100644 --- a/internal/e2e/storage_lifecycle_e2e_test.go +++ b/internal/e2e/storage_lifecycle_e2e_test.go @@ -369,7 +369,7 @@ func lifecycleRelayJourney(t *testing.T, live bool) { b.waitFor(45*time.Second, "Offline real workspace") } b.keys("M-m") - b.waitFor(20*time.Second, "Continue this chat here?") + b.waitFor(20*time.Second, say(t, "moveAsk")) b.keys("1", "Enter") b.waitFor(90*time.Second, "Moved from") var copied string diff --git a/internal/e2e/tmux_test.go b/internal/e2e/tmux_test.go index 22b3d0eb3e..25d523caae 100644 --- a/internal/e2e/tmux_test.go +++ b/internal/e2e/tmux_test.go @@ -710,7 +710,7 @@ func (r *rig) dump() { // clock.log is the automations clock's own account of what it could // not do (internal/automation's LogName), which is the first thing a // failed clock scenario needs read. - case "transcript.jsonl", "log", "clock.log", "usage.jsonl", "calls.jsonl": + case "transcript.jsonl", "log", "clock.log", "chat.log", "usage.jsonl", "calls.jsonl": if raw, err := os.ReadFile(path); err == nil && len(raw) > 0 { fmt.Fprintf(&b, "%s\n", clip(string(raw), 4000)) } diff --git a/internal/e2e/tuiwords_test.go b/internal/e2e/tuiwords_test.go index 15e03962e9..ee4d67bfec 100644 --- a/internal/e2e/tuiwords_test.go +++ b/internal/e2e/tuiwords_test.go @@ -553,6 +553,77 @@ var tuiWords = map[string]tuiWord{ why: "the first option on that question, which the ENGINE writes and home only relays", }, + // ── a chat another computer runs, carried here ──────────────────────────── + "moveAsk": { + screen: "Move this chat here?", + why: "the question Home's card asks before a chat another computer holds is carried to this " + + "one. Seven tmux scenarios used to wait for it as a raw string; the verb is Move here " + + "everywhere a person meets it, and this is the one place the suite spells the card's head", + }, + "movingHere": { + screen: "Moving here", + pkg: "internal/chatlist", + why: "what a live view says between choosing Move here and the chat arriving. It is the one " + + "sentence of a live view that the terminal and the desktop app both read out of chatlist", + }, + + "moveFailed": { + screen: "could not move this chat here", + why: "the note a live view carries when a Move here did not finish: it sits beside the live foot " + + "(`on desktop · live`) and the words still in the box, which is how a person knows nothing moved", + }, + + // ── a chat another computer runs, worked in from here ──────────────────── + "liveLegend": { + screen: " · live", + why: "the foot's host piece on a chat opened live (`on desktop · live`): the one mark that tells a " + + "person the chat is still running on the other computer and that nothing moved", + }, + "liveMessageHint": { + screen: "Message ", + why: "the empty box of a live view names the computer the words go to (`Message desktop`), where an " + + "ordinary conversation says what to ask", + }, + "liveRoadDirect": { + screen: "live · direct", + pkg: "internal/chatlist", + why: "the `road` row of /status on a view whose two computers have connected to each other: " + + "the one place a person is told the view left the relay, and what the direct-road scenarios wait for", + }, + "liveRoadRelay": { + screen: "live · relay", + pkg: "internal/chatlist", + why: "the `road` row of /status on a view that travels the relay, the word phase 1 shipped; " + + "a view held to the relay (CODEAF_REMOTE_ROAD=relay) must keep saying it", + }, + "liveWentOffline": { + screen: "went offline", + pkg: "internal/chatlist", + why: "the banner of a view whose host stopped answering. It must stand beside the last view and the " + + "words typed in the box, which the scenario checks in the same breath", + }, + "liveWatchOnly": { + screen: "watch, not type", + pkg: "internal/chatlist", + why: "the reason a computer that may only watch gives for its box, and the refusal a send gets back; " + + "the clause that names the fix (`Change that in /devices there`) follows it", + }, + "liveWatching": { + screen: "typing from", + pkg: "internal/chatlist", + why: "what a live view without the keyboard says about who has it (`typing from desktop now`, or " + + "`typing from the other computer now` when the holder has no name yet); it stands where the box " + + "would be, so a draft cannot hide it, and pressing enter there takes the keyboard and sends nothing", + }, + + // ── a pairing, read where the approving person reads it ────────────────── + "pairedControlLine": { + screen: "can also see and control your chats", + pkg: "internal/pair", + why: "the pairing screen of the computer that approved says the new one can open its chats and type " + + "into them, because that is the power a pairing now hands over and a person should not learn it later", + }, + // ── a landing that is the person's call (#268, the implementation) ─── "settleAskWord": { screen: "nobody could check it", diff --git a/internal/e2e/whole_state_e2e_test.go b/internal/e2e/whole_state_e2e_test.go index c1251cddba..b11b404fe7 100644 --- a/internal/e2e/whole_state_e2e_test.go +++ b/internal/e2e/whole_state_e2e_test.go @@ -236,7 +236,7 @@ func TestC6WholeState(t *testing.T) { a.keys("M-c") screen, ok = waitPlain(a, 40*time.Second, "Moved from") frames("a-one-key-arrival", a) - if !ok || strings.Contains(screen, "Continue this chat here?") { + if !ok || strings.Contains(screen, say(t, "moveAsk")) { t.Fatalf("C31.2 clean sleeping continuation required another key: %s", screen) } if !reflect.DeepEqual(before, c6Tree(t, original)) { diff --git a/internal/e2e/workspace_ownership_relay_e2e_test.go b/internal/e2e/workspace_ownership_relay_e2e_test.go index 510a843b39..72c45974b4 100644 --- a/internal/e2e/workspace_ownership_relay_e2e_test.go +++ b/internal/e2e/workspace_ownership_relay_e2e_test.go @@ -151,7 +151,7 @@ func TestWorkspaceOwnershipTaskIdentitySurvivesPublicRelayTake(t *testing.T) { // Select its actual remote activity row, not an elided project-sidebar path. b.waitFor(60*time.Second, "untitled", "running on") b.keys("M-m") - b.waitFor(20*time.Second, "Continue this chat here?") + b.waitFor(20*time.Second, say(t, "moveAsk")) takeBegan := time.Now() b.keys("1", "Enter") b.waitFor(90*time.Second, "Moved from") @@ -217,7 +217,7 @@ func TestWorkspaceOwnershipTaskIdentitySurvivesPublicRelayTake(t *testing.T) { a.keys("Space", "Space") a.waitFor(30*time.Second, "untitled", "running on") a.keys("M-m") - a.waitFor(20*time.Second, "Continue this chat here?") + a.waitFor(20*time.Second, say(t, "moveAsk")) takeBegan = time.Now() a.keys("1", "Enter") a.waitFor(90*time.Second, "Moved from") diff --git a/internal/executor/gated.go b/internal/executor/gated.go index c60d5eaf51..f1e754973c 100644 --- a/internal/executor/gated.go +++ b/internal/executor/gated.go @@ -9,7 +9,7 @@ import ( const TakeBackWithin = 15 * time.Second // TakeBackRetryLine keeps an unknown ownership write distinct from displacement. -const TakeBackRetryLine = "couldn't confirm taking this chat back from the sync service; try again" +const TakeBackRetryLine = "couldn't confirm taking this chat back from the relay; try again" // WorkRefusal retains the drive's sentence and the device that continued the // chat. Surfaces may dress the facts without classifying the sentence. diff --git a/internal/factory/legacy/run/followprogress.go b/internal/factory/legacy/run/followprogress.go index e586ae3ef1..30d52e5509 100644 --- a/internal/factory/legacy/run/followprogress.go +++ b/internal/factory/legacy/run/followprogress.go @@ -19,7 +19,7 @@ func followProgressBrief(j Job) string { if !factory.IsCIRepairStage(j.Stage) { return "" } - return "\nKeep the person informed in brief ordinary assistant messages (one or two sentences): what specific CI failure, review finding or conflict you are investigating; what you found and are changing; when you begin verification; and any meaningful change of approach during a long investigation. Write for the person, not an internal monologue. Give an update as work advances, roughly once a minute during lengthy work; do not repeat unchanged status or narrate tools. These messages are relayed to the job conversation. Distinguish a planned fix, edits in progress, checks actually run, and their observed results. Do not claim the PR was pushed, CI passed remotely or the PR is ready: the service reports those confirmed outcomes. Continue working after updates and finish through stage_result as usual.\n" + return "\nKeep the person informed in brief ordinary assistant messages (one or two sentences): what specific CI failure, review finding or conflict you are investigating; what you found and are changing; when you begin verification; and any meaningful change of approach during a long investigation. Write for the person, not an internal monologue. Give an update as work advances, roughly once a minute during lengthy work; do not repeat unchanged status or narrate tools. These messages are passed on to the job conversation. Distinguish a planned fix, edits in progress, checks actually run, and their observed results. Do not claim the PR was pushed, CI passed remotely or the PR is ready: the service reports those confirmed outcomes. Continue working after updates and finish through stage_result as usual.\n" } func followProgressStart(j Job) string { diff --git a/internal/factory/serve/hosted_guest_methods.go b/internal/factory/serve/hosted_guest_methods.go index 234ee0d992..ca4a56990e 100644 --- a/internal/factory/serve/hosted_guest_methods.go +++ b/internal/factory/serve/hosted_guest_methods.go @@ -208,6 +208,7 @@ var hostedGuestMethods = map[string]string{ remote.MethodTeamsTraffic: hostedGuestOwner, remote.MethodTeamsUpdate: hostedGuestOwner, remote.MethodTeamsWrapUp: hostedGuestOwner, + remote.MethodTranscriptPage: hostedGuestOwner, remote.MethodUnobserve: hostedGuestOwner, remote.MethodUseModelForNow: hostedGuestOwner, } diff --git a/internal/filesdoor/direct_door_test.go b/internal/filesdoor/direct_door_test.go new file mode 100644 index 0000000000..a1fd9adee7 --- /dev/null +++ b/internal/filesdoor/direct_door_test.go @@ -0,0 +1,447 @@ +package filesdoor + +import ( + "context" + "errors" + "io" + "net" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/relay" +) + +// liveCall is one live tunnel the door handed to the live handler: which device +// it was, which road the door says carried it, and the handles a test uses to +// end it or to see that it ended. +type liveCall struct { + device string + road string + release chan struct{} + ended chan struct{} +} + +// directRig is a door with a live handler that echoes four bytes, and the +// acceptor the Direct hook was handed. A direct stream is one end of a pipe +// given to that acceptor, and the other end given to DialDirect, which is what +// the peer-to-peer host and the viewer's link do with a data channel. +type directRig struct { + t *testing.T + w *world + served *served + + acceptor StreamAcceptor + owner context.Context + calls chan *liveCall +} + +// newDirectRig starts the door. mutate may change the config before it starts +// (a shorter roster time, no live handler). +func newDirectRig(t *testing.T, mutate func(*ServeConfig)) *directRig { + t.Helper() + w := newWorld(t) + rig := &directRig{t: t, w: w, calls: make(chan *liveCall, 64)} + cfg := w.config(wrap(t, newDisk(t))) + cfg.LiveRoad = func(ctx context.Context, tun io.ReadWriteCloser, device, road string) error { + defer tun.Close() + call := &liveCall{device: device, road: road, release: make(chan struct{}), ended: make(chan struct{})} + defer close(call.ended) + rig.calls <- call + echoed := make(chan struct{}) + go func() { + defer close(echoed) + buf := make([]byte, 4) + for { + if _, err := io.ReadFull(tun, buf); err != nil { + return + } + if _, err := tun.Write(buf); err != nil { + return + } + } + }() + select { + case <-call.release: + case <-ctx.Done(): + case <-echoed: + } + return nil + } + hooked := make(chan struct{}) + cfg.Direct = func(ctx context.Context, accept StreamAcceptor) { + rig.owner, rig.acceptor = ctx, accept + close(hooked) + } + if mutate != nil { + mutate(&cfg) + } + rig.served = w.serve(cfg) + if cfg.Direct != nil { + select { + case <-hooked: + case <-time.After(5 * time.Second): + t.Fatal("the door did not hand the host its acceptor") + } + } + return rig +} + +// pipe gives the acceptor one end and returns the other, which is the viewer's. +func (r *directRig) pipe() net.Conn { + r.t.Helper() + near, far := net.Pipe() + r.t.Cleanup(func() { _ = near.Close(); _ = far.Close() }) + _ = near.SetDeadline(time.Now().Add(10 * time.Second)) + go r.acceptor(r.owner, far) + return near +} + +func (r *directRig) dialDirect() (io.ReadWriteCloser, error) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return DialDirect(ctx, r.pipe(), r.w.id, r.w.b, r.w.a.ID()) +} + +func (r *directRig) nextCall() *liveCall { + r.t.Helper() + select { + case call := <-r.calls: + return call + case <-time.After(5 * time.Second): + r.t.Fatal("no live tunnel reached the live handler") + return nil + } +} + +func echoOnce(t *testing.T, tun io.ReadWriter) { + t.Helper() + if _, err := tun.Write([]byte("ping")); err != nil { + t.Fatalf("a write on a live tunnel failed: %v", err) + } + got := make([]byte, 4) + if _, err := io.ReadFull(tun, got); err != nil || string(got) != "ping" { + t.Fatalf("the live tunnel echoed %q, %v; want ping", got, err) + } +} + +// readsEOFBeforeAnyNoise reports whether the far end closed the stream having +// written nothing at all back, which is what a door does with an intent it will +// not serve. +func readsEOFBeforeAnyNoise(conn net.Conn) bool { + _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) + var buf [16]byte + n, err := conn.Read(buf[:]) + return n == 0 && errors.Is(err, io.EOF) +} + +// D8 / V38 / security: the direct road has its own intent and prologue. A direct +// stream completes only with both, the live and files prologues never complete +// against it, and the relay registration (whose prologue map has no direct +// entry) closes a direct intent before any byte is written back. +func TestADirectPrologueNeverCompletesAgainstTheLiveOrFilesPrologue(t *testing.T) { + rig := newDirectRig(t, nil) + mine, err := DoorKey(rig.w.id, rig.w.b.ID()) + if err != nil { + t.Fatal(err) + } + theirs, err := DoorKey(rig.w.id, rig.w.a.ID()) + if err != nil { + t.Fatal(err) + } + + for _, wrong := range []struct{ name, prologue string }{ + {"the live prologue", LiveTunnelPrologue}, + {"the files prologue", FilesTunnelPrologue}, + {"the task door's prologue", "codeaf task door v1 connect"}, + } { + t.Run("a direct intent with "+wrong.name+" never completes", func(t *testing.T) { + if _, err := pair.ConnectWithKeyIntent(rig.pipe(), theirs.PublicKey().Bytes(), mine, pair.IntentDirect, wrong.prologue); err == nil { + t.Fatalf("a direct stream completed with %s", wrong.name) + } + }) + } + for _, other := range []struct { + name string + intent byte + pro string + }{ + {"live", pair.IntentLive, DirectTunnelPrologue}, + {"files", pair.IntentFiles, DirectTunnelPrologue}, + {"files with its own prologue", pair.IntentFiles, FilesTunnelPrologue}, + {"live with its own prologue", pair.IntentLive, LiveTunnelPrologue}, + } { + t.Run("the "+other.name+" intent is closed before Noise on a direct stream", func(t *testing.T) { + conn := rig.pipe() + if _, err := conn.Write([]byte{other.intent}); err != nil { + t.Fatal(err) + } + if !readsEOFBeforeAnyNoise(conn) { + t.Fatalf("a direct stream answered the %s intent", other.name) + } + }) + } + t.Run("the relay registration closes a direct intent before Noise", func(t *testing.T) { + name, err := DoorName(rig.w.id, rig.w.a.ID()) + if err != nil { + t.Fatal(err) + } + stream, err := relay.DialDoor(context.Background(), rig.w.service, name, relay.DoorLive) + if err != nil { + t.Fatal(err) + } + defer stream.Close() + if _, err := stream.Write([]byte{pair.IntentDirect}); err != nil { + t.Fatal(err) + } + var buf [16]byte + if n, err := stream.Read(buf[:]); n != 0 || !errors.Is(err, io.EOF) { + t.Fatalf("the relay door answered a direct intent: %d bytes, %v", n, err) + } + }) + + t.Run("the direct intent with the direct prologue completes and the handler is told the road", func(t *testing.T) { + tun, err := rig.dialDirect() + if err != nil { + t.Fatalf("a direct dial failed: %v", err) + } + defer tun.Close() + call := rig.nextCall() + if call.road != "direct" || call.device != rig.w.b.ID() { + t.Fatalf("the handler was told road %q for device %q, want direct for the viewer", call.road, call.device) + } + echoOnce(t, tun) + }) + t.Run("a relay live stream is told the road is relay", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + tun, err := DialLive(ctx, rig.w.service, rig.w.id, rig.w.b, rig.w.a.ID()) + if err != nil { + t.Fatal(err) + } + defer tun.Close() + if call := rig.nextCall(); call.road != "relay" { + t.Fatalf("a relay live tunnel was told road %q, want relay", call.road) + } + }) +} + +// D8: a direct stream is refused before Noise when the door has no live handler, +// exactly as a relay live intent is. +func TestADoorWithNoLiveHandlerRefusesADirectIntentBeforeNoise(t *testing.T) { + rig := newDirectRig(t, func(cfg *ServeConfig) { cfg.LiveRoad = nil }) + // With nothing to serve the door ends the stream at once, so the intent byte + // may not even be accepted; either way no byte comes back. + conn := rig.pipe() + if _, err := conn.Write([]byte{pair.IntentDirect}); err == nil && !readsEOFBeforeAnyNoise(conn) { + t.Fatal("a door with no live handler answered a direct intent") + } +} + +// D8 / V38: a direct tunnel is owned by the lifetime of Serve, so the relay +// registration dropping and being remade does not end it, while a relay live +// tunnel on the same registration does end. The direct tunnel still echoes +// after the registration has come back. +func TestADirectStreamSurvivesTheRelayRegistrationEnding(t *testing.T) { + rig := newDirectRig(t, nil) + direct, err := rig.dialDirect() + if err != nil { + t.Fatalf("a direct dial failed: %v", err) + } + defer direct.Close() + directCall := rig.nextCall() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + viaRelay, err := DialLive(ctx, rig.w.service, rig.w.id, rig.w.b, rig.w.a.ID()) + if err != nil { + t.Fatal(err) + } + defer viaRelay.Close() + relayCall := rig.nextCall() + if relayCall.road != "relay" || directCall.road != "direct" { + t.Fatalf("roads were %q and %q", directCall.road, relayCall.road) + } + + before := rig.served.regs.Load() + rig.w.relay.dropRegistrations() + select { + case <-relayCall.ended: + case <-time.After(10 * time.Second): + t.Fatal("a relay live tunnel outlived the registration it came in on") + } + deadline := time.After(20 * time.Second) + for rig.served.regs.Load() <= before { + select { + case <-rig.served.ready: + case <-deadline: + t.Fatal("the door did not register again") + } + } + select { + case <-directCall.ended: + t.Fatal("a direct tunnel ended with the relay registration") + default: + } + echoOnce(t, direct) +} + +// D8: ending Serve ends every direct stream and Serve waits for them, so +// nothing runs against the door once it has returned. +func TestEndingServeEndsEveryDirectStreamAndWaitsForThem(t *testing.T) { + rig := newDirectRig(t, nil) + tun, err := rig.dialDirect() + if err != nil { + t.Fatal(err) + } + defer tun.Close() + call := rig.nextCall() + + rig.served.stop() + select { + case <-call.ended: + default: + t.Fatal("Serve returned while a direct stream's handler was still running") + } + // And a stream arriving once Serve is over is closed, not served. + conn := rig.pipe() + if _, err := conn.Write([]byte{pair.IntentDirect}); err == nil && !readsEOFBeforeAnyNoise(conn) { + t.Fatal("a stream was served after Serve ended") + } +} + +// V21 / V35: the host admits at most MaxDirect direct streams, closes the next +// one after its intent byte with nothing written back, counts them apart from +// relay live streams (so a relay one is still admitted), and admits a new +// direct stream once one ends. +func TestTheFifteenthDirectStreamIsRefusedBeforeNoise(t *testing.T) { + rig := newDirectRig(t, nil) + var held []io.ReadWriteCloser + var calls []*liveCall + t.Cleanup(func() { + for _, c := range calls { + select { + case <-c.release: + default: + close(c.release) + } + } + for _, h := range held { + _ = h.Close() + } + }) + for i := 0; i < MaxDirect; i++ { + tun, err := rig.dialDirect() + if err != nil { + t.Fatalf("direct dial %d failed: %v", i+1, err) + } + held = append(held, tun) + calls = append(calls, rig.nextCall()) + } + over := rig.pipe() + if _, err := over.Write([]byte{pair.IntentDirect}); err != nil { + t.Fatal(err) + } + if !readsEOFBeforeAnyNoise(over) { + t.Fatalf("direct stream number %d was answered", MaxDirect+1) + } + + // The relay's live count is separate: a relay live stream still gets in. + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + viaRelay, err := DialLive(ctx, rig.w.service, rig.w.id, rig.w.b, rig.w.a.ID()) + if err != nil { + t.Fatalf("a relay live dial was refused while the direct slots were full: %v", err) + } + defer viaRelay.Close() + if call := rig.nextCall(); call.road != "relay" { + t.Fatalf("the relay tunnel was told road %q", call.road) + } + + // One direct stream ends; its slot is given back. + close(calls[0].release) + select { + case <-calls[0].ended: + case <-time.After(5 * time.Second): + t.Fatal("the first direct handler did not end") + } + _ = held[0].Close() + var replaced io.ReadWriteCloser + for attempt := 0; attempt < 50 && replaced == nil; attempt++ { + if tun, err := rig.dialDirect(); err == nil { + replaced = tun + } + } + if replaced == nil { + t.Fatal("a direct stream was refused after one ended") + } + held = append(held, replaced) + calls = append(calls, rig.nextCall()) +} + +// V34 / security: a removed device cannot open a direct road (its hello is +// refused with the removal sentence), and a device removed while its direct +// tunnel is open loses the tunnel, as its relay tunnel would. +func TestARemovedDeviceLosesItsDirectStreamAndCannotOpenAnother(t *testing.T) { + saved := liveRecheck + liveRecheck = 20 * time.Millisecond + t.Cleanup(func() { liveRecheck = saved }) + rig := newDirectRig(t, func(cfg *ServeConfig) { cfg.RosterFor = 10 * time.Millisecond }) + + tun, err := rig.dialDirect() + if err != nil { + t.Fatal(err) + } + defer tun.Close() + call := rig.nextCall() + echoOnce(t, tun) + + rig.w.remove(rig.w.b.ID()) + select { + case <-call.ended: + case <-time.After(10 * time.Second): + t.Fatal("a removed device's direct tunnel was still open") + } + _, err = rig.dialDirect() + var refused *RefusedError + if !errors.As(err, &refused) || refused.Reason != RemovedLine { + t.Fatalf("a removed device's direct dial gave %v, want a refusal that says %q", err, RemovedLine) + } +} + +// D8: the stream a direct dial is given is closed when the handshake fails or +// the dial ends, so a failed attempt leaves no peer connection behind. +func TestADirectDialClosesItsStreamWhenTheHandshakeFails(t *testing.T) { + w := newWorld(t) + near, far := net.Pipe() + defer far.Close() + var closed atomic.Bool + var once sync.Once + watched := &closeWatcher{Conn: near, onClose: func() { once.Do(func() { closed.Store(true) }) }} + // The far end answers with nonsense, so the Noise handshake cannot finish. + go func() { + var b [1]byte + _, _ = far.Read(b[:]) + _ = far.Close() + }() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := DialDirect(ctx, watched, w.id, w.b, w.a.ID()); err == nil { + t.Fatal("a direct dial against a stream that closes completed") + } + if !closed.Load() { + t.Fatal("the stream was not closed after the handshake failed") + } +} + +type closeWatcher struct { + net.Conn + onClose func() +} + +func (c *closeWatcher) Close() error { + c.onClose() + return c.Conn.Close() +} diff --git a/internal/filesdoor/handover_test.go b/internal/filesdoor/handover_test.go index 87805fc5cb..04fc97e6c4 100644 --- a/internal/filesdoor/handover_test.go +++ b/internal/filesdoor/handover_test.go @@ -139,7 +139,7 @@ func (f *failingRegistrar) loop(register func(n int) error, hold func(), stopAft func TestFilesDoorRegistrationNeverGivesUpAndMakesAtMostSixAttemptsAMinute(t *testing.T) { failures := []error{ relay.ErrNameTaken, relay.ErrTooMany, relay.ErrUnreachable, relay.ErrNoDoor, - errors.New("the sync service refused this machine"), + errors.New("the relay refused this machine"), } f := &failingRegistrar{clock: time.Unix(0, 0)} r, ctx, _ := f.loop(func(n int) error { return failures[n%len(failures)] }, func() { t.Error("held a registration that never happened") }, 60) diff --git a/internal/filesdoor/hello.go b/internal/filesdoor/hello.go index 19b22f9749..86e59e757f 100644 --- a/internal/filesdoor/hello.go +++ b/internal/filesdoor/hello.go @@ -74,15 +74,63 @@ func sendHello(w io.Writer, tunnel *pair.Tunnel, dev identity.Dev) (int, error) return sendJSON(w, typeHello, helloFor(dev, tunnel)) } +// SayHello sends a device's certificate and channel-binding signature over +// tunnel and verifies the host's answering hello. +func SayHello(tunnel *pair.Tunnel, id identity.Identity, dev identity.Dev, host string) error { + if _, err := sendHello(tunnel, tunnel, dev); err != nil { + return err + } + typ, body, _, err := readMessage(tunnel, MaxRequestBytes) + if err != nil { + return err + } + return checkAnswer(id, tunnel, host, host, typ, body) +} + func refuse(w io.Writer, reason string) { _, _ = sendJSON(w, typeRefused, refusal{Reason: reason}) } +// checkAnswer reads the door's first message. A refusal is the door's answer +// and is final; an answer from some other computer, or one that is not a hello +// at all, is a door that cannot be trusted with the request. +func checkAnswer(id identity.Identity, tunnel *pair.Tunnel, targetID, person string, typ byte, body []byte) error { + switch typ { + case typeRefused: + var no refusal + if json.Unmarshal(body, &no) != nil || no.Reason == "" { + no.Reason = couldNotConfirm + } + return &RefusedError{Reason: no.Reason} + case typeHello: + default: + return protocolf("a first answer of type %d", typ) + } + var h hello + if err := json.Unmarshal(body, &h); err != nil { + return protocolf("a hello that is not readable") + } + switch { + case h.V != Version: + return &RefusedError{Reason: differentVersion} + case h.Cert.DeviceID() != targetID: + return &RefusedError{Reason: "could not confirm this is " + person} + } + if err := checkHello(id, tunnel, h); err != nil { + return &RefusedError{Reason: "could not confirm this is " + person} + } + return nil +} + // rosterCache refuses stale authority after its bounded lifetime. A refresh // that fails never extends the previous answer, even during an outage: a door -// that cannot tell whether a device is still allowed stops answering it. +// that cannot tell whether a device is still allowed stops answering it. A +// failure younger than ttl never reaches fetch because the last answer is still +// within its bounded lifetime, so an existing live link stays up until ttl +// expires. type rosterCache struct { - fetch func(context.Context) (map[string]bool, error) - now func() time.Time - ttl time.Duration + fetch func(context.Context) (map[string]bool, error) + now func() time.Time + ttl time.Duration + onGone func(removed []string) mu sync.Mutex active map[string]bool @@ -91,20 +139,42 @@ type rosterCache struct { func (r *rosterCache) allows(ctx context.Context, device string) (bool, error) { r.mu.Lock() - defer r.mu.Unlock() now := r.now() + var removed []string if r.active == nil || now.Before(r.fetched) || now.Sub(r.fetched) >= r.ttl { rows, err := r.fetch(ctx) if err != nil { + r.mu.Unlock() return false, err } + prev := r.active r.active = make(map[string]bool, len(rows)) for k, v := range rows { r.active[k] = v } r.fetched = now + if r.onGone != nil && prev != nil { + for k, wasAllowed := range prev { + if wasAllowed && !r.active[k] { + removed = append(removed, k) + } + } + } } - return r.active[device], nil + allowed := r.active[device] + onGone := r.onGone + r.mu.Unlock() + if len(removed) > 0 && onGone != nil { + onGone(removed) + } + return allowed, nil +} + +// AcceptHello reads the peer's hello from tunnel, verifies its certificate, +// channel binding and roster status, answers with this computer's hello, and +// returns the authenticated device id. +func AcceptHello(ctx context.Context, tunnel *pair.Tunnel, id identity.Identity, dev identity.Dev, allows func(context.Context, string) (bool, error)) (string, error) { + return acceptHello(ctx, tunnel, tunnel, tunnel, id, dev, allows) } // acceptHello reads the first message, which must be a hello from a device of @@ -112,6 +182,10 @@ func (r *rosterCache) allows(ctx context.Context, device string) (bool, error) { // Anything else is refused with a sentence and ends the connection before a // single object is read or sent. func (d *door) acceptHello(ctx context.Context, in io.Reader, out io.Writer, tunnel *pair.Tunnel) (string, error) { + return acceptHello(ctx, in, out, tunnel, d.cfg.Identity, d.cfg.Device, d.roster.allows) +} + +func acceptHello(ctx context.Context, in io.Reader, out io.Writer, tunnel *pair.Tunnel, id identity.Identity, dev identity.Dev, allows func(context.Context, string) (bool, error)) (string, error) { typ, body, _, err := readMessage(in, MaxRequestBytes) if err != nil { return "", err @@ -124,9 +198,9 @@ func (d *door) acceptHello(ctx context.Context, in io.Reader, out io.Writer, tun case h.V != Version: reason = differentVersion default: - if err := checkHello(d.cfg.Identity, tunnel, h); err != nil { + if err := checkHello(id, tunnel, h); err != nil { reason = err.Error() - } else if allowed, err := d.roster.allows(ctx, h.Cert.DeviceID()); err != nil { + } else if allowed, err := allows(ctx, h.Cert.DeviceID()); err != nil { reason = couldNotCheck } else if !allowed { reason = RemovedLine @@ -136,7 +210,7 @@ func (d *door) acceptHello(ctx context.Context, in io.Reader, out io.Writer, tun refuse(out, reason) return "", errors.New(reason) } - if _, err := sendHello(out, tunnel, d.cfg.Device); err != nil { + if _, err := sendHello(out, tunnel, dev); err != nil { return "", err } return h.Cert.DeviceID(), nil diff --git a/internal/filesdoor/helpers_test.go b/internal/filesdoor/helpers_test.go index 6f43bdfbfb..b5d17572b2 100644 --- a/internal/filesdoor/helpers_test.go +++ b/internal/filesdoor/helpers_test.go @@ -1,6 +1,7 @@ package filesdoor import ( + "bufio" "context" "crypto/ecdh" "crypto/sha256" @@ -9,6 +10,7 @@ import ( "fmt" "io" "math/rand" + "net" "net/http" "net/http/httptest" "path/filepath" @@ -30,12 +32,47 @@ type countedRelay struct { inner http.Handler engine atomic.Int64 dial atomic.Int64 + + mu sync.Mutex + engineConns []net.Conn +} + +// hijackSpy remembers the connection the relay takes over, so a test can end a +// registration the way a network drop would: from underneath it. +type hijackSpy struct { + http.ResponseWriter + saw func(net.Conn) +} + +func (h hijackSpy) Hijack() (net.Conn, *bufio.ReadWriter, error) { + conn, rw, err := h.ResponseWriter.(http.Hijacker).Hijack() + if err == nil { + h.saw(conn) + } + return conn, rw, err +} + +// dropRegistrations closes the connection of every registration that has been +// made, which is what the network going away looks like to the door. +func (c *countedRelay) dropRegistrations() { + c.mu.Lock() + conns := c.engineConns + c.engineConns = nil + c.mu.Unlock() + for _, conn := range conns { + _ = conn.Close() + } } func (c *countedRelay) ServeHTTP(w http.ResponseWriter, r *http.Request) { switch { case r.URL.Path == relay.EnginePath: c.engine.Add(1) + w = hijackSpy{ResponseWriter: w, saw: func(conn net.Conn) { + c.mu.Lock() + c.engineConns = append(c.engineConns, conn) + c.mu.Unlock() + }} case strings.HasPrefix(r.URL.Path, relay.DialPrefix): c.dial.Add(1) } diff --git a/internal/filesdoor/keys.go b/internal/filesdoor/keys.go index 4abad5df30..8d7600865d 100644 --- a/internal/filesdoor/keys.go +++ b/internal/filesdoor/keys.go @@ -81,6 +81,26 @@ const ( // derived from the same cell key. FilesTunnelPrologue = "codeaf files door v1 connect" + // LiveTunnelPrologue is mixed into the handshake of a live-view connection + // on the files-door registration, so a stream made for live viewing and a + // stream made for moving files can never complete against each other. + LiveTunnelPrologue = "codeaf live door v1 connect" + + // DirectTunnelPrologue is mixed into the handshake of a live view that + // travels over a peer-to-peer data channel. It is deliberately not the live + // prologue: the same static door key serves every road, so this string is + // what makes a stream made for the relay unable to complete against the + // direct road, and one made for the direct road unable to complete against + // the relay's live door or the files door. + DirectTunnelPrologue = "codeaf live door v1 direct" + + // MaxDirect is how many direct streams one door admits at once, counted + // before Noise so a flood costs a counter. A direct stream holds no relay + // stream, so the number is its own rather than a share of the relay's live + // streams; livedoor.MaxDirect is the same number for the router's side, and + // a syncsetup test pins that the two agree. + MaxDirect = 14 + doorKeySalt = "codeaf files door v1" ) @@ -98,6 +118,9 @@ var ( silentAfter = 2 * time.Minute // dialWithin bounds one dial attempt: relay, handshake and hello together. dialWithin = 10 * time.Second + // liveRecheck is how often an open live tunnel asks the roster whether its + // device is still allowed. + liveRecheck = DefaultRosterFor ) // DoorKey derives a device's files-door key from the person's cell key. Nothing diff --git a/internal/filesdoor/live_door_test.go b/internal/filesdoor/live_door_test.go new file mode 100644 index 0000000000..11c341bc28 --- /dev/null +++ b/internal/filesdoor/live_door_test.go @@ -0,0 +1,573 @@ +package filesdoor + +import ( + "bytes" + "context" + "errors" + "io" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/relay" +) + +// V21: the host admits at most 14 concurrent live-intent streams, closes the +// 15th after its intent byte with no bytes written back, still serves a +// move-intent stream at the same moment, admits a new live stream once one +// ends, and refuses live-intent streams when Live is nil. +func TestTheHostRefusesTheFifteenthLiveIntentBeforeNoise(t *testing.T) { + t.Run("fourteen live streams hold while the fifteenth is closed before Noise and move still works", func(t *testing.T) { + w := newWorld(t) + disk := newDisk(t) + frame, objects := w.frameOf(1, 128) + putFrame(t, disk, frame) + store := wrap(t, disk) + + type liveSlot struct { + release chan struct{} + exited chan struct{} + } + entered := make(chan liveSlot, relay.MaxStreams) + cfg := w.config(store) + cfg.Live = func(ctx context.Context, tun io.ReadWriteCloser, _ string) error { + defer tun.Close() + slot := liveSlot{ + release: make(chan struct{}), + exited: make(chan struct{}), + } + defer close(slot.exited) + entered <- slot + select { + case <-slot.release: + case <-ctx.Done(): + } + return nil + } + w.serve(cfg) + + ctx := context.Background() + var viewers []io.ReadWriteCloser + var slots []liveSlot + t.Cleanup(func() { + for _, s := range slots { + select { + case <-s.release: + default: + close(s.release) + } + } + for _, v := range viewers { + _ = v.Close() + } + }) + + for i := 0; i < relay.LiveStreams; i++ { + tun, err := DialLive(ctx, w.service, w.id, w.b, w.a.ID()) + if err != nil { + t.Fatalf("live dial %d failed: %v", i+1, err) + } + viewers = append(viewers, tun) + select { + case slot := <-entered: + slots = append(slots, slot) + case <-time.After(5 * time.Second): + t.Fatalf("live dial %d did not reach Live handler", i+1) + } + } + + // Dial the 15th stream without the relay class header so an older relay + // passes it through to the host backstop, then send the live intent byte. + name, err := DoorName(w.id, w.a.ID()) + if err != nil { + t.Fatal(err) + } + fifteenth, err := relay.Dial(ctx, w.service, name) + if err != nil { + t.Fatalf("fifteenth raw dial failed: %v", err) + } + defer fifteenth.Close() + + if _, err := fifteenth.Write([]byte{pair.IntentLive}); err != nil { + t.Fatal(err) + } + var reply [16]byte + n, readErr := fifteenth.Read(reply[:]) + if n != 0 || !errors.Is(readErr, io.EOF) { + t.Fatalf("fifteenth live stream read %d bytes (%v), want 0 bytes and io.EOF before any Noise message", n, readErr) + } + + // A Move-intent ('C') stream still completes while all 14 live streams hold. + mover := w.source() + got, err := mover.Get(ctx, objects[0].RID) + if err != nil { + t.Fatalf("move-intent Get while 14 live streams held failed: %v", err) + } + if !bytes.Equal(got, objects[0].Bytes) { + t.Fatal("move-intent Get returned altered object bytes") + } + + // When one live stream ends, a new live stream is admitted. + close(slots[0].release) + select { + case <-slots[0].exited: + case <-time.After(5 * time.Second): + t.Fatal("first live handler did not exit") + } + _ = viewers[0].Close() + + // THE LIVE CAP COUNTS EVERY STREAM ON THE MACHINE, NOT ONLY LIVE ONES, so + // two always stay free for a move (relay.LiveStreams). The move source + // keeps its tunnel until it is closed, and the fifteenth stream is still + // the dialler's; with both open, thirteen live views plus those two are + // fourteen and a new live view is rightly refused. Both are done with, so + // they are closed here, and what is left is thirteen live streams. + _ = mover.Close() + _ = fifteenth.Close() + + // The relay gives a slot back when its splice ends, which is asynchronous + // to the Close calls above, so the dial is tried again on that one refusal + // for a few seconds. The pause keeps every try inside the relay's thirty + // dials a minute, so the rate limit cannot stand in for the cap here. + var replacement io.ReadWriteCloser + admitted := time.Now().Add(5 * time.Second) + for { + replacement, err = DialLive(ctx, w.service, w.id, w.b, w.a.ID()) + if err == nil || !errors.Is(err, relay.ErrTooMany) || time.Now().After(admitted) { + break + } + time.Sleep(500 * time.Millisecond) + } + if err != nil { + t.Fatalf("replacement live dial after one ended failed: %v", err) + } + viewers = append(viewers, replacement) + select { + case slot := <-entered: + slots = append(slots, slot) + case <-time.After(5 * time.Second): + t.Fatal("replacement live stream did not reach Live handler") + } + }) + + t.Run("a door with nil Live refuses live intent before Noise", func(t *testing.T) { + w := newWorld(t) + w.serve(w.config(wrap(t, newDisk(t)))) + + name, err := DoorName(w.id, w.a.ID()) + if err != nil { + t.Fatal(err) + } + stream, err := relay.Dial(context.Background(), w.service, name) + if err != nil { + t.Fatal(err) + } + defer stream.Close() + + if _, err := stream.Write([]byte{pair.IntentLive}); err != nil { + t.Fatal(err) + } + var reply [16]byte + n, readErr := stream.Read(reply[:]) + if n != 0 || !errors.Is(readErr, io.EOF) { + t.Fatalf("door with nil Live answered %d bytes (%v), want 0 bytes and io.EOF", n, readErr) + } + }) +} + +// V14 / V28: an existing Source moving a chat with intent 'C' and the files +// prologue still completes a normal round trip against a door with Live set. +func TestAnOlderViewerStillMovesAChat(t *testing.T) { + w := newWorld(t) + disk := newDisk(t) + frame, objects := w.frameOf(1, 256, 512) + frameID := putFrame(t, disk, frame) + + var liveCalled atomic.Bool + cfg := w.config(wrap(t, disk)) + cfg.Live = func(_ context.Context, tun io.ReadWriteCloser, _ string) error { + liveCalled.Store(true) + return tun.Close() + } + w.serve(cfg) + + src := w.source() + ctx := context.Background() + have, err := src.Has(ctx, []string{objects[0].RID, objects[1].RID}) + if err != nil || len(have) != 2 || !have[0] || !have[1] { + t.Fatalf("Has = %v, %v", have, err) + } + gotFrame, err := src.GetFrame(ctx, frameID) + if err != nil || !bytes.Equal(gotFrame, frame) { + t.Fatalf("GetFrame = %d bytes, %v", len(gotFrame), err) + } + gotMany, err := src.GetMany(ctx, []string{objects[0].RID, objects[1].RID}) + if err != nil || len(gotMany) != 2 || !bytes.Equal(gotMany[0].Bytes, objects[0].Bytes) || !bytes.Equal(gotMany[1].Bytes, objects[1].Bytes) { + t.Fatalf("GetMany = %d objects, %v", len(gotMany), err) + } + if liveCalled.Load() { + t.Fatal("a move stream invoked the Live handler") + } +} + +// D2: a connection that sends the live intent with the files prologue, or the +// files intent with the live prologue, never completes the Noise handshake. +func TestAFilesPrologueAndALivePrologueNeverCompleteAgainstEachOther(t *testing.T) { + w := newWorld(t) + store := wrap(t, newDisk(t)) + var liveCalled atomic.Bool + cfg := w.config(store) + cfg.Live = func(_ context.Context, tun io.ReadWriteCloser, _ string) error { + liveCalled.Store(true) + return tun.Close() + } + w.serve(cfg) + + hostKey, err := DoorKey(w.id, w.a.ID()) + if err != nil { + t.Fatal(err) + } + viewerKey, err := DoorKey(w.id, w.b.ID()) + if err != nil { + t.Fatal(err) + } + name, err := DoorName(w.id, w.a.ID()) + if err != nil { + t.Fatal(err) + } + + for _, tc := range []struct { + name string + intent byte + prologue string + }{ + {name: "live intent with files prologue", intent: pair.IntentLive, prologue: FilesTunnelPrologue}, + {name: "files intent with live prologue", intent: pair.IntentFiles, prologue: LiveTunnelPrologue}, + } { + t.Run(tc.name, func(t *testing.T) { + stream, err := relay.Dial(context.Background(), w.service, name) + if err != nil { + t.Fatal(err) + } + defer stream.Close() + + if _, err := pair.ConnectWithKeyIntent(stream, hostKey.PublicKey().Bytes(), viewerKey, tc.intent, tc.prologue); err == nil { + t.Fatalf("handshake completed for %s", tc.name) + } + if liveCalled.Load() { + t.Fatal("mismatched handshake reached Live") + } + if store.reads.Load() != 0 { + t.Fatal("mismatched handshake read the store") + } + }) + } +} + +// V10: removing a device cancels its live tunnel immediately through the push +// callback, cancels it on the next recheck through the pull backstop when no +// push arrives, and closes the tunnel on a roster error past the TTL while +// riding out a roster error younger than the TTL. +func TestRemovingADeviceCancelsItsLiveTunnelThroughThePushAndThroughThePull(t *testing.T) { + t.Run("push revocation cancels only the removed device", func(t *testing.T) { + w := newWorld(t) + c, err := identity.NewDevice(w.id) + if err != nil { + t.Fatal(err) + } + w.allow(c.ID(), true) + + goneCh := make(chan func([]string), 1) + type session struct { + device string + done <-chan struct{} + } + sessions := make(chan session, 4) + + cfg := w.config(wrap(t, newDisk(t))) + cfg.Revoked = func(_ context.Context, gone func(devices []string)) func() { + select { + case goneCh <- gone: + default: + } + return func() {} + } + cfg.Live = func(ctx context.Context, tun io.ReadWriteCloser, device string) error { + defer tun.Close() + sessions <- session{device: device, done: ctx.Done()} + <-ctx.Done() + return nil + } + w.serve(cfg) + + var gone func([]string) + select { + case gone = <-goneCh: + case <-time.After(5 * time.Second): + t.Fatal("Revoked was not started on registration") + } + + ctx := context.Background() + tunB, err := DialLive(ctx, w.service, w.id, w.b, w.a.ID()) + if err != nil { + t.Fatal(err) + } + defer tunB.Close() + + tunC, err := DialLive(ctx, w.service, w.id, c, w.a.ID()) + if err != nil { + t.Fatal(err) + } + defer tunC.Close() + + byDevice := make(map[string]<-chan struct{}, 2) + for len(byDevice) < 2 { + select { + case s := <-sessions: + byDevice[s.device] = s.done + case <-time.After(5 * time.Second): + t.Fatal("both live sessions did not arrive") + } + } + + gone([]string{w.b.ID()}) + + select { + case <-byDevice[w.b.ID()]: + case <-time.After(2 * time.Second): + t.Fatal("removed device context was not cancelled by push") + } + + select { + case <-byDevice[c.ID()]: + t.Fatal("other device context was cancelled when only b was removed") + default: + } + }) + + t.Run("pull recheck cancels a removed device without push", func(t *testing.T) { + oldRecheck := liveRecheck + liveRecheck = 15 * time.Millisecond + t.Cleanup(func() { liveRecheck = oldRecheck }) + + w := newWorld(t) + cfg := w.config(wrap(t, newDisk(t))) + cfg.RosterFor = 15 * time.Millisecond + canceled := make(chan struct{}) + entered := make(chan struct{}) + cfg.Live = func(ctx context.Context, tun io.ReadWriteCloser, _ string) error { + defer tun.Close() + close(entered) + <-ctx.Done() + close(canceled) + return nil + } + w.serve(cfg) + + tun, err := DialLive(context.Background(), w.service, w.id, w.b, w.a.ID()) + if err != nil { + t.Fatal(err) + } + defer tun.Close() + + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("live handler was not reached") + } + + w.allow(w.b.ID(), false) + + select { + case <-canceled: + case <-time.After(2 * time.Second): + t.Fatal("live link was not cancelled after roster removal and liveRecheck") + } + }) + + t.Run("a roster error older than the ttl closes the tunnel while a younger one does not", func(t *testing.T) { + oldRecheck := liveRecheck + liveRecheck = 15 * time.Millisecond + t.Cleanup(func() { liveRecheck = oldRecheck }) + + w := newWorld(t) + var failRoster atomic.Bool + cfg := w.config(wrap(t, newDisk(t))) + cfg.RosterFor = 160 * time.Millisecond + cfg.Roster = func(ctx context.Context) (map[string]bool, error) { + if failRoster.Load() { + return nil, errors.New("directory unreachable") + } + return w.roster(ctx) + } + + entered := make(chan struct{}) + liveDone := make(chan struct{}) + cfg.Live = func(ctx context.Context, tun io.ReadWriteCloser, _ string) error { + defer tun.Close() + defer close(liveDone) + close(entered) + _, _ = io.Copy(tun, tun) + return nil + } + w.serve(cfg) + + tun, err := DialLive(context.Background(), w.service, w.id, w.b, w.a.ID()) + if err != nil { + t.Fatal(err) + } + defer tun.Close() + + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("live handler was not reached") + } + + // Turn on roster errors immediately; while the cached answer is younger + // than RosterFor (160 ms), recheck ticks at 15 ms must keep the tunnel open. + failRoster.Store(true) + youngTimer := time.NewTimer(45 * time.Millisecond) + defer youngTimer.Stop() + <-youngTimer.C + + select { + case <-liveDone: + t.Fatal("a roster failure younger than the ttl closed the live tunnel") + default: + } + if _, err := tun.Write([]byte("still open")); err != nil { + t.Fatalf("write during young roster failure failed: %v", err) + } + echo := make([]byte, len("still open")) + if _, err := io.ReadFull(tun, echo); err != nil || string(echo) != "still open" { + t.Fatalf("read during young roster failure = %q, %v", echo, err) + } + + // Once the 160 ms TTL expires, the next recheck fails closed and shuts the tunnel. + select { + case <-liveDone: + case <-time.After(2 * time.Second): + t.Fatal("a roster error older than the ttl did not close the live tunnel") + } + var buf [8]byte + if _, err := tun.Read(buf[:]); err == nil { + t.Fatal("viewer tunnel remained readable after a roster error older than the ttl") + } + }) +} + +// D2 / 3.2: the files door's idle watchdog closes an idle files-intent stream +// after idleAfter, while a live link idle past idleAfter stays open. +func TestALiveLinkIsNotCutByTheFilesDoorsIdleWatchdog(t *testing.T) { + oldIdle := idleAfter + idleAfter = 60 * time.Millisecond + t.Cleanup(func() { idleAfter = oldIdle }) + + w := newWorld(t) + cfg := w.config(wrap(t, newDisk(t))) + cfg.Live = func(ctx context.Context, tun io.ReadWriteCloser, _ string) error { + defer tun.Close() + _, _ = io.Copy(tun, tun) + return nil + } + w.serve(cfg) + + liveTun, err := DialLive(context.Background(), w.service, w.id, w.b, w.a.ID()) + if err != nil { + t.Fatal(err) + } + defer liveTun.Close() + + key, err := DoorKey(w.id, w.b.ID()) + if err != nil { + t.Fatal(err) + } + filesTun := w.rawTunnel(key) + sendRaw(t, filesTun, typeHello, jsonOf(t, helloFor(w.b, filesTun))) + if got := receive(t, filesTun, 5*time.Second); got.err != nil || got.typ != typeHello { + t.Fatalf("files hello = type %d, %v", got.typ, got.err) + } + + // Wait for the files-intent stream to be closed by the idle watchdog. + if got := receive(t, filesTun, 2*time.Second); got.err == nil { + t.Fatalf("idle files-intent stream stayed open and answered type %d", got.typ) + } + + // Wait one more idleAfter window so the live tunnel has been idle well past idleAfter. + extra := time.NewTimer(80 * time.Millisecond) + defer extra.Stop() + <-extra.C + + want := []byte("still alive after idleAfter") + if _, err := liveTun.Write(want); err != nil { + t.Fatalf("live tunnel write after idleAfter failed: %v", err) + } + got := make([]byte, len(want)) + if _, err := io.ReadFull(liveTun, got); err != nil { + t.Fatalf("live tunnel read after idleAfter failed: %v", err) + } + if !bytes.Equal(got, want) { + t.Fatalf("live tunnel echoed %q, want %q", got, want) + } +} + +// 3.2: DialLive reaches the host's Live handler with the authenticated viewer +// device id, carries bytes both ways, and preserves relay.ErrNoMachine when the +// host is not registered. +func TestDialLiveReachesTheHostLiveHandlerWithTheViewersDeviceId(t *testing.T) { + w := newWorld(t) + + // Before the host registers, DialLive reports relay.ErrNoMachine. + if _, err := DialLive(context.Background(), w.service, w.id, w.b, w.a.ID()); !errors.Is(err, relay.ErrNoMachine) { + t.Fatalf("DialLive with unregistered host = %v, want relay.ErrNoMachine", err) + } + + var ( + mu sync.Mutex + gotDevice string + ) + cfg := w.config(wrap(t, newDisk(t))) + cfg.Live = func(_ context.Context, tun io.ReadWriteCloser, device string) error { + defer tun.Close() + mu.Lock() + gotDevice = device + mu.Unlock() + + var in [16]byte + if _, err := io.ReadFull(tun, in[:]); err != nil { + return err + } + _, err := tun.Write(append([]byte("host heard: "), in[:]...)) + return err + } + w.serve(cfg) + + tun, err := DialLive(context.Background(), w.service, w.id, w.b, w.a.ID()) + if err != nil { + t.Fatal(err) + } + defer tun.Close() + + msg := []byte("viewer-sixteen!!") + if _, err := tun.Write(msg); err != nil { + t.Fatal(err) + } + want := append([]byte("host heard: "), msg...) + reply := make([]byte, len(want)) + if _, err := io.ReadFull(tun, reply); err != nil { + t.Fatal(err) + } + if !bytes.Equal(reply, want) { + t.Fatalf("reply = %q, want %q", reply, want) + } + + mu.Lock() + defer mu.Unlock() + if gotDevice != w.b.ID() { + t.Fatalf("Live received device %q, want %q", gotDevice, w.b.ID()) + } +} diff --git a/internal/filesdoor/serve.go b/internal/filesdoor/serve.go index 4a86d64364..e1b76ca75b 100644 --- a/internal/filesdoor/serve.go +++ b/internal/filesdoor/serve.go @@ -24,7 +24,7 @@ import ( const ( // LostLine and BackLine are the only two things the door says on its own, // once each per spell of the sync service being out of reach. - LostLine = "moving chats between your computers is paused while the sync service is out of reach" + LostLine = "moving chats between your computers is paused while they cannot reach each other" BackLine = "moving chats between your computers works again" // The registration backoff doubles from a second up to ten seconds. In a @@ -69,15 +69,55 @@ type ServeConfig struct { SecretsPage int // ChatTitle reads the name of one local conversation for a paired peer. ChatTitle func(id string) string + // Live serves an authenticated live-view tunnel for device until ctx ends + // or the tunnel closes. When nil, live-intent connections are refused + // before Noise completes. + Live func(ctx context.Context, tun io.ReadWriteCloser, device string) error + // LiveRoad is Live for a handler that must know which road carried the + // tunnel: "relay" for a stream that came through the registration, "direct" + // for one the Direct host handed to [door.AcceptStream]. When it is set it + // serves every live tunnel and Live is not consulted; a direct stream is + // refused before Noise completes when it is nil. + LiveRoad func(ctx context.Context, tun io.ReadWriteCloser, device, road string) error + // Direct, when set, is called once as Serve starts with the acceptor the + // peer-to-peer host hands each opened data-channel stream to. The context is + // the lifetime of Serve itself, NOT of any one registration: a direct tunnel + // does not ride the relay, so the relay registration dropping and being + // remade must not end it. + Direct func(ctx context.Context, accept StreamAcceptor) + // Revoked subscribes to device-removal notifications for the life of one + // registration and calls gone with any device ids that were removed. + Revoked func(ctx context.Context, gone func(devices []string)) (stop func()) // Ready, when set, is called after every successful registration, before // the door starts answering. It must not block. Ready func() } +// StreamAcceptor takes one peer-to-peer stream whose far end has not yet been +// authenticated and runs the whole connection on the calling goroutine: Noise, +// the device hello, the roster, then the live handler. It returns when the +// connection ends and closes the stream either way. +type StreamAcceptor func(ctx context.Context, stream io.ReadWriteCloser) + +// liveHandler is the one function that serves every live tunnel, whichever of +// the two config fields supplied it, or nil when the door serves none. +func (c ServeConfig) liveHandler() func(ctx context.Context, tun io.ReadWriteCloser, device, road string) error { + switch { + case c.LiveRoad != nil: + return c.LiveRoad + case c.Live != nil: + live := c.Live + return func(ctx context.Context, tun io.ReadWriteCloser, device, _ string) error { + return live(ctx, tun, device) + } + } + return nil +} + func (c ServeConfig) check() error { address, err := url.Parse(strings.TrimSpace(c.Service)) if err != nil || address.Host == "" || (address.Scheme != "http" && address.Scheme != "https") { - return errors.New("filesdoor: a door needs a sync service address that looks like https://relay.example.com") + return errors.New("filesdoor: a door needs a relay address that looks like https://relay.example.com") } if c.Roster == nil || c.Store == nil || c.LockPath == "" { return errors.New("filesdoor: a door needs a roster, a store and a lock file") @@ -124,7 +164,21 @@ func Serve(ctx context.Context, cfg ServeConfig) error { } defer release(lock) - d := &door{cfg: cfg, key: key, roster: &rosterCache{fetch: cfg.Roster, now: time.Now, ttl: ttl}} + d := &door{ + cfg: cfg, + key: key, + liveCancels: make(map[string][]liveCancel), + } + d.roster = &rosterCache{fetch: cfg.Roster, now: time.Now, ttl: ttl, onGone: d.evict} + d.serveCtx = ctx + // DIRECT STREAMS ARE OWNED BY THIS CONTEXT AND NOT BY A REGISTRATION. They are + // waited for when Serve ends, so nothing touches the roster or the live + // handler once Serve has returned, and they are never waited for by a + // registration that merely dropped. + defer d.closeDirect() + if cfg.Direct != nil { + cfg.Direct(ctx, d.AcceptStream) + } (®istrar{ service: cfg.Service, key: key, @@ -133,7 +187,7 @@ func Serve(ctx context.Context, cfg ServeConfig) error { ready: cfg.Ready, say: cfg.Say, now: time.Now, - wait: sleep, + wait: jitteredSleep, }).run(ctx) return nil } @@ -181,6 +235,10 @@ func sleep(ctx context.Context, d time.Duration) error { } } +func jitteredSleep(ctx context.Context, d time.Duration) error { + return sleep(ctx, relay.Jitter(d)) +} + // registrar keeps the door registered under its name. It deliberately never // gives up while the context lives: a name still held by the dead connection of // a process that just ended, a rate limit, an unreachable relay and a relay @@ -243,17 +301,133 @@ type door struct { cfg ServeConfig key *ecdh.PrivateKey roster *rosterCache + + // serveCtx is the lifetime of Serve, kept so a direct stream can be tied to it. + serveCtx context.Context + + liveMu sync.Mutex + liveCount int + liveNextID uint64 + liveCancels map[string][]liveCancel + + // directMu guards the direct-stream bookkeeping. directClosed is set once + // Serve is ending, after which a stream is refused rather than started, so + // directWG.Add can never race the Wait that closeDirect runs. + directMu sync.Mutex + directCount int + directClosed bool + directWG sync.WaitGroup +} + +type liveCancel struct { + id uint64 + cancel context.CancelFunc +} + +func (d *door) admitLive() bool { + d.liveMu.Lock() + defer d.liveMu.Unlock() + if d.liveCount >= relay.LiveStreams { + return false + } + d.liveCount++ + return true +} + +func (d *door) releaseLive() { + d.liveMu.Lock() + d.liveCount-- + d.liveMu.Unlock() +} + +// admitDirect takes one of the host's MaxDirect direct-stream slots, before +// Noise, so a flood of streams costs a counter and not a handshake. It refuses +// once Serve is ending. +func (d *door) admitDirect() bool { + d.directMu.Lock() + defer d.directMu.Unlock() + if d.directClosed || d.directCount >= MaxDirect { + return false + } + d.directCount++ + d.directWG.Add(1) + return true +} + +func (d *door) releaseDirect() { + d.directMu.Lock() + d.directCount-- + d.directMu.Unlock() + d.directWG.Done() +} + +// closeDirect stops new direct streams and waits for the open ones, which end +// because their contexts derive from Serve's, now done. +func (d *door) closeDirect() { + d.directMu.Lock() + d.directClosed = true + d.directMu.Unlock() + d.directWG.Wait() +} + +func (d *door) trackLive(device string, cancel context.CancelFunc) func() { + d.liveMu.Lock() + d.liveNextID++ + id := d.liveNextID + if d.liveCancels == nil { + d.liveCancels = make(map[string][]liveCancel) + } + d.liveCancels[device] = append(d.liveCancels[device], liveCancel{id: id, cancel: cancel}) + d.liveMu.Unlock() + return func() { + d.liveMu.Lock() + entries := d.liveCancels[device] + for i, entry := range entries { + if entry.id == id { + entries = append(entries[:i], entries[i+1:]...) + break + } + } + if len(entries) == 0 { + delete(d.liveCancels, device) + } else { + d.liveCancels[device] = entries + } + d.liveMu.Unlock() + } +} + +func (d *door) evict(devices []string) { + var cancels []context.CancelFunc + d.liveMu.Lock() + for _, dev := range devices { + for _, entry := range d.liveCancels[dev] { + cancels = append(cancels, entry.cancel) + } + delete(d.liveCancels, dev) + } + d.liveMu.Unlock() + for _, cancel := range cancels { + cancel() + } } // hold owns accepted streams until the registration ends, and waits for every // connection to finish before it returns, so nothing touches the store once // Serve has returned. func (d *door) hold(ctx context.Context, registration *relay.Registration) { - stop := context.AfterFunc(ctx, func() { _ = registration.Close() }) + holdCtx, cancelHold := context.WithCancel(ctx) + stop := context.AfterFunc(holdCtx, func() { _ = registration.Close() }) defer stop() var connections sync.WaitGroup defer connections.Wait() + defer cancelHold() defer registration.Close() + if d.cfg.Revoked != nil { + if stopRevoked := d.cfg.Revoked(holdCtx, d.evict); stopRevoked != nil { + defer stopRevoked() + } + } for { stream, err := registration.Accept() if err != nil { @@ -262,19 +436,90 @@ func (d *door) hold(ctx context.Context, registration *relay.Registration) { connections.Add(1) go func() { defer connections.Done() - d.answer(ctx, stream) + d.answer(ctx, holdCtx, stream) }() } } -// answer runs one connection: tunnel, hello, then requests one at a time. -func (d *door) answer(ctx context.Context, stream io.ReadWriteCloser) { +// answer runs one connection: tunnel, hello, then either the live handler or +// file-transfer requests one at a time. +// +// TWO CONTEXTS, BECAUSE THE TWO KINDS OF CONNECTION END DIFFERENTLY. A files +// connection ends with ctx, as it always has: when a registration drops, one +// that is mid-transfer is left to finish. A live link may stay open for hours +// and nothing finishes it, so it ends with registrationEnded, or the +// registrar could never register again while one was open. +func (d *door) answer(ctx, registrationEnded context.Context, stream io.ReadWriteCloser) { + d.serveStream(ctx, registrationEnded, stream, false) +} + +// AcceptStream runs one peer-to-peer stream through the same door a relay +// stream goes through: the same Noise handshake against the same door key, the +// same device hello, the same roster and revocation, and the same live +// handler. It is the [StreamAcceptor] the Direct host is handed. +// +// THE DIFFERENCE IS THE INTENT AND THE PROLOGUE, AND THE HOST CHOOSES THEM. A +// direct stream completes only with [pair.IntentDirect] and +// [DirectTunnelPrologue]; the relay registration's prologue map has no direct +// entry, and this one has nothing else, so a stream made for one road can never +// finish against the other, or against the files door, even though every one +// of them uses the same static door key. What the door learns about the road +// is therefore never something the viewer says. +// +// IT IS OWNED BY THE LIFETIME OF SERVE. A relay registration dropping and being +// remade must not kill a healthy direct tunnel, so the stream's context is +// derived from ctx and ended when Serve ends, and never from a registration. +func (d *door) AcceptStream(ctx context.Context, stream io.ReadWriteCloser) { + if d.serveCtx == nil { + _ = stream.Close() + return + } + ctx, cancel := context.WithCancel(ctx) + defer cancel() + defer context.AfterFunc(d.serveCtx, cancel)() + d.serveStream(ctx, ctx, stream, true) +} + +// serveStream is the body both [door.answer] and [door.AcceptStream] share. +func (d *door) serveStream(ctx, registrationEnded context.Context, stream io.ReadWriteCloser, direct bool) { defer stream.Close() defer context.AfterFunc(ctx, func() { _ = stream.Close() })() guard := newWatch(handshakeWithin, func() { _ = stream.Close() }) defer guard.stop() - tunnel, err := pair.AcceptWithKeyPrologue(stream, d.key, FilesTunnelPrologue) + live := d.cfg.liveHandler() + prologues := map[byte]string{} + switch { + case direct: + if live != nil { + prologues[pair.IntentDirect] = DirectTunnelPrologue + } + default: + prologues[pair.IntentFiles] = FilesTunnelPrologue + if live != nil { + prologues[pair.IntentLive] = LiveTunnelPrologue + } + } + admitted := byte(0) + defer func() { + d.releaseAdmitted(admitted) + }() + tunnel, intent, err := pair.AcceptWithKeyPrologues(stream, d.key, func(intent byte) bool { + switch intent { + case pair.IntentLive: + if live == nil || !d.admitLive() { + return false + } + case pair.IntentDirect: + if live == nil || !d.admitDirect() { + return false + } + default: + return true + } + admitted = intent + return true + }, prologues) if err != nil { return } @@ -283,6 +528,22 @@ func (d *door) answer(ctx context.Context, stream io.ReadWriteCloser) { if err != nil { return } + if intent == pair.IntentLive || intent == pair.IntentDirect { + road := "relay" + if intent == pair.IntentDirect { + road = "direct" + } + // A live view may sit quiet for minutes while the person reads, so the + // files door's request watchdog must stop once the hello has finished. + guard.stop() + d.answerLive(registrationEnded, tunnel, device, road, live) + // The slot is given back as soon as the view ends, not when this + // goroutine unwinds, so a viewer that redials at once finds it free. + d.releaseAdmitted(admitted) + admitted = 0 + _ = tunnel.Close() + return + } // From here the same timer is the idle bound, moved forward by every byte. guard.after = idleAfter guard.kick() @@ -318,6 +579,72 @@ func (d *door) answer(ctx context.Context, stream io.ReadWriteCloser) { } } +// releaseAdmitted gives back the slot an admitted connection took, if it took +// one: the live count for the relay, the direct count for a peer-to-peer one. +func (d *door) releaseAdmitted(intent byte) { + switch intent { + case pair.IntentLive: + d.releaseLive() + case pair.IntentDirect: + d.releaseDirect() + } +} + +// answerLive runs a live-view connection under a revocable context and a +// periodic roster re-check. A roster error younger than the roster cache's TTL +// is masked by the cached answer and keeps the link; a failure once the TTL has +// expired returns an error from allows and closes the tunnel so a removed +// device's view is never extended past the TTL. It is the same for both roads: +// a removed device loses its direct tunnel as fast as its relay one. +func (d *door) answerLive(ctx context.Context, tunnel *pair.Tunnel, device, road string, live func(ctx context.Context, tun io.ReadWriteCloser, device, road string) error) { + linkCtx, cancelLink := context.WithCancel(ctx) + defer cancelLink() + // A CANCELLED LINK CLOSES ITS TUNNEL whatever the handler does with its + // context: a removed device's view must end, not wait for the handler to + // notice. + defer context.AfterFunc(linkCtx, func() { _ = tunnel.Close() })() + untrack := d.trackLive(device, cancelLink) + defer untrack() + + recheck := liveRecheck + if recheck == DefaultRosterFor && d.roster.ttl < recheck { + recheck = d.roster.ttl + } + if recheck <= 0 { + recheck = DefaultRosterFor + } + recheckDone := make(chan struct{}) + defer func() { + cancelLink() + <-recheckDone + }() + go func() { + defer close(recheckDone) + ticker := time.NewTicker(recheck) + defer ticker.Stop() + for { + select { + case <-linkCtx.Done(): + return + case <-ticker.C: + allowed, err := d.roster.allows(linkCtx, device) + if err != nil { + _ = tunnel.Close() + cancelLink() + return + } + if !allowed { + d.evict([]string{device}) + cancelLink() + return + } + } + } + }() + + _ = live(linkCtx, tunnel, device, road) +} + // reply is one response before it is written. type reply struct { typ byte diff --git a/internal/filesdoor/source.go b/internal/filesdoor/source.go index ef2b2dca9a..d867b11c65 100644 --- a/internal/filesdoor/source.go +++ b/internal/filesdoor/source.go @@ -2,6 +2,7 @@ package filesdoor import ( "context" + "crypto/ecdh" "encoding/binary" "encoding/hex" "encoding/json" @@ -710,7 +711,7 @@ func (s *Source) handshake(ctx context.Context) (*pair.Tunnel, error) { if err != nil { return nil, err } - stream, err := relay.Dial(attempt, s.cfg.Service, relay.NameFor(theirs.PublicKey().Bytes())) + stream, err := relay.DialDoor(attempt, s.cfg.Service, relay.NameFor(theirs.PublicKey().Bytes()), relay.DoorMove) if err != nil { return nil, err } @@ -759,31 +760,88 @@ func (s *Source) handshake(ctx context.Context) (*pair.Tunnel, error) { // and is final; an answer from some other computer, or one that is not a hello // at all, is a door that cannot be trusted with the request. func (s *Source) checkAnswer(tunnel *pair.Tunnel, typ byte, body []byte) error { - switch typ { - case typeRefused: - var no refusal - if json.Unmarshal(body, &no) != nil || no.Reason == "" { - no.Reason = couldNotConfirm - } - return &RefusedError{Reason: no.Reason} - case typeHello: - default: - return protocolf("a first answer of type %d", typ) + return checkAnswer(s.cfg.Identity, tunnel, s.cfg.TargetID, s.person(), typ, body) +} + +// DialLive opens an authenticated live-view tunnel to host on its files-door +// registration using the live dial class, intent and prologue. +func DialLive(ctx context.Context, service string, id identity.Identity, dev identity.Dev, host string) (io.ReadWriteCloser, error) { + attempt, cancel := context.WithTimeout(ctx, dialWithin) + defer cancel() + keys, err := liveKeys(id, dev, host) + if err != nil { + return nil, err } - var h hello - if err := json.Unmarshal(body, &h); err != nil { - return protocolf("a hello that is not readable") + name, err := DoorName(id, host) + if err != nil { + return nil, err } - switch { - case h.V != Version: - return &RefusedError{Reason: differentVersion} - case h.Cert.DeviceID() != s.cfg.TargetID: - return &RefusedError{Reason: "could not confirm this is " + s.person()} + stream, err := relay.DialDoor(attempt, service, name, relay.DoorLive) + if err != nil { + return nil, err } - if err := checkHello(s.cfg.Identity, tunnel, h); err != nil { - return &RefusedError{Reason: "could not confirm this is " + s.person()} + return sayLive(attempt, stream, id, dev, host, keys, pair.IntentLive, LiveTunnelPrologue) +} + +// DialDirect finishes a live-view tunnel over a stream that already exists: the +// byte stream of an open peer-to-peer data channel. It is DialLive for a +// carrier the caller built, with the direct intent and prologue, the same +// door-key handshake against the host's pinned key and the same device hello, +// and it returns a READY tunnel, which is the contract a link's Dial has. The +// stream is closed when the handshake fails, and the dial ends with +// [dialWithin]. +func DialDirect(ctx context.Context, stream io.ReadWriteCloser, id identity.Identity, dev identity.Dev, host string) (io.ReadWriteCloser, error) { + attempt, cancel := context.WithTimeout(ctx, dialWithin) + defer cancel() + keys, err := liveKeys(id, dev, host) + if err != nil { + _ = stream.Close() + return nil, err } - return nil + return sayLive(attempt, stream, id, dev, host, keys, pair.IntentDirect, DirectTunnelPrologue) +} + +// liveKeysOf are the two door keys a live dial uses: this device's own, and the +// host's, whose public half the handshake pins. +type liveKeysOf struct{ mine, theirs *ecdh.PrivateKey } + +func liveKeys(id identity.Identity, dev identity.Dev, host string) (liveKeysOf, error) { + mine, err := DoorKey(id, dev.ID()) + if err != nil { + return liveKeysOf{}, err + } + theirs, err := DoorKey(id, host) + if err != nil { + return liveKeysOf{}, err + } + return liveKeysOf{mine: mine, theirs: theirs}, nil +} + +// sayLive is the handshake and hello every live dial runs over a stream it has +// been handed, whichever road made the stream. It takes the stream's ownership: +// a failed or timed-out dial closes it. +func sayLive(attempt context.Context, stream io.ReadWriteCloser, id identity.Identity, dev identity.Dev, host string, keys liveKeysOf, intent byte, prologue string) (io.ReadWriteCloser, error) { + succeeded := false + defer func() { + if !succeeded { + _ = stream.Close() + } + }() + stop := context.AfterFunc(attempt, func() { _ = stream.Close() }) + defer stop() + + tunnel, err := pair.ConnectWithKeyIntent(stream, keys.theirs.PublicKey().Bytes(), keys.mine, intent, prologue) + if err != nil { + return nil, err + } + if err := SayHello(tunnel, id, dev, host); err != nil { + return nil, err + } + if !stop() || attempt.Err() != nil { + return nil, errors.New("filesdoor: the dial ran out of time") + } + succeeded = true + return tunnel, nil } func (s *Source) person() string { diff --git a/internal/guard/sweep_test.go b/internal/guard/sweep_test.go index 5ba723ab1d..9fc2dd60d8 100644 --- a/internal/guard/sweep_test.go +++ b/internal/guard/sweep_test.go @@ -18,7 +18,9 @@ import ( var guardedPackages = []string{ "cmd/codeaf", "internal/catalog", + "internal/directroad", "internal/exec", + "internal/livedoor", "internal/plan", "internal/provider", "internal/resident", diff --git a/internal/handoff/idle_open_test.go b/internal/handoff/idle_open_test.go index 6b37fb1525..7141290ab3 100644 --- a/internal/handoff/idle_open_test.go +++ b/internal/handoff/idle_open_test.go @@ -25,7 +25,7 @@ func TestIdleOpen_C6_C8_ReleasedAndLapsedChatNeedsOnlyRelay(t *testing.T) { taker.FreeOnly = true if !released { if _, err := taker.Take(t.Context(), chatID); !errors.Is(err, directory.ErrLeaseHeld) { - t.Fatalf("lapsed hold bypassed Continue here: %v", err) + t.Fatalf("lapsed hold bypassed Move here: %v", err) } // The confirmed continuation still needs only the relay. taker.FreeOnly = false diff --git a/internal/identity/pristine.go b/internal/identity/pristine.go index 1aa69ce23a..f88ab4ddd1 100644 --- a/internal/identity/pristine.go +++ b/internal/identity/pristine.go @@ -72,6 +72,22 @@ var startupRules = rules{ }), "history.jsonl": onlyCommands, "models*.json": pickerCache, "lanes.json": never, "lanes.json.lock": never, "lanes.log": never, "lanes": never, // provider facts fetched from the model catalogue, fetched again on demand + // REMOTE CONTROL'S BOOKKEEPING IS NEVER LOCAL WORK. Watching and typing into + // a chat from another computer leaves these behind on whichever computer + // ran it, and none of them is something the person made: the permit book + // belongs to an identity the join replaces (a book written for another + // identity is read as the safe default and rewritten), the day's byte + // count starts again at zero each day, the live door's sockets and pid + // files are swept when their process is gone, and the view copy is a read- + // only picture of ANOTHER computer's chat. A home that counted any of them + // as use would look used the moment a computer was paired and then left + // alone, and could not join another set of computers without --replace. + // Anything else in v3/remote (the device key, say) is still use. + "remote": within(rules{ + "permits.json": never, "permits.json.new": never, + "budget.json": never, ".budget-*.tmp": never, + }), + "live": never, "viewed": never, "draft-*.json": untypedDraft, "hosts": never, "standing": never, "stores": within(rules{ "sweep.stamp": never, diff --git a/internal/identity/remote_bookkeeping_test.go b/internal/identity/remote_bookkeeping_test.go new file mode 100644 index 0000000000..146bec607f --- /dev/null +++ b/internal/identity/remote_bookkeeping_test.go @@ -0,0 +1,90 @@ +package identity + +import ( + "os" + "path/filepath" + "testing" +) + +// The validation contract for remote control's bookkeeping in a home. +// +// C2: whatever remote control writes into a home (the permit book, the day's +// byte count, the live door's sockets and pid files, the copy of another +// computer's chat) never makes the home count as having local work, so it +// never blocks a join and never makes a fresh home look used. The writers +// themselves are held to this in their own packages (internal/pair for the +// permit book, internal/livedoor for the byte count); this table holds the +// judge to the names, including the temporary files each writer replaces. + +// remoteHome is a home that was only started, with one change applied, and +// without the memory graph: Joinable reads that graph as a real start makes it, +// and the fixture's hand-made one is a different shape, so a test of what else +// the home holds judges the home without it. +func remoteHome(t *testing.T, change func(home string)) string { + t.Helper() + return startedHome(t, func(home string) { + for _, graph := range []string{"graph.db", "graph.db-wal", "graph.db-shm"} { + if err := os.Remove(filepath.Join(home, graph)); err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + } + if change != nil { + change(home) + } + }) +} + +func TestRemoteControlBookkeepingNeverCountsAsLocalWork(t *testing.T) { + // The control: with nothing added, the home can join, so a refusal below is + // the added file's doing and not the fixture's. + if ok, err := Joinable(remoteHome(t, nil)); err != nil || !ok { + t.Fatalf("the started home cannot join before anything is added: joinable=%v err=%v", ok, err) + } + for _, name := range []string{ + "v3/remote/permits.json", + "v3/remote/permits.json.new", + "v3/remote/budget.json", + "v3/remote/.budget-123456.tmp", + "v3/live/4242.json", + "v3/live/4242.sock", + "v3/live/.live-123456.tmp", + "v3/viewed/work-laptop/01CHAT.json", + } { + t.Run(name, func(t *testing.T) { + home := remoteHome(t, func(home string) { + put(t, filepath.Join(home, name), `{"v":1}`) + }) + if ok, err := Joinable(home); err != nil || !ok { + t.Fatalf("%s blocked a join: joinable=%v err=%v", name, ok, err) + } + // Pristine keeps the graph, which a real start leaves and the fixture + // models, so a fresh home is judged as it really is. + fresh := startedHome(t, func(home string) { + put(t, filepath.Join(home, name), `{"v":1}`) + }) + if ok, err := Pristine(fresh); err != nil || !ok { + t.Fatalf("%s made a home that was only started look used: pristine=%v err=%v", name, ok, err) + } + }) + } +} + +// Only the bookkeeping is let through. The remote folder also holds a +// computer's device key and whatever a later build puts there, and an entry +// this judge does not name is use, as everywhere else in a home. +func TestTheRemoteFolderStillProtectsWhatIsNotBookkeeping(t *testing.T) { + for _, name := range []string{ + "v3/remote/device.key", + "v3/remote/notes.txt", + "v3/remote/permits.json.bak", + } { + t.Run(name, func(t *testing.T) { + home := remoteHome(t, func(home string) { + put(t, filepath.Join(home, name), "the person's") + }) + if ok, err := Joinable(home); err != nil || ok { + t.Fatalf("%s was let through as bookkeeping: joinable=%v err=%v", name, ok, err) + } + }) + } +} diff --git a/internal/livedoor/budget.go b/internal/livedoor/budget.go new file mode 100644 index 0000000000..6a56130363 --- /dev/null +++ b/internal/livedoor/budget.go @@ -0,0 +1,290 @@ +package livedoor + +import ( + "encoding/json" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/env" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/home" +) + +const ( + budgetPersistInterval = 30 * time.Second + budgetEnvDailyMB = "CODEAF_REMOTE_DAILY_MB" +) + +var budgetDiskMu sync.Mutex + +type budgetDisk struct { + Day string `json:"day"` + Bytes int64 `json:"bytes"` +} + +// Budget counts carrier bytes across all live door tunnels per UTC day and +// degrades sessions to watch-only once the daily allowance is exhausted. +type Budget struct { + path string + clk Clock + limit int64 + + mu sync.Mutex + day string + bytes int64 + dirty bool + closed bool + exhaustedNotified bool + timer Timer + done chan struct{} + nextHookID uint64 + hooks map[uint64]func() +} + +// OpenBudget loads or initializes the daily byte budget stored at +// /v3/remote/budget.json. A missing, corrupt, or previous-day file starts +// at zero bytes for the current UTC date without scheduling any background timer. +func OpenBudget(homeDir string, clk Clock, limit int64) *Budget { + if clk == nil { + clk = RealClock() + } + effectiveLimit := resolveBudgetLimit(limit) + homeDir = strings.TrimSpace(homeDir) + if homeDir == "" { + homeDir = home.Dir() + } + var path string + if strings.TrimSpace(homeDir) != "" { + path = filepath.Join(homeDir, "v3", "remote", "budget.json") + } + + today := utcDay(clk.Now()) + var initialBytes int64 + if path != "" { + budgetDiskMu.Lock() + raw, err := os.ReadFile(path) + budgetDiskMu.Unlock() + if err == nil { + var d budgetDisk + if json.Unmarshal(raw, &d) == nil && d.Day == today && d.Bytes > 0 { + initialBytes = d.Bytes + } + } + } + + return &Budget{ + path: path, + clk: clk, + limit: effectiveLimit, + day: today, + bytes: initialBytes, + done: make(chan struct{}), + hooks: make(map[uint64]func()), + } +} + +func resolveBudgetLimit(limit int64) int64 { + if limit > 0 { + return limit + } + if limit == 0 { + if raw := strings.TrimSpace(env.Get(budgetEnvDailyMB)); raw != "" { + if mb, err := strconv.ParseInt(raw, 10, 64); err == nil && mb > 0 { + return mb << 20 + } + } + } + return DailyBudget +} + +func utcDay(t time.Time) string { + return t.UTC().Format("2006-01-02") +} + +func (b *Budget) rollDayLocked() { + today := utcDay(b.clk.Now()) + if today != b.day { + b.day = today + b.bytes = 0 + b.exhaustedNotified = false + } +} + +func (b *Budget) addOnExhausted(fn func()) func() { + if b == nil || fn == nil { + return func() {} + } + b.mu.Lock() + b.nextHookID++ + id := b.nextHookID + b.hooks[id] = fn + b.mu.Unlock() + + var once sync.Once + return func() { + once.Do(func() { + b.mu.Lock() + delete(b.hooks, id) + b.mu.Unlock() + }) + } +} + +// Charge adds n carrier bytes to the current UTC day's count, lazily arming the +// thirty-second persistence timer on the first charge and firing registered +// exhaustion callbacks once when the day's total reaches the limit. +func (b *Budget) Charge(n int64) (over bool) { + if b == nil { + return false + } + b.mu.Lock() + b.rollDayLocked() + if n > 0 { + b.bytes += n + b.dirty = true + if !b.closed && b.timer == nil { + t := b.clk.NewTimer(budgetPersistInterval) + b.timer = t + guard.Go("livedoor.budget.persist", func() { + b.waitPersist(t) + }) + } + } + over = b.bytes >= b.limit + var callbacks []func() + if over && !b.exhaustedNotified { + b.exhaustedNotified = true + for _, fn := range b.hooks { + if fn != nil { + callbacks = append(callbacks, fn) + } + } + } + b.mu.Unlock() + + for _, fn := range callbacks { + fn() + } + return over +} + +// Exhausted reports whether the current UTC day's byte allowance has been used up. +func (b *Budget) Exhausted() bool { + if b == nil { + return false + } + b.mu.Lock() + defer b.mu.Unlock() + b.rollDayLocked() + return b.bytes >= b.limit +} + +// Bytes returns the carrier bytes charged so far during the current UTC day. +func (b *Budget) Bytes() int64 { + if b == nil { + return 0 + } + b.mu.Lock() + defer b.mu.Unlock() + b.rollDayLocked() + return b.bytes +} + +// Close stops any pending persistence timer and flushes the current day's byte +// count atomically to /v3/remote/budget.json. +func (b *Budget) Close() { + if b == nil { + return + } + b.mu.Lock() + if b.closed { + b.mu.Unlock() + return + } + b.closed = true + close(b.done) + if b.timer != nil { + b.timer.Stop() + b.timer = nil + } + b.rollDayLocked() + day, bytes := b.day, b.bytes + b.dirty = false + b.mu.Unlock() + + _ = b.writeDisk(day, bytes) +} + +func (b *Budget) waitPersist(t Timer) { + select { + case <-t.C(): + budgetDiskMu.Lock() + defer budgetDiskMu.Unlock() + + b.mu.Lock() + if b.timer == t { + b.timer = nil + } + if b.closed || !b.dirty { + b.mu.Unlock() + return + } + b.rollDayLocked() + day, bytes := b.day, b.bytes + b.dirty = false + b.mu.Unlock() + + _ = b.writeDiskLocked(day, bytes) + case <-b.done: + t.Stop() + } +} + +func (b *Budget) writeDisk(day string, bytes int64) error { + budgetDiskMu.Lock() + defer budgetDiskMu.Unlock() + return b.writeDiskLocked(day, bytes) +} + +func (b *Budget) writeDiskLocked(day string, bytes int64) error { + if b.path == "" { + return nil + } + dir := filepath.Dir(b.path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + _ = os.Chmod(dir, 0o700) + raw, err := json.Marshal(budgetDisk{ + Day: day, + Bytes: bytes, + }) + if err != nil { + return err + } + tmp, err := os.CreateTemp(dir, ".budget-*.tmp") + if err != nil { + return err + } + tmpName := tmp.Name() + _ = tmp.Chmod(0o600) + if _, err := tmp.Write(raw); err != nil { + _ = tmp.Close() + _ = os.Remove(tmpName) + return err + } + if err := tmp.Close(); err != nil { + _ = os.Remove(tmpName) + return err + } + if err := os.Rename(tmpName, b.path); err != nil { + _ = os.Remove(tmpName) + return err + } + _ = os.Chmod(b.path, 0o600) + return nil +} diff --git a/internal/livedoor/budget_test.go b/internal/livedoor/budget_test.go new file mode 100644 index 0000000000..8786acbae5 --- /dev/null +++ b/internal/livedoor/budget_test.go @@ -0,0 +1,247 @@ +package livedoor + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net" + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/remote" +) + +// TestPastTheDailyBudgetEverySessionBecomesWatchOnlyWithAReason verifies +// contract V19: once traffic across live tunnels reaches the daily byte budget, +// every open channel on every link is reset once with reason budget, and when +// the viewer redials on the tunnel it receives a watch-only stamp (Drive:false) +// and continues watching without being cut again. +func TestPastTheDailyBudgetEverySessionBecomesWatchOnlyWithAReason(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + homeDir := shortTempDir(t) + fc := NewFakeClock(time.Date(2026, 11, 23, 14, 0, 0, 0, time.UTC)) + reg := NewRegistry() + + // Set a small limit (4 KiB) so initial handshakes succeed under the budget + // and a single call pushes the day's total over the limit. + budget := OpenBudget(homeDir, fc, 4096) + t.Cleanup(func() { budget.Close() }) + + hellos := make(chan remote.Hello, 8) + resolver := newEchoStampResolver(func(h remote.Hello) { + hellos <- h + }) + + startLink := func(device string) (*Mux, *Channel) { + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + peer := Peer{ + Device: device, + Label: device, + Permit: pair.Permit{Watch: true, Drive: true}, + } + guard.Go("livedoor.test.v19.serve", func() { + _ = Serve(ctx, hConn, peer, ServeConfig{ + Resolver: resolver, + Registry: reg, + Budget: budget, + Clock: fc, + Host: "workstation", + Road: "relay", + }) + }) + vMux := NewMux(vConn, Viewer, MuxConfig{Clock: fc}) + t.Cleanup(func() { _ = vMux.Close() }) + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck(%s) failed: %v", device, err) + } + ch := openAndHandshake(t, ctx, vMux, "chat-budget") + h := <-hellos + if h.Remote == nil || !h.Remote.Drive { + t.Fatalf("initial hello for %s had Remote=%+v, want Drive=true before budget exhaustion", device, h.Remote) + } + return vMux, ch + } + + vMux1, ch1 := startLink("dev-budget-1") + _, ch2 := startLink("dev-budget-2") + if budget.Exhausted() { + t.Fatalf("budget already exhausted after handshakes (bytes=%d)", budget.Bytes()) + } + + // Send a call frame large enough to push the shared budget past 4096 bytes. + bigCall := makeFrameLineOfExactLength(t, "call", remote.MethodPing, 4096) + _, _ = ch1.Write(bigCall) + + var buf [64]byte + for i, ch := range []*Channel{ch1, ch2} { + _, err := ch.Read(buf[:]) + if got := reasonOf(err); got != ReasonBudget { + t.Fatalf("channel %d when budget exhausted ended with %v (reason=%q), want %q", i+1, err, got, ReasonBudget) + } + } + if !budget.Exhausted() { + t.Fatal("budget.Exhausted() is false after exceeding limit") + } + + // Redialling on the same link opens a watch-only channel (Drive:false) that + // stays open even as further bytes are charged. + chRedial := openAndHandshake(t, ctx, vMux1, "chat-budget") + redialHello := <-hellos + if redialHello.Remote == nil || redialHello.Remote.Drive || !redialHello.Remote.Watch || !redialHello.Watch { + t.Fatalf("redial hello after budget exhaustion had Remote=%+v Watch=%v, want Drive=false Watch=true", + redialHello.Remote, redialHello.Watch) + } + + // A disallowed Submit on the watch-only redial channel is refused with the + // watch-only sentence rather than resetting the channel again. + submitLine, _ := json.Marshal(remote.Frame{ + Kind: "call", + ID: 99, + Method: remote.MethodSubmit, + }) + if _, err := chRedial.Write(append(submitLine, '\n')); err != nil { + t.Fatalf("Write on watch-only redial channel failed: %v", err) + } + scan := newLineScanner(chRedial, MaxLine) + resLine, err := scan.ReadLine(MaxLine) + if err != nil { + t.Fatalf("reading refusal on watch-only redial channel failed: %v", err) + } + var res remote.Frame + if err := json.Unmarshal(bytes.TrimRight(resLine, "\r\n"), &res); err != nil { + t.Fatalf("unmarshaling refusal failed: %v", err) + } + wantErr := remote.GuestRefusal("workstation", remote.MethodSubmit, false) + if res.ID != 99 || res.Error != wantErr { + t.Fatalf("watch-only redial Submit result = %+v, want ID=99 Error=%q", res, wantErr) + } +} + +// TestTheCountSurvivesARestartAndRollsAtUTCMidnight verifies contract V19: +// the persistence timer schedules nothing until the first charge, charging to +// the limit and advancing 30s (or closing) writes /v3/remote/budget.json +// with mode 0600 so reopening from disk restores the exact count, and advancing +// the clock past 00:00 UTC rolls the day and resets the count to zero. +func TestTheCountSurvivesARestartAndRollsAtUTCMidnight(t *testing.T) { + homeDir := shortTempDir(t) + start := time.Date(2026, 11, 23, 23, 50, 0, 0, time.UTC) + fc := NewFakeClock(start) + + const limit = 10 << 20 + b1 := OpenBudget(homeDir, fc, limit) + if got := fc.BlockedTimers(); got != 0 { + t.Fatalf("BlockedTimers before first charge = %d, want 0", got) + } + + // First charge lazily arms the 30-second persistence timer. + if over := b1.Charge(limit / 2); over { + t.Fatalf("Charge(%d) reported over=true below limit %d", limit/2, limit) + } + if got := fc.BlockedTimers(); got != 1 { + t.Fatalf("BlockedTimers after first charge = %d, want 1", got) + } + + // Charge to the limit and fire the 30s timer so it persists to disk even before Close. + if over := b1.Charge(limit / 2); !over { + t.Fatalf("Charge to limit (%d) reported over=false, want true", limit) + } + if !b1.Exhausted() || b1.Bytes() != limit { + t.Fatalf("b1 Exhausted=%v Bytes=%d, want true and %d", b1.Exhausted(), b1.Bytes(), limit) + } + fc.Advance(30 * time.Second) + b1.Close() + + budgetPath := filepath.Join(homeDir, "v3", "remote", "budget.json") + info, err := os.Stat(budgetPath) + if err != nil { + t.Fatalf("Stat(%q) failed: %v", budgetPath, err) + } + if runtime.GOOS != "windows" { + if perm := info.Mode().Perm(); perm != 0o600 { + t.Fatalf("budget.json mode = %04o, want 0600", perm) + } + } + + // Reopen from disk on the same UTC day: count and exhausted state must match. + b2 := OpenBudget(homeDir, fc, limit) + t.Cleanup(func() { b2.Close() }) + if got := fc.BlockedTimers(); got != 0 { + t.Fatalf("BlockedTimers on reopened budget before charge = %d, want 0", got) + } + if got := b2.Bytes(); got != limit { + t.Fatalf("reopened budget Bytes() = %d, want %d", got, limit) + } + if !b2.Exhausted() { + t.Fatal("reopened budget Exhausted() = false, want true") + } + + // Advance past 00:00 UTC into 2026-11-24: count must roll over to 0. + fc.Advance(15 * time.Minute) + if got := b2.Bytes(); got != 0 { + t.Fatalf("Bytes() after UTC midnight rollover = %d, want 0", got) + } + if b2.Exhausted() { + t.Fatal("Exhausted() after UTC midnight rollover = true, want false") + } +} + +// TestAnIdleBudgetSchedulesNothing verifies contract V19: an opened budget that +// receives no charges schedules zero timers on the clock and writes no file +// while idle. +func TestAnIdleBudgetSchedulesNothing(t *testing.T) { + homeDir := shortTempDir(t) + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + + b := OpenBudget(homeDir, fc, 0) + if got := fc.BlockedTimers(); got != 0 { + t.Fatalf("BlockedTimers on newly opened idle budget = %d, want 0", got) + } + if b.Exhausted() || b.Bytes() != 0 { + t.Fatalf("idle budget Exhausted=%v Bytes=%d, want false and 0", b.Exhausted(), b.Bytes()) + } + + fc.Advance(2 * time.Hour) + if got := fc.BlockedTimers(); got != 0 { + t.Fatalf("BlockedTimers after 2 virtual hours of idle = %d, want 0", got) + } + budgetPath := filepath.Join(homeDir, "v3", "remote", "budget.json") + if _, err := os.Stat(budgetPath); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("idle budget created %q before any charge or Close (err=%v)", budgetPath, err) + } +} + +// C2: the day's byte count is remote control's own file in a home. It must +// never make that home count as having local work, so a computer that watched +// or was watched, and was then left alone, can still join another set of +// computers, and a home that was only started still looks unused. +func TestTheByteCountNeverMakesAHomeLookUsed(t *testing.T) { + homeDir := shortTempDir(t) + if _, err := identity.EnsureSolo(homeDir); err != nil { + t.Fatal(err) + } + b := OpenBudget(homeDir, NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)), 1<<20) + b.Charge(1024) + b.Close() + if _, err := os.Stat(filepath.Join(homeDir, "v3", "remote", "budget.json")); err != nil { + t.Fatalf("the byte count was not written, so this proves nothing: %v", err) + } + if ok, err := identity.Pristine(homeDir); err != nil || !ok { + t.Fatalf("the byte count made a home that was only started look used: pristine=%v err=%v", ok, err) + } + if ok, err := identity.Joinable(homeDir); err != nil || !ok { + t.Fatalf("the byte count blocked a join: joinable=%v err=%v", ok, err) + } +} diff --git a/internal/livedoor/clock.go b/internal/livedoor/clock.go new file mode 100644 index 0000000000..4b5ed2eac3 --- /dev/null +++ b/internal/livedoor/clock.go @@ -0,0 +1,34 @@ +package livedoor + +import "time" + +// Clock is the time source for the multiplexer and live door so tests can +// drive pacing, ping deadlines, and idle detach without sleeping on wall time. +type Clock interface { + // Now returns the current wall reading without a monotonic suffix so a + // machine waking from sleep is seen as having jumped forward in time. + Now() time.Time + NewTimer(d time.Duration) Timer +} + +// Timer is a one-shot timer created by a Clock. +type Timer interface { + C() <-chan time.Time + Stop() +} + +// RealClock returns the machine's wall clock backed by the standard time package. +func RealClock() Clock { + return realClock{} +} + +type realClock struct{} + +func (realClock) Now() time.Time { return time.Now().Round(0) } + +func (realClock) NewTimer(d time.Duration) Timer { return realTimer{time.NewTimer(d)} } + +type realTimer struct{ t *time.Timer } + +func (r realTimer) C() <-chan time.Time { return r.t.C } +func (r realTimer) Stop() { r.t.Stop() } diff --git a/internal/livedoor/clock_fake.go b/internal/livedoor/clock_fake.go new file mode 100644 index 0000000000..3dccec0167 --- /dev/null +++ b/internal/livedoor/clock_fake.go @@ -0,0 +1,157 @@ +package livedoor + +import ( + "fmt" + "runtime" + "sync" + "sync/atomic" + "time" +) + +// FakeClock is a deterministic clock driven by tests across packages. +// A test that waits for a background goroutine to park on a timer before +// calling Advance must use WaitForTimers (or inspect BlockedTimers) rather than +// calling runtime.Gosched or sleeping on real time. +type FakeClock struct { + mu sync.Mutex + now time.Time + nextSeq uint64 + pending []*fakeTimer + blocked atomic.Int32 +} + +type fakeTimer struct { + clock *FakeClock + at time.Time + seq uint64 + ch chan time.Time + stopped bool +} + +// NewFakeClock creates a FakeClock positioned at start. +func NewFakeClock(start time.Time) *FakeClock { + if start.IsZero() { + start = time.Unix(1_700_000_000, 0).UTC() + } + return &FakeClock{now: start} +} + +// Now returns the fake clock's current time. +func (c *FakeClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +// NewTimer registers a timer that fires when Advance moves the clock to or +// past Now().Add(d). A non-positive duration fires immediately. +func (c *FakeClock) NewTimer(d time.Duration) Timer { + c.mu.Lock() + defer c.mu.Unlock() + c.nextSeq++ + t := &fakeTimer{ + clock: c, + at: c.now.Add(d), + seq: c.nextSeq, + ch: make(chan time.Time, 1), + } + if d <= 0 { + t.stopped = true + t.ch <- c.now + return t + } + c.pending = append(c.pending, t) + c.blocked.Store(int32(len(c.pending))) + return t +} + +// BlockedTimers reports how many unfired, unstopped timers are currently +// waiting on the fake clock. +func (c *FakeClock) BlockedTimers() int { + return int(c.blocked.Load()) +} + +// WaitForTimers spins on BlockedTimers with a bounded real-time loop of at +// most three seconds until at least n timers are pending (or zero when n <= 0), +// panicking with a clear diagnostic if the condition is not reached in time. +func (c *FakeClock) WaitForTimers(n int) { + deadline := time.Now().Add(3 * time.Second) + for { + cur := int(c.blocked.Load()) + if (n <= 0 && cur == 0) || (n > 0 && cur >= n) { + return + } + if time.Now().After(deadline) { + panic(fmt.Sprintf("livedoor.FakeClock: timed out waiting for %d blocked timer(s); have %d", n, cur)) + } + runtime.Gosched() + } +} + +// Advance moves the clock forward by d and fires every timer whose deadline +// has passed in deadline order, yielding after each firing so goroutines +// blocked on timer.C() run before subsequent timers fire. +func (c *FakeClock) Advance(d time.Duration) { + c.mu.Lock() + target := c.now.Add(d) + c.now = target + c.mu.Unlock() + + for { + c.mu.Lock() + bestIdx := -1 + var best *fakeTimer + for i, t := range c.pending { + if t.at.After(target) { + continue + } + if best == nil || t.at.Before(best.at) || (t.at.Equal(best.at) && t.seq < best.seq) { + best = t + bestIdx = i + } + } + if best == nil { + c.mu.Unlock() + break + } + c.pending = append(c.pending[:bestIdx], c.pending[bestIdx+1:]...) + c.blocked.Store(int32(len(c.pending))) + best.stopped = true + best.ch <- best.at + c.mu.Unlock() + + // Yield so a goroutine blocked on <-best.C() wakes and runs its handler + // before the next timer in deadline order is fired. + for i := 0; i < 64; i++ { + runtime.Gosched() + if len(best.ch) == 0 { + break + } + } + for i := 0; i < 16; i++ { + runtime.Gosched() + } + } +} + +func (t *fakeTimer) C() <-chan time.Time { return t.ch } + +func (t *fakeTimer) Stop() { + c := t.clock + c.mu.Lock() + if !t.stopped { + t.stopped = true + for i, p := range c.pending { + if p == t { + c.pending = append(c.pending[:i], c.pending[i+1:]...) + break + } + } + c.blocked.Store(int32(len(c.pending))) + } + select { + case <-t.ch: + default: + } + c.mu.Unlock() +} diff --git a/internal/livedoor/clock_test.go b/internal/livedoor/clock_test.go new file mode 100644 index 0000000000..36159ca903 --- /dev/null +++ b/internal/livedoor/clock_test.go @@ -0,0 +1,68 @@ +package livedoor + +import ( + "testing" + "time" +) + +// TestFakeClockFiresTimersInDeadlineOrderAndStopPreventsFiring verifies contract +// (clock): FakeClock fires due timers in deadline order on Advance and Stop +// prevents a timer from firing. +func TestFakeClockFiresTimersInDeadlineOrderAndStopPreventsFiring(t *testing.T) { + start := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) + fc := NewFakeClock(start) + + t30 := fc.NewTimer(30 * time.Millisecond) + t10 := fc.NewTimer(10 * time.Millisecond) + t20Stopped := fc.NewTimer(20 * time.Millisecond) + t25 := fc.NewTimer(25 * time.Millisecond) + + if got := fc.BlockedTimers(); got != 4 { + t.Fatalf("BlockedTimers() = %d, want 4", got) + } + t20Stopped.Stop() + if got := fc.BlockedTimers(); got != 3 { + t.Fatalf("BlockedTimers() after Stop = %d, want 3", got) + } + + // THE ORDER IS PROVED BY STEPPING, NOT BY GOROUTINES RACING TO RECORD IT. + // Each Advance releases only the timers that are due, so a timer that fires + // early shows up as a value on a channel that should still be empty, with no + // scheduler in the way. + fired := func(tm Timer) (time.Time, bool) { + select { + case at := <-tm.C(): + return at, true + default: + return time.Time{}, false + } + } + fc.Advance(10 * time.Millisecond) + if at, ok := fired(t10); !ok || !at.Equal(start.Add(10*time.Millisecond)) { + t.Fatalf("after 10ms the 10ms timer = (%v, %v), want it fired at its own deadline", at, ok) + } + if _, ok := fired(t25); ok { + t.Fatal("the 25ms timer fired at 10ms") + } + if _, ok := fired(t30); ok { + t.Fatal("the 30ms timer fired at 10ms") + } + fc.Advance(15 * time.Millisecond) + if at, ok := fired(t25); !ok || !at.Equal(start.Add(25*time.Millisecond)) { + t.Fatalf("after 25ms the 25ms timer = (%v, %v), want it fired at its own deadline", at, ok) + } + if _, ok := fired(t30); ok { + t.Fatal("the 30ms timer fired at 25ms") + } + fc.Advance(15 * time.Millisecond) + if at, ok := fired(t30); !ok || !at.Equal(start.Add(30*time.Millisecond)) { + t.Fatalf("after 40ms the 30ms timer = (%v, %v), want it fired at its own deadline", at, ok) + } + if _, ok := fired(t20Stopped); ok { + t.Fatal("a stopped timer fired on Advance") + } + + if !fc.Now().Equal(start.Add(40 * time.Millisecond)) { + t.Fatalf("Now() = %v, want %v", fc.Now(), start.Add(40*time.Millisecond)) + } +} diff --git a/internal/livedoor/direct.go b/internal/livedoor/direct.go new file mode 100644 index 0000000000..0360513677 --- /dev/null +++ b/internal/livedoor/direct.go @@ -0,0 +1,152 @@ +package livedoor + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" +) + +// The two roads a live view can travel. The HOST decides which one a tunnel is +// from the byte that opened it and the prologue it completed, never from +// anything a viewer says, and both sides report it in the road word a person +// sees. +const ( + RoadRelay = "relay" + RoadDirect = "direct" +) + +// SignalVersion is the only version of the signalling payload there is. +const SignalVersion = 1 + +// What a Signal says. An offer, an answer and the candidates that follow them +// are the whole of how two computers find a path to each other; `end` abandons +// an attempt; `refuse` is the host saying no before it has allocated anything. +const ( + SignalOffer = "offer" + SignalAnswer = "answer" + SignalCandidate = "cand" + SignalEnd = "end" + SignalRefuse = "refuse" +) + +// Why a host refuses an offer. They are closed words and nobody speaks them to +// a person: a refused offer leaves the view on the relay with no sentence. +const ( + RefuseRelayOnly = "relay-only" + RefuseBusy = "busy" + RefuseOff = "off" +) + +// Signal is the JSON payload of one OpSignal frame. It travels on channel 0 of +// a relay tunnel that is already open, so the relay carries it as ciphertext +// inside the Noise records of that tunnel and learns only that a few records +// crossed. +// +// ID is a random attempt id that both sides echo, so a frame that belongs to an +// attempt that has already ended is dropped instead of being fed to a new one. +// A candidate carries its address line in C, its media id in Mid and its index +// in Idx; a candidate with End set and an empty C says there are no more. +type Signal struct { + V int `json:"v"` + T string `json:"t"` + ID string `json:"id,omitempty"` + SDP string `json:"sdp,omitempty"` + C string `json:"c,omitempty"` + Mid string `json:"mid,omitempty"` + Idx int `json:"idx,omitempty"` + End bool `json:"end,omitempty"` + Reason string `json:"reason,omitempty"` +} + +// maxSignalIDBytes bounds an attempt id: sixteen hex digits is what a sender +// makes, and this leaves room for a longer one without letting a peer park a +// large string in every frame. +const maxSignalIDBytes = 64 + +// ErrSignal reports a signalling payload that cannot be understood or that is +// over its size limit. +var ErrSignal = errors.New("livedoor: unusable signal") + +// EncodeSignal writes a signal in the form an OpSignal frame carries. A signal +// over SignalMax is an error, because the receiver would close the link on it. +func EncodeSignal(s Signal) ([]byte, error) { + if s.V == 0 { + s.V = SignalVersion + } + payload, err := json.Marshal(s) + if err != nil { + return nil, err + } + if len(payload) > SignalMax { + return nil, fmt.Errorf("%w: %d bytes is over the %d-byte limit", ErrSignal, len(payload), SignalMax) + } + return payload, nil +} + +// DecodeSignal reads one OpSignal payload. It refuses a payload over SignalMax, +// one that is not a single JSON object, an unknown version and an unknown kind, +// so everything past this point sees only a well-formed signal. +func DecodeSignal(payload []byte) (Signal, error) { + var s Signal + if len(payload) > SignalMax { + return s, fmt.Errorf("%w: %d bytes is over the %d-byte limit", ErrSignal, len(payload), SignalMax) + } + decoder := json.NewDecoder(bytes.NewReader(payload)) + if err := decoder.Decode(&s); err != nil { + return Signal{}, fmt.Errorf("%w: %v", ErrSignal, err) + } + if decoder.More() { + return Signal{}, fmt.Errorf("%w: more than one value", ErrSignal) + } + if s.V != SignalVersion { + return Signal{}, fmt.Errorf("%w: version %d", ErrSignal, s.V) + } + switch s.T { + case SignalOffer, SignalAnswer, SignalCandidate, SignalEnd, SignalRefuse: + default: + return Signal{}, fmt.Errorf("%w: kind %q", ErrSignal, s.T) + } + if len(s.ID) > maxSignalIDBytes { + return Signal{}, fmt.Errorf("%w: attempt id too long", ErrSignal) + } + return s, nil +} + +// Signaller sends one OpSignal frame on channel 0 of THE relay link it belongs +// to. It is how a direct-road implementation talks to the other computer +// before a direct path exists. +type Signaller interface { + Send(payload []byte) error +} + +// DirectHost is the host half of the direct road, implemented outside this +// package (by internal/directroad, through a seam syncsetup installs) so this +// package imports no peer-to-peer library. +// +// Offered is called with the raw offer payload of a viewer the door has already +// authenticated. It returns the session that will carry the rest of that +// attempt, or nil to say no, which the router answers with a `refuse` signal +// before anything has been allocated for the peer. +type DirectHost interface { + Offered(ctx context.Context, peer Peer, offer []byte, s Signaller) DirectSession +} + +// DirectSession is one pending attempt on the host. Deliver is handed each +// later signal payload of the same attempt in the order it arrived, and Close +// ends the attempt and releases everything it holds. Both must be safe to call +// after the attempt has finished by itself. +type DirectSession interface { + Deliver(payload []byte) + Close() +} + +// DirectConfig is what a viewer link needs to try the direct road. Dial builds +// the peer-to-peer connection (signalling through s), finishes the tunnel's +// handshake and device hello, and returns a READY tunnel: the same contract a +// link's own Dial has for the relay road. +type DirectConfig struct { + Dial func(ctx context.Context, s Signaller) (io.ReadWriteCloser, error) +} diff --git a/internal/livedoor/door_test.go b/internal/livedoor/door_test.go new file mode 100644 index 0000000000..75de4fcff9 --- /dev/null +++ b/internal/livedoor/door_test.go @@ -0,0 +1,501 @@ +package livedoor + +import ( + "bytes" + "context" + "encoding/json" + "net" + "testing" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" +) + +// TestAPairedViewerOpensAChatAnotherProcessHoldsAndSeesItsTail verifies contract +// V1 (router half): opening a channel to a held chat delivers the holder's +// welcome followed by its replayed event lines in order, and the rewritten +// hello the holder receives has Join:true, New:false, Back:true, the +// authenticated Remote stamp from Peer, the holder's Session and Workspace, and +// the viewer's Resume and ClientID preserved while overriding any spoofed +// viewer values for Remote, Watch, New, or Session. +func TestAPairedViewerOpensAChatAnotherProcessHoldsAndSeesItsTail(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + gotHelloCh := make(chan remote.Hello, 1) + wantSession := "/work/state/v3/projects/p/chat-v1/transcript.jsonl" + wantWorkspace := "/work/project-v1" + + resolver := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.v1.holder", func() { + defer holderSide.Close() + scan := newLineScanner(holderSide, MaxLine) + line, err := scan.ReadLine(FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if err := json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f); err != nil { + return + } + var h remote.Hello + if err := json.Unmarshal(f.Payload, &h); err != nil { + return + } + gotHelloCh <- h + + welcomePayload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: h.Workspace, + SessionFile: h.Session, + Model: "model-v1", + Title: "Tail Conversation", + Remote: h.Remote, + }) + welcomeFrame, _ := json.Marshal(remote.Frame{ + Kind: "welcome", + Payload: welcomePayload, + }) + if _, err := holderSide.Write(append(welcomeFrame, '\n')); err != nil { + return + } + + for i, text := range []string{"tail-part-1", "tail-part-2", "tail-part-3"} { + evPayload, _ := json.Marshal(remote.WireEvent(session.Event{ + Kind: session.EventTextDelta, + Text: text, + })) + evFrame, _ := json.Marshal(remote.Frame{ + Kind: "event", + ID: 1, + Seq: uint64(i + 1), + Payload: evPayload, + }) + if _, err := holderSide.Write(append(evFrame, '\n')); err != nil { + return + } + } + }) + return routerSide, Route{ + Kind: "daemon", + PID: 5001, + Session: wantSession, + Workspace: wantWorkspace, + }, nil + }) + + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + + // Peer is watch-only (Drive:false), while the viewer attempts to spoof + // Drive:true, Watch:false, New:true, and Session:"/etc/x" in its Hello. + peer := Peer{ + Device: "dev-paired-v1", + Label: "airbook", + Permit: pair.Permit{Watch: true, Drive: false}, + Class: pair.ClassLegacy, + } + guard.Go("livedoor.test.v1.serve", func() { + _ = Serve(ctx, hConn, peer, ServeConfig{ + Resolver: resolver, + Host: "studio", + Road: "relay", + }) + }) + + vMux := NewMux(vConn, Viewer, MuxConfig{}) + t.Cleanup(func() { _ = vMux.Close() }) + ack, err := vMux.WaitHelloAck(ctx) + if err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + if !ack.Watch || ack.Drive || ack.Road != "relay" { + t.Fatalf("HelloAck = %+v, want Watch=true Drive=false Road=relay", ack) + } + + vCh, err := vMux.Open(ctx, "chat-v1") + if err != nil { + t.Fatalf("Open(chat-v1) failed: %v", err) + } + + spoofedHello := remote.Hello{ + Version: remote.Version, + Workspace: "/etc/shadow-dir", + Session: "/etc/x", + SessionInstance: "inst-42", + ClientID: "client-keep-me", + Surface: "airbook-surface", + Encodings: []string{"gzip"}, + Resume: []remote.StreamCursor{{Stream: 9, Seq: 4}}, + Join: false, + New: true, + Watch: false, + Back: false, + Remote: &remote.RemoteViewer{ + Device: "spoofed-root", + Label: "spoofed", + Watch: true, + Drive: true, + Road: "local", + }, + } + hPayload, _ := json.Marshal(spoofedHello) + hLine, _ := json.Marshal(remote.Frame{Kind: "hello", Payload: hPayload}) + if _, err := vCh.Write(append(hLine, '\n')); err != nil { + t.Fatalf("writing viewer hello failed: %v", err) + } + + gotHello := <-gotHelloCh + if !gotHello.Join || gotHello.New || !gotHello.Back || !gotHello.Watch { + t.Fatalf("rewritten hello flags: Join=%v New=%v Back=%v Watch=%v, want Join=true New=false Back=true Watch=true", + gotHello.Join, gotHello.New, gotHello.Back, gotHello.Watch) + } + if gotHello.Session != wantSession || gotHello.Workspace != wantWorkspace { + t.Fatalf("rewritten hello Session=%q Workspace=%q, want %q and %q", + gotHello.Session, gotHello.Workspace, wantSession, wantWorkspace) + } + wantRemote := remote.RemoteViewer{ + Device: peer.Device, + Label: peer.Label, + Watch: true, + Drive: false, + Road: "relay", + } + if gotHello.Remote == nil || *gotHello.Remote != wantRemote { + t.Fatalf("rewritten hello Remote = %+v, want %+v", gotHello.Remote, wantRemote) + } + if gotHello.ClientID != "client-keep-me" || gotHello.SessionInstance != "inst-42" || gotHello.Surface != "airbook-surface" || gotHello.Version != remote.Version { + t.Fatalf("rewritten hello lost pass-through fields: %+v", gotHello) + } + if len(gotHello.Resume) != 1 || gotHello.Resume[0] != (remote.StreamCursor{Stream: 9, Seq: 4}) { + t.Fatalf("rewritten hello Resume = %+v, want [{Stream:9 Seq:4}]", gotHello.Resume) + } + if len(gotHello.Encodings) != 1 || gotHello.Encodings[0] != "gzip" { + t.Fatalf("rewritten hello Encodings = %+v, want [gzip]", gotHello.Encodings) + } + + vScan := newLineScanner(vCh, MaxLine) + wLine, err := vScan.ReadLine(MaxLine) + if err != nil { + t.Fatalf("reading welcome line failed: %v", err) + } + var wFrame remote.Frame + if err := json.Unmarshal(bytes.TrimRight(wLine, "\r\n"), &wFrame); err != nil || wFrame.Kind != "welcome" { + t.Fatalf("first reply frame = %+v (err=%v), want welcome", wFrame, err) + } + + wantTexts := []string{"tail-part-1", "tail-part-2", "tail-part-3"} + for i, wantText := range wantTexts { + evLine, err := vScan.ReadLine(MaxLine) + if err != nil { + t.Fatalf("reading event %d failed: %v", i+1, err) + } + var evFrame remote.Frame + if err := json.Unmarshal(bytes.TrimRight(evLine, "\r\n"), &evFrame); err != nil { + t.Fatalf("unmarshaling event %d failed: %v", i+1, err) + } + if evFrame.Kind != "event" || evFrame.Seq != uint64(i+1) { + t.Fatalf("event %d frame = {Kind:%q Seq:%d}, want event Seq=%d", i+1, evFrame.Kind, evFrame.Seq, i+1) + } + var ew remote.EventWire + if err := json.Unmarshal(evFrame.Payload, &ew); err != nil || ew.Text != wantText { + t.Fatalf("event %d Text = %q (err=%v), want %q", i+1, ew.Text, err, wantText) + } + } +} + +// TestATurnRunningOnTheHostReachesTheViewerBeforeItEnds verifies contract V2: +// when the holder emits a live turn event line and then blocks on an unclosed +// gate before finishing the turn, the viewer reads the event line while the +// turn gate is still closed. +func TestATurnRunningOnTheHostReachesTheViewerBeforeItEnds(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + turnGate := make(chan struct{}) + defer close(turnGate) + + resolver := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.v2.holder", func() { + defer holderSide.Close() + scan := newLineScanner(holderSide, MaxLine) + line, err := scan.ReadLine(FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f) != nil { + return + } + var h remote.Hello + if json.Unmarshal(f.Payload, &h) != nil { + return + } + wPayload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: h.Workspace, + SessionFile: h.Session, + Live: 1, + Remote: h.Remote, + }) + wFrame, _ := json.Marshal(remote.Frame{Kind: "welcome", Payload: wPayload}) + if _, err := holderSide.Write(append(wFrame, '\n')); err != nil { + return + } + + deltaPayload, _ := json.Marshal(remote.WireEvent(session.Event{ + Kind: session.EventTextDelta, + Text: "streaming-before-turn-ends", + })) + deltaFrame, _ := json.Marshal(remote.Frame{ + Kind: "event", + ID: 1, + Seq: 1, + Payload: deltaPayload, + }) + if _, err := holderSide.Write(append(deltaFrame, '\n')); err != nil { + return + } + + // Wait on turnGate before ending the turn. + <-turnGate + }) + return routerSide, Route{ + Kind: "daemon", + PID: 5002, + Session: "/work/v2/transcript.jsonl", + Workspace: "/work/v2", + }, nil + }) + + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + peer := Peer{ + Device: "dev-v2", + Label: "laptop", + Permit: pair.Permit{Watch: true, Drive: true}, + } + guard.Go("livedoor.test.v2.serve", func() { + _ = Serve(ctx, hConn, peer, ServeConfig{ + Resolver: resolver, + Host: "workstation", + Road: "relay", + }) + }) + + vMux := NewMux(vConn, Viewer, MuxConfig{}) + t.Cleanup(func() { _ = vMux.Close() }) + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + vCh, err := vMux.Open(ctx, "chat-v2") + if err != nil { + t.Fatalf("Open(chat-v2) failed: %v", err) + } + hPayload, _ := json.Marshal(remote.Hello{Version: remote.Version}) + hLine, _ := json.Marshal(remote.Frame{Kind: "hello", Payload: hPayload}) + if _, err := vCh.Write(append(hLine, '\n')); err != nil { + t.Fatalf("writing hello failed: %v", err) + } + + vScan := newLineScanner(vCh, MaxLine) + if _, err := vScan.ReadLine(MaxLine); err != nil { + t.Fatalf("reading welcome failed: %v", err) + } + + // Read the event while turnGate is still closed. + evLine, err := vScan.ReadLine(MaxLine) + if err != nil { + t.Fatalf("reading mid-turn event failed: %v", err) + } + select { + case <-turnGate: + t.Fatal("turnGate was already open when event arrived") + default: + } + var evFrame remote.Frame + if err := json.Unmarshal(bytes.TrimRight(evLine, "\r\n"), &evFrame); err != nil || evFrame.Kind != "event" { + t.Fatalf("mid-turn frame = %+v (err=%v), want event", evFrame, err) + } + var ew remote.EventWire + if err := json.Unmarshal(evFrame.Payload, &ew); err != nil || ew.Text != "streaming-before-turn-ends" { + t.Fatalf("mid-turn EventWire.Text = %q (err=%v), want %q", ew.Text, err, "streaming-before-turn-ends") + } +} + +// TestAWatchOnlyPeerIsRefusedCallsThatTypeAndToldWhy verifies contract V11 +// (router half): a peer with Permit{Watch:true, Drive:false} is stamped with +// Drive:false, a Submit call is intercepted at the router without reaching the +// holder and answered with a result frame carrying the same call ID and +// remote.GuestRefusal(host, "Submit", false), and an allowed read call (Ping) +// is forwarded to the holder. +func TestAWatchOnlyPeerIsRefusedCallsThatTypeAndToldWhy(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + const hostName = "mini-server" + gotStampCh := make(chan remote.RemoteViewer, 1) + holderCalls := make(chan remote.Frame, 4) + + resolver := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.v11.holder", func() { + defer holderSide.Close() + scan := newLineScanner(holderSide, MaxLine) + line, err := scan.ReadLine(FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f) != nil { + return + } + var h remote.Hello + if json.Unmarshal(f.Payload, &h) != nil || h.Remote == nil { + return + } + gotStampCh <- *h.Remote + + wPayload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: h.Workspace, + SessionFile: h.Session, + Remote: h.Remote, + }) + wFrame, _ := json.Marshal(remote.Frame{Kind: "welcome", Payload: wPayload}) + if _, err := holderSide.Write(append(wFrame, '\n')); err != nil { + return + } + + for { + cLine, err := scan.ReadLine(MaxLine) + if err != nil { + return + } + var call remote.Frame + if json.Unmarshal(bytes.TrimRight(cLine, "\r\n"), &call) == nil { + holderCalls <- call + resFrame, _ := json.Marshal(remote.Frame{ + Kind: "result", + ID: call.ID, + }) + _, _ = holderSide.Write(append(resFrame, '\n')) + } + } + }) + return routerSide, Route{ + Kind: "daemon", + PID: 5003, + Session: "/work/v11/transcript.jsonl", + Workspace: "/work/v11", + }, nil + }) + + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + peer := Peer{ + Device: "dev-watch-only", + Label: "ipad", + Permit: pair.Permit{Watch: true, Drive: false}, + } + guard.Go("livedoor.test.v11.serve", func() { + _ = Serve(ctx, hConn, peer, ServeConfig{ + Resolver: resolver, + Host: hostName, + Road: "relay", + }) + }) + + vMux := NewMux(vConn, Viewer, MuxConfig{}) + t.Cleanup(func() { _ = vMux.Close() }) + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + vCh, err := vMux.Open(ctx, "chat-v11") + if err != nil { + t.Fatalf("Open(chat-v11) failed: %v", err) + } + hPayload, _ := json.Marshal(remote.Hello{Version: remote.Version}) + hLine, _ := json.Marshal(remote.Frame{Kind: "hello", Payload: hPayload}) + if _, err := vCh.Write(append(hLine, '\n')); err != nil { + t.Fatalf("writing hello failed: %v", err) + } + + vScan := newLineScanner(vCh, MaxLine) + if _, err := vScan.ReadLine(MaxLine); err != nil { + t.Fatalf("reading welcome failed: %v", err) + } + + stamp := <-gotStampCh + if !stamp.Watch || stamp.Drive { + t.Fatalf("holder saw stamp %+v, want Watch=true Drive=false", stamp) + } + + // 1. Send a disallowed Submit call (ID 41) and an allowed Ping call (ID 42). + submitCall, _ := json.Marshal(remote.Frame{ + Kind: "call", + ID: 41, + Method: remote.MethodSubmit, + }) + if _, err := vCh.Write(append(submitCall, '\n')); err != nil { + t.Fatalf("writing Submit call failed: %v", err) + } + + res1Line, err := vScan.ReadLine(MaxLine) + if err != nil { + t.Fatalf("reading Submit refusal result failed: %v", err) + } + var res1 remote.Frame + if err := json.Unmarshal(bytes.TrimRight(res1Line, "\r\n"), &res1); err != nil { + t.Fatalf("unmarshaling Submit result failed: %v", err) + } + wantRefusal := remote.GuestRefusal(hostName, remote.MethodSubmit, false) + if res1.Kind != "result" || res1.ID != 41 || res1.Error != wantRefusal { + t.Fatalf("Submit result = %+v, want Kind=result ID=41 Error=%q", res1, wantRefusal) + } + + // 2. Send an allowed Ping call (ID 42) and verify the holder receives ONLY Ping. + pingCall, _ := json.Marshal(remote.Frame{ + Kind: "call", + ID: 42, + Method: remote.MethodPing, + }) + if _, err := vCh.Write(append(pingCall, '\n')); err != nil { + t.Fatalf("writing Ping call failed: %v", err) + } + + res2Line, err := vScan.ReadLine(MaxLine) + if err != nil { + t.Fatalf("reading Ping result failed: %v", err) + } + var res2 remote.Frame + if err := json.Unmarshal(bytes.TrimRight(res2Line, "\r\n"), &res2); err != nil { + t.Fatalf("unmarshaling Ping result failed: %v", err) + } + if res2.Kind != "result" || res2.ID != 42 || res2.Error != "" { + t.Fatalf("Ping result = %+v, want Kind=result ID=42 Error=\"\"", res2) + } + + forwarded := <-holderCalls + if forwarded.ID != 42 || forwarded.Method != remote.MethodPing { + t.Fatalf("holder received call %+v, want only Ping (ID 42), never Submit", forwarded) + } + select { + case extra := <-holderCalls: + t.Fatalf("holder received unexpected extra call: %+v", extra) + default: + } +} diff --git a/internal/livedoor/flow_test.go b/internal/livedoor/flow_test.go new file mode 100644 index 0000000000..ac40095079 --- /dev/null +++ b/internal/livedoor/flow_test.go @@ -0,0 +1,538 @@ +package livedoor + +import ( + "bytes" + "context" + "encoding/json" + "net" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" +) + +// TestAViewerThatStopsReadingIsResetAndOtherViewersAndMoveAreNotStalled +// verifies contract V17: when two viewers on two tunnels attach to a stub +// holder that streams a burst of events and viewer A never reads, A's channel +// is Reset with reason lagging, A's holder connection is closed, and viewer B +// receives all of its lines at full rate without the stub holder's writes to B +// ever stalling behind A. +func TestAViewerThatStopsReadingIsResetAndOtherViewersAndMoveAreNotStalled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + lim := DefaultLimits() + lim.ChannelWindow = 16 << 10 + lim.LinkWindow = 64 << 10 + lim.QueueMax = 32 << 10 + lim.Rate = 64 << 20 + lim.RateBurst = 64 << 20 + + const totalLines = 32 + payloadText := strings.Repeat("x", 2400) + + var ( + aHolderClosed atomic.Bool + aWriteAttempts atomic.Int32 + bWriteAttempts atomic.Int32 + bRead atomic.Int32 + holderMu sync.Mutex + holderSideA net.Conn + holderSideB net.Conn + bothAttached = make(chan struct{}) + attachedCount int + ) + + acceptOnStubHolder := func(isA bool) net.Conn { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.v17.handshake", func() { + scan := newLineScanner(holderSide, lim.MaxLine) + line, err := scan.ReadLine(lim.FirstLineMax) + if err != nil { + _ = holderSide.Close() + return + } + var f remote.Frame + if json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f) != nil { + _ = holderSide.Close() + return + } + var h remote.Hello + if json.Unmarshal(f.Payload, &h) != nil { + _ = holderSide.Close() + return + } + wPayload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: h.Workspace, + SessionFile: h.Session, + Remote: h.Remote, + }) + wFrame, _ := json.Marshal(remote.Frame{Kind: "welcome", Payload: wPayload}) + if _, err := holderSide.Write(append(wFrame, '\n')); err != nil { + _ = holderSide.Close() + return + } + + holderMu.Lock() + if isA { + holderSideA = holderSide + } else { + holderSideB = holderSide + } + attachedCount++ + if attachedCount == 2 { + close(bothAttached) + } + holderMu.Unlock() + }) + return routerSide + } + + resolverA := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + return acceptOnStubHolder(true), Route{ + Kind: "daemon", + PID: 6001, + Session: "/work/v17/transcript.jsonl", + Workspace: "/work/v17", + }, nil + }) + resolverB := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + return acceptOnStubHolder(false), Route{ + Kind: "daemon", + PID: 6001, + Session: "/work/v17/transcript.jsonl", + Workspace: "/work/v17", + }, nil + }) + + // Tunnel A: viewer A never reads from its channel after sending hello. + vConnA, hConnA := net.Pipe() + t.Cleanup(func() { + _ = vConnA.Close() + _ = hConnA.Close() + }) + guard.Go("livedoor.test.v17.serveA", func() { + _ = Serve(ctx, hConnA, Peer{ + Device: "dev-a", + Label: "slow-viewer", + Permit: pair.Permit{Watch: true, Drive: true}, + }, ServeConfig{ + Resolver: resolverA, + Limits: lim, + Host: "workstation", + Road: "relay", + }) + }) + vMuxA := NewMux(vConnA, Viewer, MuxConfig{Limits: lim}) + t.Cleanup(func() { _ = vMuxA.Close() }) + if _, err := vMuxA.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck(A) failed: %v", err) + } + vChA, err := vMuxA.Open(ctx, "chat-v17") + if err != nil { + t.Fatalf("Open(A) failed: %v", err) + } + + // Tunnel B: viewer B reads all events at full rate. + vConnB, hConnB := net.Pipe() + t.Cleanup(func() { + _ = vConnB.Close() + _ = hConnB.Close() + }) + guard.Go("livedoor.test.v17.serveB", func() { + _ = Serve(ctx, hConnB, Peer{ + Device: "dev-b", + Label: "fast-viewer", + Permit: pair.Permit{Watch: true, Drive: true}, + }, ServeConfig{ + Resolver: resolverB, + Limits: lim, + Host: "workstation", + Road: "relay", + }) + }) + vMuxB := NewMux(vConnB, Viewer, MuxConfig{Limits: lim}) + t.Cleanup(func() { _ = vMuxB.Close() }) + if _, err := vMuxB.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck(B) failed: %v", err) + } + vChB, err := vMuxB.Open(ctx, "chat-v17") + if err != nil { + t.Fatalf("Open(B) failed: %v", err) + } + + hPayload, _ := json.Marshal(remote.Hello{Version: remote.Version}) + hLine, _ := json.Marshal(remote.Frame{Kind: "hello", Payload: hPayload}) + if _, err := vChA.Write(append(hLine, '\n')); err != nil { + t.Fatalf("Write hello(A) failed: %v", err) + } + if _, err := vChB.Write(append(hLine, '\n')); err != nil { + t.Fatalf("Write hello(B) failed: %v", err) + } + + scanB := newLineScanner(vChB, lim.MaxLine) + if _, err := scanB.ReadLine(lim.MaxLine); err != nil { + t.Fatalf("B reading welcome failed: %v", err) + } + <-bothAttached + + // One shared stub holder fans out the stream to both A and B. + aClosedAck := make(chan struct{}) + guard.Go("livedoor.test.v17.sharedHolderFanout", func() { + defer func() { + _ = holderSideA.Close() + _ = holderSideB.Close() + }() + aAlive := true + for seq := 1; seq <= totalLines; seq++ { + // Pace the producer against B's consumer so a loaded scheduler cannot + // starve B's reader goroutine past the 32 KiB outbound queue while A + // never reads and still overflows its 48 KiB window-plus-queue cap. + paceDeadline := time.Now().Add(3 * time.Second) + for int32(seq)-bRead.Load() > 4 { + if ctx.Err() != nil || time.Now().After(paceDeadline) { + return + } + runtime.Gosched() + } + evPayload, _ := json.Marshal(remote.WireEvent(session.Event{ + Kind: session.EventTextDelta, + Text: payloadText, + })) + evFrame, _ := json.Marshal(remote.Frame{ + Kind: "event", + ID: 1, + Seq: uint64(seq), + Payload: evPayload, + }) + raw := append(evFrame, '\n') + if aAlive { + aWriteAttempts.Add(1) + if _, err := holderSideA.Write(raw); err != nil { + aAlive = false + aHolderClosed.Store(true) + close(aClosedAck) + } + } + bWriteAttempts.Add(1) + if _, err := holderSideB.Write(raw); err != nil { + return + } + for i := 0; i < 8; i++ { + runtime.Gosched() + } + } + if aAlive { + var drain [64]byte + _, _ = holderSideA.Read(drain[:]) + aHolderClosed.Store(true) + close(aClosedAck) + } + }) + + for seq := 1; seq <= totalLines; seq++ { + line, err := scanB.ReadLine(lim.MaxLine) + if err != nil { + t.Fatalf("B reading event %d failed: %v", seq, err) + } + var f remote.Frame + if err := json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f); err != nil || f.Seq != uint64(seq) { + t.Fatalf("B event %d = %+v (err=%v), want Seq=%d", seq, f, err, seq) + } + bRead.Store(int32(seq)) + } + + <-vChA.Done() + if got := vChA.Reason(); got != ReasonLagging { + t.Fatalf("lagging viewer A channel Reason() = %q, want %q", got, ReasonLagging) + } + var buf [64]byte + _, readErrA := vChA.Read(buf[:]) + if got := reasonOf(readErrA); got != ReasonLagging { + t.Fatalf("vChA.Read after lagging reset returned %v (reason=%q), want %q", readErrA, got, ReasonLagging) + } + <-aClosedAck + if !aHolderClosed.Load() { + t.Fatal("holder conn for lagging viewer A was not closed") + } + if gotB := bWriteAttempts.Load(); gotB != totalLines { + t.Fatalf("bWriteAttempts = %d, want %d", gotB, totalLines) + } + if gotA := aWriteAttempts.Load(); gotA >= totalLines { + t.Fatalf("aWriteAttempts = %d, want < %d (A holder conn must close before stream ends)", gotA, totalLines) + } +} + +func makeFrameLineOfExactLength(t *testing.T, kind, method string, targetLen int) []byte { + t.Helper() + baseFrame := remote.Frame{ + Kind: kind, + ID: 1, + Method: method, + Payload: json.RawMessage(`""`), + } + baseBytes, err := json.Marshal(baseFrame) + if err != nil { + t.Fatalf("Marshal baseFrame failed: %v", err) + } + padLen := targetLen - len(baseBytes) + if padLen < 0 { + t.Fatalf("targetLen %d smaller than base frame %d", targetLen, len(baseBytes)) + } + paddedPayload, err := json.Marshal(strings.Repeat("p", padLen)) + if err != nil { + t.Fatalf("Marshal paddedPayload failed: %v", err) + } + fullFrame := remote.Frame{ + Kind: kind, + ID: 1, + Method: method, + Payload: paddedPayload, + } + line, err := json.Marshal(fullFrame) + if err != nil { + t.Fatalf("Marshal fullFrame failed: %v", err) + } + if len(line) != targetLen { + t.Fatalf("constructed line length = %d, want %d", len(line), targetLen) + } + return append(line, '\n') +} + +// TestALineOverTheCapResetsTheChannelInBothDirections verifies contract V18: +// a line of exactly MaxLine bytes passes in both directions, while a viewer +// line of MaxLine+1 bytes and a holder line of MaxLine+1 bytes each reset the +// channel with frame-too-large. +func TestALineOverTheCapResetsTheChannelInBothDirections(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + lim := DefaultLimits() + lim.Rate = 64 << 20 + lim.RateBurst = 64 << 20 + + // Holder echoes allowed calls or emits a line of a requested length. + nextHolderLineLen := make(chan int, 4) + resolver := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.v18.holder", func() { + defer holderSide.Close() + scan := newLineScanner(holderSide, lim.MaxLine+64) + line, err := scan.ReadLine(lim.FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f) != nil { + return + } + var h remote.Hello + if json.Unmarshal(f.Payload, &h) != nil { + return + } + wPayload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: h.Workspace, + SessionFile: h.Session, + Remote: h.Remote, + }) + wFrame, _ := json.Marshal(remote.Frame{Kind: "welcome", Payload: wPayload}) + if _, err := holderSide.Write(append(wFrame, '\n')); err != nil { + return + } + + for { + cLine, err := scan.ReadLine(lim.MaxLine + 64) + if err != nil { + return + } + var call remote.Frame + if json.Unmarshal(bytes.TrimRight(cLine, "\r\n"), &call) != nil { + return + } + replyLen := len(cLine) - 1 + select { + case custom := <-nextHolderLineLen: + replyLen = custom + default: + } + outLine := makeFrameLineOfExactLength(t, "result", "", replyLen) + if _, err := holderSide.Write(outLine); err != nil { + return + } + } + }) + return routerSide, Route{ + Kind: "daemon", + PID: 6002, + Session: "/work/v18/transcript.jsonl", + Workspace: "/work/v18", + }, nil + }) + + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + guard.Go("livedoor.test.v18.serve", func() { + _ = Serve(ctx, hConn, Peer{ + Device: "dev-v18", + Label: "laptop", + Permit: pair.Permit{Watch: true, Drive: true}, + }, ServeConfig{ + Resolver: resolver, + Limits: lim, + Host: "workstation", + Road: "relay", + }) + }) + + vMux := NewMux(vConn, Viewer, MuxConfig{Limits: lim}) + t.Cleanup(func() { _ = vMux.Close() }) + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + + openWithHello := func(chat string) (*Channel, *lineScanner) { + ch, err := vMux.Open(ctx, chat) + if err != nil { + t.Fatalf("Open(%s) failed: %v", chat, err) + } + hPayload, _ := json.Marshal(remote.Hello{Version: remote.Version}) + hLine, _ := json.Marshal(remote.Frame{Kind: "hello", Payload: hPayload}) + if _, err := ch.Write(append(hLine, '\n')); err != nil { + t.Fatalf("Write hello(%s) failed: %v", chat, err) + } + sc := newLineScanner(ch, lim.MaxLine+64) + if _, err := sc.ReadLine(lim.MaxLine); err != nil { + t.Fatalf("Read welcome(%s) failed: %v", chat, err) + } + return ch, sc + } + + // 1. A line of exactly MaxLine bytes passes in both directions (viewer -> holder + // and holder -> viewer). + ch1, sc1 := openWithHello("chat-exact-cap") + exactCall := makeFrameLineOfExactLength(t, "call", remote.MethodPing, MaxLine) + if _, err := ch1.Write(exactCall); err != nil { + t.Fatalf("writing MaxLine viewer call failed: %v", err) + } + exactReply, err := sc1.ReadLine(MaxLine) + if err != nil { + t.Fatalf("reading MaxLine holder reply failed: %v", err) + } + if gotLen := len(bytes.TrimRight(exactReply, "\r\n")); gotLen != MaxLine { + t.Fatalf("exact MaxLine reply length = %d, want %d", gotLen, MaxLine) + } + + // 2. A viewer line of MaxLine+1 bytes resets the channel with frame-too-large. + overViewerCall := makeFrameLineOfExactLength(t, "call", remote.MethodPing, MaxLine+1) + _, _ = ch1.Write(overViewerCall) + _, err = sc1.ReadLine(MaxLine + 64) + if got := reasonOf(err); got != ReasonFrameTooLarge { + t.Fatalf("viewer MaxLine+1 line ended channel with %v (reason=%q), want %q", err, got, ReasonFrameTooLarge) + } + + // 3. A holder line of MaxLine+1 bytes resets the channel with frame-too-large. + ch2, sc2 := openWithHello("chat-holder-over-cap") + nextHolderLineLen <- MaxLine + 1 + smallCall := makeFrameLineOfExactLength(t, "call", remote.MethodPing, 128) + if _, err := ch2.Write(smallCall); err != nil { + t.Fatalf("writing trigger call failed: %v", err) + } + _, err = sc2.ReadLine(MaxLine + 64) + if got := reasonOf(err); got != ReasonFrameTooLarge { + t.Fatalf("holder MaxLine+1 line ended channel with %v (reason=%q), want %q", err, got, ReasonFrameTooLarge) + } +} + +// TestAFirstLineOverTheLimitIsRefused verifies contract V18: a viewer's first +// line on a channel of FirstLineMax+1 bytes resets the channel with +// frame-too-large and closes the holder connection before anything is written +// to the holder. +func TestAFirstLineOverTheLimitIsRefused(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + lim := DefaultLimits() + lim.Rate = 64 << 20 + lim.RateBurst = 64 << 20 + + var holderReadBytes atomic.Int64 + holderClosed := make(chan struct{}) + + resolver := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.v18.firstline.holder", func() { + defer close(holderClosed) + defer holderSide.Close() + var buf [1024]byte + for { + n, err := holderSide.Read(buf[:]) + if n > 0 { + holderReadBytes.Add(int64(n)) + } + if err != nil { + return + } + } + }) + return routerSide, Route{ + Kind: "daemon", + PID: 6003, + Session: "/work/v18-first/transcript.jsonl", + Workspace: "/work/v18-first", + }, nil + }) + + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + guard.Go("livedoor.test.v18.firstline.serve", func() { + _ = Serve(ctx, hConn, Peer{ + Device: "dev-firstline", + Label: "laptop", + Permit: pair.Permit{Watch: true, Drive: true}, + }, ServeConfig{ + Resolver: resolver, + Limits: lim, + Host: "workstation", + Road: "relay", + }) + }) + + vMux := NewMux(vConn, Viewer, MuxConfig{Limits: lim}) + t.Cleanup(func() { _ = vMux.Close() }) + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + + vCh, err := vMux.Open(ctx, "chat-oversize-hello") + if err != nil { + t.Fatalf("Open failed: %v", err) + } + + oversizeHello := makeFrameLineOfExactLength(t, "hello", "", FirstLineMax+1) + _, _ = vCh.Write(oversizeHello) + + var buf [64]byte + _, readErr := vCh.Read(buf[:]) + if got := reasonOf(readErr); got != ReasonFrameTooLarge { + t.Fatalf("oversize first line readErr = %v (reason=%q), want %q", readErr, got, ReasonFrameTooLarge) + } + <-holderClosed + if got := holderReadBytes.Load(); got != 0 { + t.Fatalf("holder received %d bytes on oversize first line, want 0", got) + } +} diff --git a/internal/livedoor/grants_test.go b/internal/livedoor/grants_test.go new file mode 100644 index 0000000000..d52eae90d9 --- /dev/null +++ b/internal/livedoor/grants_test.go @@ -0,0 +1,332 @@ +package livedoor + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net" + "sync" + "sync/atomic" + "testing" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/remote" +) + +func newEchoStampResolver(onHello func(remote.Hello)) Resolver { + return fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.grants.holder", func() { + defer holderSide.Close() + scan := newLineScanner(holderSide, MaxLine) + line, err := scan.ReadLine(FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f) != nil { + return + } + var h remote.Hello + if json.Unmarshal(f.Payload, &h) != nil { + return + } + if onHello != nil { + onHello(h) + } + wPayload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: h.Workspace, + SessionFile: h.Session, + Remote: h.Remote, + }) + wFrame, _ := json.Marshal(remote.Frame{Kind: "welcome", Payload: wPayload}) + if _, err := holderSide.Write(append(wFrame, '\n')); err != nil { + return + } + _, _ = io.Copy(io.Discard, holderSide) + }) + return routerSide, Route{ + Kind: "daemon", + PID: 7001, + Session: "/work/grants/" + chat + "/transcript.jsonl", + Workspace: "/work/grants", + }, nil + }) +} + +func openAndHandshake(t *testing.T, ctx context.Context, vMux *Mux, chat string) *Channel { + t.Helper() + ch, err := vMux.Open(ctx, chat) + if err != nil { + t.Fatalf("Open(%s) failed: %v", chat, err) + } + hPayload, _ := json.Marshal(remote.Hello{Version: remote.Version}) + hLine, _ := json.Marshal(remote.Frame{Kind: "hello", Payload: hPayload}) + if _, err := ch.Write(append(hLine, '\n')); err != nil { + t.Fatalf("Write hello(%s) failed: %v", chat, err) + } + scan := newLineScanner(ch, MaxLine) + if _, err := scan.ReadLine(MaxLine); err != nil { + t.Fatalf("Read welcome(%s) failed: %v", chat, err) + } + return ch +} + +// TestRemovingADeviceClosesItsOpenLiveViewsAtOnce verifies contract V10: +// Registry.Revoke(device) closes every open channel of that device with reason +// removed, closes its tunnel link, and leaves another device's tunnel and +// channels untouched. +func TestRemovingADeviceClosesItsOpenLiveViewsAtOnce(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + reg := NewRegistry() + resolver := newEchoStampResolver(nil) + + startDevice := func(device string) (*Mux, *Channel, *Channel) { + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + peer := Peer{ + Device: device, + Label: device, + Permit: pair.Permit{Watch: true, Drive: true}, + } + guard.Go("livedoor.test.v10.revoke.serve", func() { + _ = Serve(ctx, hConn, peer, ServeConfig{ + Resolver: resolver, + Registry: reg, + Host: "workstation", + Road: "relay", + }) + }) + vMux := NewMux(vConn, Viewer, MuxConfig{}) + t.Cleanup(func() { _ = vMux.Close() }) + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck(%s) failed: %v", device, err) + } + ch1 := openAndHandshake(t, ctx, vMux, "chat-1") + ch2 := openAndHandshake(t, ctx, vMux, "chat-2") + return vMux, ch1, ch2 + } + + muxA, chA1, chA2 := startDevice("dev-revoke-me") + muxB, chB1, chB2 := startDevice("dev-keep-me") + + reg.Revoke("dev-revoke-me") + + var buf [64]byte + for i, ch := range []*Channel{chA1, chA2} { + _, err := ch.Read(buf[:]) + if got := reasonOf(err); got != ReasonRemoved { + t.Fatalf("revoked device channel %d ended with %v (reason=%q), want %q", i+1, err, got, ReasonRemoved) + } + } + <-muxA.Done() + + select { + case <-muxB.Done(): + t.Fatal("other device's tunnel muxB was closed by Revoke(dev-revoke-me)") + case <-chB1.Done(): + t.Fatal("other device's channel chB1 was closed by Revoke(dev-revoke-me)") + case <-chB2.Done(): + t.Fatal("other device's channel chB2 was closed by Revoke(dev-revoke-me)") + default: + } +} + +// TestTurningWatchOffClosesItsViews verifies contract V10: when a device's +// permit changes to Watch:false and Registry.PermitsChanged is called, every +// open channel ends with permit-changed and the tunnel link closes. +func TestTurningWatchOffClosesItsViews(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + reg := NewRegistry() + var ( + permMu sync.Mutex + permit = pair.Permit{Watch: true, Drive: true} + ) + getPermit := func(string) pair.Permit { + permMu.Lock() + defer permMu.Unlock() + return permit + } + + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + peer := Peer{ + Device: "dev-watch-off", + Label: "laptop", + Permit: permit, + } + guard.Go("livedoor.test.v10.watchoff.serve", func() { + _ = Serve(ctx, hConn, peer, ServeConfig{ + Resolver: newEchoStampResolver(nil), + Registry: reg, + Permit: getPermit, + Host: "workstation", + Road: "relay", + }) + }) + + vMux := NewMux(vConn, Viewer, MuxConfig{}) + t.Cleanup(func() { _ = vMux.Close() }) + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + ch1 := openAndHandshake(t, ctx, vMux, "chat-w1") + ch2 := openAndHandshake(t, ctx, vMux, "chat-w2") + + permMu.Lock() + permit = pair.Permit{Watch: false, Drive: false} + permMu.Unlock() + reg.PermitsChanged(peer.Device) + + var buf [64]byte + for i, ch := range []*Channel{ch1, ch2} { + _, err := ch.Read(buf[:]) + if got := reasonOf(err); got != ReasonPermitChanged { + t.Fatalf("channel %d after Watch:false ended with %v (reason=%q), want %q", i+1, err, got, ReasonPermitChanged) + } + } + <-vMux.Done() +} + +// TestTurningDriveOffResetsItsChannelsAndTheyComeBackWatchOnly verifies +// contract V10: when a device's permit changes to Drive:false and +// Registry.PermitsChanged is called, every open channel is reset with +// permit-changed while keeping the tunnel link open, and a subsequent Open on +// the same tunnel is stamped with Drive:false. +func TestTurningDriveOffResetsItsChannelsAndTheyComeBackWatchOnly(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + reg := NewRegistry() + var ( + permMu sync.Mutex + permit = pair.Permit{Watch: true, Drive: true} + ) + getPermit := func(string) pair.Permit { + permMu.Lock() + defer permMu.Unlock() + return permit + } + + hellos := make(chan remote.Hello, 4) + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + peer := Peer{ + Device: "dev-drive-off", + Label: "laptop", + Permit: permit, + } + guard.Go("livedoor.test.v10.driveoff.serve", func() { + _ = Serve(ctx, hConn, peer, ServeConfig{ + Resolver: newEchoStampResolver(func(h remote.Hello) { hellos <- h }), + Registry: reg, + Permit: getPermit, + Host: "workstation", + Road: "relay", + }) + }) + + vMux := NewMux(vConn, Viewer, MuxConfig{}) + t.Cleanup(func() { _ = vMux.Close() }) + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + ch1 := openAndHandshake(t, ctx, vMux, "chat-d1") + firstHello := <-hellos + if firstHello.Remote == nil || !firstHello.Remote.Drive || firstHello.Watch { + t.Fatalf("initial hello Remote=%+v Watch=%v, want Drive=true Watch=false", firstHello.Remote, firstHello.Watch) + } + + // Turn Drive off and notify the registry. + permMu.Lock() + permit = pair.Permit{Watch: true, Drive: false} + permMu.Unlock() + reg.PermitsChanged(peer.Device) + + var buf [64]byte + _, err := ch1.Read(buf[:]) + if got := reasonOf(err); got != ReasonPermitChanged { + t.Fatalf("ch1 after Drive:false ended with %v (reason=%q), want %q", err, got, ReasonPermitChanged) + } + + // Re-open on the same tunnel; the holder must now see Drive:false and Watch:true. + _ = openAndHandshake(t, ctx, vMux, "chat-d1") + secondHello := <-hellos + if secondHello.Remote == nil || secondHello.Remote.Drive || !secondHello.Remote.Watch || !secondHello.Watch { + t.Fatalf("re-opened hello Remote=%+v Watch=%v, want Remote.Drive=false Remote.Watch=true Watch=true", + secondHello.Remote, secondHello.Watch) + } +} + +// TestAnUnpairedDeviceCannotListOrOpenAChat verifies contract V10: when Serve +// starts for a device whose permit has Watch:false, the viewer receives a +// HELLO_ACK with watch:false, the link closes at once, and the resolver is +// never asked. +func TestAnUnpairedDeviceCannotListOrOpenAChat(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + var resolveCalls atomic.Int32 + resolver := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + resolveCalls.Add(1) + return nil, Route{}, ErrNotRunning + }) + + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + peer := Peer{ + Device: "dev-unallowed", + Label: "stranger", + Permit: pair.Permit{Watch: false, Drive: false}, + } + serveDone := make(chan error, 1) + guard.Go("livedoor.test.v10.unpaired.serve", func() { + serveDone <- Serve(ctx, hConn, peer, ServeConfig{ + Resolver: resolver, + Permit: func(string) pair.Permit { return pair.Permit{Watch: false, Drive: false} }, + Host: "workstation", + Road: "relay", + }) + }) + + vMux := NewMux(vConn, Viewer, MuxConfig{}) + t.Cleanup(func() { _ = vMux.Close() }) + + ack, err := vMux.WaitHelloAck(ctx) + if err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + if ack.Watch || ack.Drive { + t.Fatalf("HelloAck for Watch:false peer = %+v, want Watch=false Drive=false", ack) + } + + <-vMux.Done() + if err := <-serveDone; err != nil { + t.Fatalf("Serve returned %v, want nil", err) + } + if _, openErr := vMux.Open(ctx, "any-chat"); openErr == nil { + t.Fatal("Open on closed unpaired link succeeded, want error") + } + if got := resolveCalls.Load(); got != 0 { + t.Fatalf("resolver was called %d times for Watch:false peer, want 0", got) + } +} diff --git a/internal/livedoor/helpers_direct_test.go b/internal/livedoor/helpers_direct_test.go new file mode 100644 index 0000000000..52fccc8bc0 --- /dev/null +++ b/internal/livedoor/helpers_direct_test.go @@ -0,0 +1,961 @@ +package livedoor + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "runtime" + "sort" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/remote" +) + +// This file is the rig the direct-road Link tests stand on. It is built from the +// contract and the package's PUBLIC surface only: a Link is given a fake +// DirectConfig.Dial that hands back one end of a net.Pipe with a real Serve on the +// other, so the road the Link believes it is on is a real tunnel whose frames the +// tests can count, stall, kill and read back, and the FakeClock is the only time +// the Link's own logic ever sees. + +// within spins, with no sleeping, for up to ten seconds of real time until cond +// holds. WHETHER A THING HAPPENS IS THE CONTRACT; THAT IT HAS HAPPENED BY THE +// NEXT LINE IS NOT, because the Link hands work to goroutines and the race +// detector makes a scheduler tick long. +func within(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + runtime.Gosched() + } +} + +// quiesce gives every goroutine that is ready to run a long turn. It is used +// before a NEGATIVE assertion ("nothing happened"), where there is no condition +// to wait for, so that a thing that was about to happen has had its chance. +func quiesce() { + for i := 0; i < 300; i++ { + runtime.Gosched() + } +} + +// tapFrame is one frame as it crossed a carrier. +type tapFrame struct { + op uint8 + channel uint32 +} + +// frameTap decodes frames out of the byte stream written to one side of a +// carrier, so a test can say "exactly one CLOSE and no PING crossed here" in the +// wire's own terms instead of counting write calls. +type frameTap struct { + mu sync.Mutex + buf []byte + frames []tapFrame +} + +func (f *frameTap) feed(p []byte) { + f.mu.Lock() + defer f.mu.Unlock() + f.buf = append(f.buf, p...) + for len(f.buf) >= frameHeaderBytes { + n := int(binary.BigEndian.Uint32(f.buf[5:9])) + if len(f.buf) < frameHeaderBytes+n { + return + } + f.frames = append(f.frames, tapFrame{op: f.buf[0], channel: binary.BigEndian.Uint32(f.buf[1:5])}) + f.buf = f.buf[frameHeaderBytes+n:] + } +} + +// count is how many frames of op have crossed. +func (f *frameTap) count(op uint8) int { + f.mu.Lock() + defer f.mu.Unlock() + n := 0 + for _, fr := range f.frames { + if fr.op == op { + n++ + } + } + return n +} + +// mark is a position in the stream, for since. +func (f *frameTap) mark() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.frames) +} + +// since is every frame after mark, in order. +func (f *frameTap) since(mark int) []tapFrame { + f.mu.Lock() + defer f.mu.Unlock() + if mark >= len(f.frames) { + return nil + } + return append([]tapFrame(nil), f.frames[mark:]...) +} + +// opsSince is the number of frames of op after mark. +func (f *frameTap) opsSince(mark int, op uint8) int { + n := 0 + for _, fr := range f.since(mark) { + if fr.op == op { + n++ + } + } + return n +} + +// stallConn is the viewer's end of a tunnel as the Link sees it. It records every +// frame the Link tries to send, and it can be STALLED: from then on nothing the +// Link writes reaches the host and nothing the host writes reaches the Link, +// while nothing is closed. That is a path that has died without telling anyone, +// which is the failure the fallback exists for. +type stallConn struct { + inner net.Conn + sent frameTap + stalled atomic.Bool + closed atomic.Bool +} + +func (c *stallConn) Read(p []byte) (int, error) { + for { + n, err := c.inner.Read(p) + if c.stalled.Load() { + if err != nil { + return 0, err + } + // Dropped on the floor, but still drained, so the host's writes + // complete and the host never blocks on a black hole. + continue + } + return n, err + } +} + +func (c *stallConn) Write(p []byte) (int, error) { + c.sent.feed(p) + if c.stalled.Load() { + return len(p), nil + } + return c.inner.Write(p) +} + +func (c *stallConn) Close() error { + c.closed.Store(true) + return c.inner.Close() +} + +// tapWriteConn records the frames the host wrote, after each write has been +// taken in by the viewer's side, so a count of host pongs means pongs the Link +// has had delivered. +type tapWriteConn struct { + net.Conn + tap *frameTap +} + +func (c *tapWriteConn) Write(p []byte) (int, error) { + n, err := c.Conn.Write(p) + if n > 0 { + c.tap.feed(p[:n]) + } + return n, err +} + +// tunnelEnd is one tunnel the rig has served: the viewer's end with its taps and +// stall switch, the host's end and the host's own taps. +type tunnelEnd struct { + road string + index int + viewer *stallConn + host net.Conn + hostTap frameTap + served chan struct{} +} + +// stall black-holes this tunnel: no close, no error, just silence both ways. +func (e *tunnelEnd) stall() { e.viewer.stalled.Store(true) } + +// kill is the host end of the tunnel going away abruptly. +func (e *tunnelEnd) kill() { _ = e.host.Close() } + +// openRec is one channel the host side resolved: which road's tunnel it came in +// on, which tunnel of that road, and for which chat. +type openRec struct { + road string + tunnel int + chat string +} + +// openGate holds the host's resolution of one chat open until released, so a test +// can have an open in flight while something else happens. +type openGate struct { + entered chan struct{} + release chan struct{} +} + +// directDialFn is what a fake direct dial does on its nth call. +type directDialFn func(ctx context.Context, n int, s Signaller) (io.ReadWriteCloser, error) + +// rigOpts shapes a directRig. +type rigOpts struct { + active bool + noDirect bool + noAdvertise bool + idleDetach time.Duration + sharedReg bool + holder func(r *directRig, road string, tunnel int) Resolver +} + +// directRig is a viewer Link, a host that serves whatever tunnels it dials, and +// the instruments around them. +type directRig struct { + t *testing.T + ctx context.Context + fc *FakeClock + link *Link + peer Peer + opts rigOpts + + host *fakeDirectHost + relayReg *Registry + directReg *Registry + + relayDials atomic.Int32 + directDials atomic.Int32 + directDone atomic.Int32 + + mu sync.Mutex + tunnels []*tunnelEnd + relayTimes []time.Time + directTimes []time.Time + opens []openRec + states []State + ended []string + signals [][]byte + directFn directDialFn + relayFn func(ctx context.Context, n int) error + gates map[string]*openGate + closers []func() +} + +// newDirectRig builds the rig. It dials nothing: the Link dials when a channel is +// first opened, as it always has. +func newDirectRig(t *testing.T, opts rigOpts) *directRig { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + r := &directRig{ + t: t, + ctx: ctx, + fc: NewFakeClock(time.Date(2026, 11, 24, 12, 0, 0, 0, time.UTC)), + opts: opts, + host: &fakeDirectHost{}, + relayReg: NewRegistry(), + gates: make(map[string]*openGate), + peer: Peer{Device: "dev-viewer", Label: "laptop", Permit: pair.Permit{Watch: true, Drive: true}}, + } + r.directReg = NewRegistry() + if opts.sharedReg { + r.directReg = r.relayReg + } + // Registered first so that it runs LAST: the link is closed before the pipes + // under it, and the host's context ends after both. + t.Cleanup(func() { + r.mu.Lock() + closers := append([]func(){}, r.closers...) + r.mu.Unlock() + for _, c := range closers { + c() + } + cancel() + }) + + lim := DefaultLimits() + if opts.idleDetach > 0 { + lim.IdleDetach = opts.idleDetach + } + cfg := LinkConfig{ + Clock: r.fc, + HostName: "Desktop", + Limits: lim, + Dial: r.dialRelay, + OnState: r.onState, + OnSignal: r.onSignal, + } + if opts.active { + cfg.Active = func() bool { return true } + } + if !opts.noDirect { + cfg.Direct = &DirectConfig{Dial: r.dialDirect} + } + r.link = NewLink(cfg) + r.link.OnChannelEnd(r.onEnd) + t.Cleanup(r.link.Close) + return r +} + +func (r *directRig) onState(s State) { + r.mu.Lock() + defer r.mu.Unlock() + r.states = append(r.states, s) +} + +func (r *directRig) onSignal(p []byte) { + r.mu.Lock() + defer r.mu.Unlock() + r.signals = append(r.signals, append([]byte(nil), p...)) +} + +func (r *directRig) onEnd(chat, reason string) { + r.mu.Lock() + defer r.mu.Unlock() + r.ended = append(r.ended, chat+":"+reason) +} + +func (r *directRig) stateCount() int { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.states) +} + +func (r *directRig) statesFrom(n int) []State { + r.mu.Lock() + defer r.mu.Unlock() + if n >= len(r.states) { + return nil + } + return append([]State(nil), r.states[n:]...) +} + +func (r *directRig) endedList() []string { + r.mu.Lock() + defer r.mu.Unlock() + return append([]string(nil), r.ended...) +} + +func (r *directRig) signalsGot() [][]byte { + r.mu.Lock() + defer r.mu.Unlock() + return append([][]byte(nil), r.signals...) +} + +// setDirect decides what the fake direct dial does from now on. +func (r *directRig) setDirect(fn directDialFn) { + r.mu.Lock() + defer r.mu.Unlock() + r.directFn = fn +} + +// failDirect makes every direct dial fail at once, the way a path that cannot +// be found does. +func (r *directRig) failDirect() { + r.setDirect(func(context.Context, int, Signaller) (io.ReadWriteCloser, error) { + return nil, errors.New("no direct path") + }) +} + +func (r *directRig) dialRelay(ctx context.Context) (io.ReadWriteCloser, error) { + n := int(r.relayDials.Add(1)) + r.mu.Lock() + r.relayTimes = append(r.relayTimes, r.fc.Now()) + fn := r.relayFn + r.mu.Unlock() + if fn != nil { + if err := fn(ctx, n); err != nil { + return nil, err + } + } + return r.newTunnel(RoadRelay), nil +} + +func (r *directRig) dialDirect(ctx context.Context, s Signaller) (io.ReadWriteCloser, error) { + n := int(r.directDials.Add(1)) + r.mu.Lock() + r.directTimes = append(r.directTimes, r.fc.Now()) + fn := r.directFn + r.mu.Unlock() + defer r.directDone.Add(1) + if fn == nil { + return r.newTunnel(RoadDirect), nil + } + return fn(ctx, n, s) +} + +// newTunnel serves one fresh tunnel of road with a real Serve on the host end and +// returns the viewer's end. +func (r *directRig) newTunnel(road string) *stallConn { + vConn, hConn := net.Pipe() + e := &tunnelEnd{road: road, host: hConn, served: make(chan struct{}), viewer: &stallConn{inner: vConn}} + r.mu.Lock() + e.index = 1 + for _, o := range r.tunnels { + if o.road == road { + e.index++ + } + } + r.tunnels = append(r.tunnels, e) + r.closers = append(r.closers, func() { _ = vConn.Close(); _ = hConn.Close() }) + r.mu.Unlock() + + cfg := ServeConfig{Resolver: r.resolverFor(road, e.index), Host: "Desktop", Road: road} + switch road { + case RoadRelay: + cfg.Registry = r.relayReg + if !r.opts.noAdvertise { + cfg.Direct = r.host + } + case RoadDirect: + cfg.Registry = r.directReg + } + guard.Go("livedoor.test.direct.serve", func() { + defer close(e.served) + _ = Serve(r.ctx, &tapWriteConn{Conn: hConn, tap: &e.hostTap}, r.peer, cfg) + }) + return e.viewer +} + +func (r *directRig) resolverFor(road string, tunnel int) Resolver { + if r.opts.holder != nil { + return r.opts.holder(r, road, tunnel) + } + return r.stubResolver(road, tunnel) +} + +func (r *directRig) recordOpen(road string, tunnel int, chat string) { + r.mu.Lock() + defer r.mu.Unlock() + r.opens = append(r.opens, openRec{road: road, tunnel: tunnel, chat: chat}) +} + +// opensOn is the chats the host resolved on road's tunnels, in order. +func (r *directRig) opensOn(road string) []string { + r.mu.Lock() + defer r.mu.Unlock() + var out []string + for _, o := range r.opens { + if o.road == road { + out = append(out, o.chat) + } + } + return out +} + +func (r *directRig) lastOpen() openRec { + r.mu.Lock() + defer r.mu.Unlock() + if len(r.opens) == 0 { + return openRec{} + } + return r.opens[len(r.opens)-1] +} + +// holdNextOpen makes the host's next resolution of chat on road wait until the +// returned gate is released. +func (r *directRig) holdNextOpen(road, chat string) *openGate { + g := &openGate{entered: make(chan struct{}), release: make(chan struct{})} + r.mu.Lock() + r.gates[road+"/"+chat] = g + r.mu.Unlock() + return g +} + +func (r *directRig) takeGate(road, chat string) *openGate { + r.mu.Lock() + defer r.mu.Unlock() + key := road + "/" + chat + g := r.gates[key] + delete(r.gates, key) + return g +} + +// stubResolver is a holder that welcomes whoever says hello and says, in the +// welcome's Model, WHICH ROAD THE CHANNEL CAME IN ON, so the viewer can read the +// road a channel is really carried on from the channel itself. +func (r *directRig) stubResolver(road string, tunnel int) Resolver { + return fakeResolverFunc(func(ctx context.Context, chat string) (net.Conn, Route, error) { + r.recordOpen(road, tunnel, chat) + if g := r.takeGate(road, chat); g != nil { + close(g.entered) + select { + case <-g.release: + case <-ctx.Done(): + return nil, Route{}, ctx.Err() + } + } + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.direct.holder", func() { + defer holderSide.Close() + scan := newLineScanner(holderSide, MaxLine) + line, err := scan.ReadLine(FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f) != nil { + return + } + var h remote.Hello + if json.Unmarshal(f.Payload, &h) != nil { + return + } + payload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: h.Workspace, + SessionFile: h.Session, + Model: road, + Remote: h.Remote, + }) + frame, _ := json.Marshal(remote.Frame{Kind: "welcome", Payload: payload}) + if _, err := holderSide.Write(append(frame, '\n')); err != nil { + return + } + _, _ = io.Copy(io.Discard, holderSide) + }) + return routerSide, Route{Kind: "daemon", PID: 7001, Session: "/work/p/" + chat + "/transcript.jsonl", Workspace: "/work/p"}, nil + }) +} + +// tunnelsOn is every tunnel the rig has served on road, oldest first. +func (r *directRig) tunnelsOn(road string) []*tunnelEnd { + r.mu.Lock() + defer r.mu.Unlock() + var out []*tunnelEnd + for _, e := range r.tunnels { + if e.road == road { + out = append(out, e) + } + } + return out +} + +// tunnel is the nth (1-based) tunnel served on road. +func (r *directRig) tunnel(road string, n int) *tunnelEnd { + r.t.Helper() + all := r.tunnelsOn(road) + if n < 1 || n > len(all) { + r.t.Fatalf("the rig has served %d %s tunnels, wanted number %d", len(all), road, n) + } + return all[n-1] +} + +// latest is the newest tunnel served on road. +func (r *directRig) latest(road string) *tunnelEnd { + r.t.Helper() + all := r.tunnelsOn(road) + if len(all) == 0 { + r.t.Fatalf("the rig has served no %s tunnel", road) + } + return all[len(all)-1] +} + +// openChatErr opens chat through the Link's opener with a real-time watchdog, so +// an open that hangs fails the test instead of the package's whole timeout. +func (r *directRig) openChatErr(chat string) (io.ReadWriteCloser, error) { + ctx, cancel := context.WithCancel(r.ctx) + r.mu.Lock() + r.closers = append(r.closers, cancel) + r.mu.Unlock() + watchdog := time.AfterFunc(10*time.Second, cancel) + defer watchdog.Stop() + return r.link.OpenerContext(chat)(ctx) +} + +func (r *directRig) openChat(chat string) io.ReadWriteCloser { + r.t.Helper() + ch, err := r.openChatErr(chat) + if err != nil { + r.t.Fatalf("opening %s failed: %v", chat, err) + } + return ch +} + +// trySpeak says hello on ch and reads the holder's welcome, returning the road the +// holder says the channel arrived on. +func (r *directRig) trySpeak(ch io.ReadWriteCloser) (string, error) { + payload, _ := json.Marshal(remote.Hello{Version: remote.Version}) + line, _ := json.Marshal(remote.Frame{Kind: "hello", Payload: payload}) + if _, err := ch.Write(append(line, '\n')); err != nil { + return "", err + } + type result struct { + road string + err error + } + done := make(chan result, 1) + guard.Go("livedoor.test.direct.welcome", func() { + scan := newLineScanner(ch, MaxLine) + raw, err := scan.ReadLine(MaxLine) + if err != nil { + done <- result{err: err} + return + } + var f remote.Frame + if err := json.Unmarshal(bytes.TrimRight(raw, "\r\n"), &f); err != nil || f.Kind != "welcome" { + done <- result{err: fmt.Errorf("the first line was %q, not a welcome", raw)} + return + } + var w remote.Welcome + _ = json.Unmarshal(f.Payload, &w) + done <- result{road: w.Model} + }) + select { + case res := <-done: + return res.road, res.err + case <-time.After(10 * time.Second): + r.t.Fatal("no welcome arrived on the channel") + return "", nil + } +} + +// speak is trySpeak that fails the test on an error. +func (r *directRig) speak(ch io.ReadWriteCloser) string { + r.t.Helper() + road, err := r.trySpeak(ch) + if err != nil { + r.t.Fatalf("saying hello on the channel failed: %v", err) + } + return road +} + +// endOf reads ch until it ends and returns the error that ended it. +func (r *directRig) endOf(ch io.ReadWriteCloser) error { + r.t.Helper() + done := make(chan error, 1) + guard.Go("livedoor.test.direct.end", func() { + var buf [64]byte + for { + if _, err := ch.Read(buf[:]); err != nil { + done <- err + return + } + } + }) + select { + case err := <-done: + return err + case <-time.After(10 * time.Second): + r.t.Fatal("the channel did not end") + return nil + } +} + +// isPlanned is whether err is the viewer-local planned redial, the answer a +// remote.Roam reads to skip its first pause. +func isPlanned(err error) bool { + var ce *ChannelError + return errors.As(err, &ce) && ce.PlannedRedial() +} + +func (r *directRig) waitRoad(road string) { + r.t.Helper() + within(r.t, "the road to read "+road, func() bool { return r.link.Road() == road && r.link.State().Road == road }) +} + +func (r *directRig) waitState(kind StateKind, road string) { + r.t.Helper() + within(r.t, fmt.Sprintf("the state to read %v on %s", kind, road), func() bool { + s := r.link.State() + return s.Kind == kind && s.Road == road + }) +} + +// ── the fake clock, read ──────────────────────────────────────────────────── + +// timersWithin is how far ahead each pending fake-clock timer is, nearest first, +// keeping only those due in more than zero and at most max. +func timersWithin(fc *FakeClock, max time.Duration) []time.Duration { + fc.mu.Lock() + defer fc.mu.Unlock() + var out []time.Duration + for _, tm := range fc.pending { + if d := tm.at.Sub(fc.now); d > 0 && d <= max { + out = append(out, d) + } + } + sort.Slice(out, func(i, j int) bool { return out[i] < out[j] }) + return out +} + +// hasTimerIn is whether some pending timer is due in exactly d. +func hasTimerIn(fc *FakeClock, d time.Duration) bool { + for _, got := range timersWithin(fc, 1000*time.Hour) { + if got == d { + return true + } + } + return false +} + +// waitAttemptArmed waits for a timer to be pending exactly d ahead. That is the +// attempt timer being armed: a test must not move the clock before it exists, or +// the timer would be armed from the later reading. +func (r *directRig) waitAttemptArmed(d time.Duration) { + r.t.Helper() + within(r.t, fmt.Sprintf("a timer to be armed %v ahead (have %v)", d, timersWithin(r.fc, 1000*time.Hour)), func() bool { + return hasTimerIn(r.fc, d) + }) +} + +// runToNextAttempt moves the fake clock timer by timer, to each next deadline +// within eleven minutes, until a direct attempt begins, and says how far it +// moved. Moving to a deadline exactly (never past it) keeps an attempt that +// starts there from having its own connect timer fired by the same Advance. +func (r *directRig) runToNextAttempt() time.Duration { + r.t.Helper() + before := r.directDials.Load() + deadline := time.Now().Add(10 * time.Second) + var moved time.Duration + for r.directDials.Load() == before { + if time.Now().After(deadline) { + r.t.Fatalf("no direct attempt began (the clock moved %v; timers: %v)", moved, timersWithin(r.fc, 1000*time.Hour)) + } + cands := timersWithin(r.fc, 11*time.Minute) + if len(cands) == 0 { + runtime.Gosched() + continue + } + r.fc.Advance(cands[0]) + moved += cands[0] + for i := 0; i < 2000 && r.directDials.Load() == before; i++ { + runtime.Gosched() + } + } + return moved +} + +// swapToDirect runs the clock to the next attempt and waits for the road to read +// direct. +func (r *directRig) swapToDirect() { + r.t.Helper() + r.runToNextAttempt() + r.waitRoad(RoadDirect) +} + +// swapToRelay has the host end the newest direct tunnel abruptly and waits for the +// road to read relay. +func (r *directRig) swapToRelay() { + r.t.Helper() + r.latest(RoadDirect).kill() + r.waitRoad(RoadRelay) +} + +// settleDirect waits until the host has answered every ping the nested link sent +// on e, which is how a test advances a healthy direct link a little at a time +// without letting the virtual clock outrun the real round trips. +func (r *directRig) settleDirect(e *tunnelEnd) { + r.t.Helper() + quiesce() + within(r.t, "the host's pongs to catch up with the direct link's pings", func() bool { + return e.hostTap.count(OpPong) >= e.viewer.sent.count(OpPing) + }) + // The pong has been WRITTEN once the host's tap has seen it, but the viewer's + // reader goroutine may not yet have decoded it and moved the link's last-heard + // instant. With a clock that stands still during a round trip that lag is the + // whole difference between "heard a moment ago" and "one pong missed", so the + // reader is given its turn before the clock moves again. + for i := 0; i < 8; i++ { + quiesce() + } +} + +// advanceHealthy moves the clock d forward in quarter-second steps over a direct +// link that is alive, letting each ping be answered before the next step. +func (r *directRig) advanceHealthy(e *tunnelEnd, d time.Duration) { + r.t.Helper() + const step = 250 * time.Millisecond + for d > 0 { + s := step + if d < s { + s = d + } + d -= s + r.fc.Advance(s) + r.settleDirect(e) + } +} + +// alignOnPong advances the clock in tenth-of-a-second steps until one more pong +// has reached the direct link, and stops there, so the link's last-heard instant +// is the clock's reading at the moment of the call. +func (r *directRig) alignOnPong(e *tunnelEnd) { + r.t.Helper() + before := e.hostTap.count(OpPong) + for i := 0; e.hostTap.count(OpPong) == before; i++ { + if i > 60 { + r.t.Fatal("the direct link was never answered") + } + r.fc.Advance(100 * time.Millisecond) + quiesce() + } + quiesce() +} + +// ladderStep waits for the next attempt to be armed exactly want ahead, shows that +// it does not fire a millisecond early, and lets it fire. +func (r *directRig) ladderStep(want time.Duration) { + r.t.Helper() + before := r.directDials.Load() + r.waitAttemptArmed(want) + r.fc.Advance(want - time.Millisecond) + quiesce() + if got := r.directDials.Load(); got != before { + r.t.Fatalf("an attempt began %v early (a timer due in %v)", time.Millisecond, want) + } + r.fc.Advance(time.Millisecond) + within(r.t, fmt.Sprintf("the attempt due after %v to begin", want), func() bool { return r.directDials.Load() > before }) +} + +// advanceFine moves the clock d forward in tenth-of-a-second steps, letting every +// goroutine that is ready run between the steps. Periodic timers the Link re-arms +// from a goroutine are re-armed from the clock's reading when they fire, so one +// big Advance would skip their ticks; small steps keep their cadence honest. It +// does not wait on any pong, so it is for paths that are dead or about to be. +func (r *directRig) advanceFine(d time.Duration) { + r.t.Helper() + for d > 0 { + s := 100 * time.Millisecond + if d < s { + s = d + } + d -= s + r.fc.Advance(s) + quiesce() + } +} + +// askAgainAfterDropErr opens chat on a Link whose relay tunnel has just gone, the +// way a roaming client does: an open that is refused because the dying tunnel +// had not been let go of yet is simply asked again, and one that is refused with a +// SPOKEN reason is the answer. The Link may dial at once or wait for its redial +// timer, and both are phase 1's to decide; this moves the clock to the redial +// timer only while an open is still waiting for it. +func (r *directRig) askAgainAfterDropErr(chat string) (io.ReadWriteCloser, error) { + r.t.Helper() + var last error + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + ch, err := r.reopenOnce(chat) + if err == nil { + return ch, nil + } + if _, spoken := ReasonOf(err); spoken { + return nil, err + } + last = err + // An open that is refused while the Link waits out its own redial timer is + // phase 1's way of saying "not yet"; the roaming client asks again after its + // pause, and here the pause is the fake clock moving to that timer, once the + // Link has armed it. + quiesce() + r.moveToRedialTimer() + } + return nil, last +} + +// moveToRedialTimer moves the fake clock to the nearest timer within twenty +// seconds, but ONLY while the Link is not Live: a Live Link has already dialled, +// and the timers it holds then belong to the direct ladder, which a test must be +// the one to move. +func (r *directRig) moveToRedialTimer() { + if r.link.State().Kind == Live { + return + } + if cands := timersWithin(r.fc, 20*time.Second); len(cands) > 0 { + r.fc.Advance(cands[0]) + } +} + +// reopenOnce is one open of chat, with the fake clock moved to the redial timer +// if the open is waiting on it. +func (r *directRig) reopenOnce(chat string) (io.ReadWriteCloser, error) { + r.t.Helper() + type result struct { + ch io.ReadWriteCloser + err error + } + done := make(chan result, 1) + guard.Go("livedoor.test.direct.reopen", func() { + ch, err := r.openChatErr(chat) + done <- result{ch: ch, err: err} + }) + deadline := time.Now().Add(10 * time.Second) + for { + select { + case res := <-done: + return res.ch, res.err + default: + } + if time.Now().After(deadline) { + r.t.Fatalf("reopening %s never finished", chat) + } + quiesce() + select { + case res := <-done: + return res.ch, res.err + default: + } + r.moveToRedialTimer() + } +} + +func (r *directRig) askAgainAfterDrop(chat string) io.ReadWriteCloser { + r.t.Helper() + ch, err := r.askAgainAfterDropErr(chat) + if err != nil { + r.t.Fatalf("reopening %s failed: %v", chat, err) + } + return ch +} + +// hostSays makes the host of reg's tunnels end every channel of the device with +// reason while leaving each tunnel open, which is the host speaking a reason on a +// channel and nothing else. +func hostSays(t *testing.T, reg *Registry, device, reason string) { + t.Helper() + var targets []channelResetter + reg.mu.Lock() + for _, entry := range reg.byDevice[device] { + if cr, ok := entry.closer.(channelResetter); ok { + targets = append(targets, cr) + } + } + reg.mu.Unlock() + if len(targets) == 0 { + t.Fatalf("the registry holds no tunnel of %s to speak on", device) + } + for _, cr := range targets { + cr.resetAllChannels(reason) + } +} + +// bounded runs fn on its own goroutine and fails the test if it has not returned +// within ten seconds of real time. It is for calls that must never block. +func bounded(t *testing.T, what string, fn func()) { + t.Helper() + done := make(chan struct{}) + guard.Go("livedoor.test.direct.bounded", func() { + defer close(done) + fn() + }) + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatalf("%s blocked", what) + } +} diff --git a/internal/livedoor/helpers_test.go b/internal/livedoor/helpers_test.go new file mode 100644 index 0000000000..33b903ab7e --- /dev/null +++ b/internal/livedoor/helpers_test.go @@ -0,0 +1,39 @@ +package livedoor + +import ( + "io" + "runtime" + "sync/atomic" + "testing" + "time" +) + +// eventually waits, in real time bounded at three seconds and without sleeping, +// for cond to become true. THE LINK'S STATE CHANGES UNDER ITS OWN LOCK BUT ITS +// TUNNEL CLOSE AND ITS CHANNEL-END CALLBACKS RUN ON GOROUTINES, so a test that +// advances the fake clock may read them a scheduler tick before they happen, +// and the race detector makes that tick long. Whether the thing happens is the +// contract; that it has happened by the instant of the next line is not. +func eventually(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + runtime.Gosched() + } +} + +// countBeforeRWC counts each write BEFORE handing it to the transport, so a +// test that sees a frame arrive at the far end can rely on the count already +// including it. +type countBeforeRWC struct { + io.ReadWriteCloser + n *atomic.Int64 +} + +func (c *countBeforeRWC) Write(p []byte) (int, error) { + c.n.Add(1) + return c.ReadWriteCloser.Write(p) +} diff --git a/internal/livedoor/limits.go b/internal/livedoor/limits.go new file mode 100644 index 0000000000..efbe0832c2 --- /dev/null +++ b/internal/livedoor/limits.go @@ -0,0 +1,274 @@ +package livedoor + +import "time" + +const ( + // MaxLine caps a single EventWire JSON line so one oversized event cannot pin + // memory at the host or viewer above the tunnel. + MaxLine = 256 << 10 + + // ChunkBytes caps a single multiplexer frame payload so concurrent channels + // interleave fairly on one tunnel and fit well inside a Noise plaintext record. + ChunkBytes = 16 << 10 + + // ChannelWindow bounds unacknowledged data bytes in flight on one multiplexed + // channel so one unread chat cannot stall other chats on the same link. + ChannelWindow = 256 << 10 + + // LinkWindow bounds total unacknowledged data bytes in flight across the entire + // tunnel so a blind relay cannot buffer unbounded data for a slow viewer. + LinkWindow = 1 << 20 + + // QueueMax bounds the per-channel outbound queue at the host before a lagging + // viewer is reset back to Resume. + QueueMax = 4 << 20 + + // RingBytes bounds the holder's replay ring so a reset-then-Resume cycle + // either catches up within fixed memory or signals an explicit gap. + RingBytes = 1 << 20 + + // Rate paces outbound data payload bytes per second in each direction so a + // chatty session stays below the relay abuse breaker. + Rate = 1 << 20 + + // RateBurst is the token-bucket burst allowance paired with Rate so an initial + // welcome tail or burst of deltas up to one megabyte leaves without delay. + RateBurst = 1 << 20 + + // DailyBudget is the per-day carrier byte allowance before live sessions + // degrade to watch-only until midnight. + DailyBudget = 256 << 20 + + // MaxLive caps concurrent live-intent relay streams on the host so two of the + // sixteen relay stream slots stay reserved for Move. + MaxLive = 14 + + // MaxTunnelsPerDevice caps simultaneous live tunnels from the same viewer + // device so a reconnecting link may briefly overlap its dying predecessor. + MaxTunnelsPerDevice = 2 + + // MaxChannelsPerLink caps concurrent open channels on a single multiplexed + // tunnel so one viewer cannot allocate unbounded channel state. + MaxChannelsPerLink = 32 + + // FirstLineMax bounds the initial handshake line read on a local holder socket + // before the full session line limit applies. + FirstLineMax = 64 << 10 + + // MaxDirect caps concurrent direct tunnels on one host. A direct tunnel + // holds no relay stream, so this number is its own and not a share of + // MaxLive; the files door's admission count (filesdoor.MaxDirect) is the + // same number and a syncsetup test pins that they agree. + MaxDirect = 14 + + // DirectRate is the pacing of a direct tunnel in bytes per second, in each + // direction, and its burst too. The 1 MiB/s Rate exists to keep the relay + // under its abuse breaker and its message bill; a direct path has neither, + // so this bucket exists for symmetry and never binds on a network. + DirectRate = 64 << 20 + + // SignalMax bounds one signalling payload. It is half of ChunkBytes so a + // signal always fits one frame with room to spare, and far more than a + // data-channel-only session description needs. + SignalMax = 8 << 10 + + // SignalRate is how many signalling frames a link may carry in a minute + // before it is closed as `too-many`. An attempt is an offer, an answer and + // a handful of candidates, so this allows several attempts a minute. + SignalRate = 64 + + // PendingOffers caps the direct attempts a host has in flight at once, over + // every viewer, so a flood of offers cannot make a host build peer + // connections without limit. + PendingOffers = 4 +) + +var ( + // PingEvery is the interval between multiplexer pings while a viewed chat is + // active; tests shrink it with t.Cleanup. + PingEvery = 3 * time.Second + + // DeadAfter is the silence window after a ping before an unanswered link is + // declared dead; tests shrink it with t.Cleanup. + DeadAfter = 6 * time.Second + + // ActiveWindow is how long after a user action a viewed link remains in active + // ping mode before going quiet to keep the relay hibernated. + ActiveWindow = 30 * time.Second + + // IdleDetach is how long an inactive viewer with no running turn stays attached + // before closing channels with reason idle so the relay costs nothing at rest. + IdleDetach = 10 * time.Minute + + // WriteDeadline bounds how long the holder waits on a remote guest socket write + // before dropping that guest so a local surface never stalls. + WriteDeadline = 2 * time.Second + + // DirectPingEvery and DirectDeadAfter are the liveness of a direct tunnel. + // The mux ping IS how a viewer learns a direct path has died, and it costs + // the relay nothing, so it runs every second and declares the road dead + // after DirectPingEvery+DirectDeadAfter of silence (three seconds). + DirectPingEvery = 1 * time.Second + DirectDeadAfter = 2 * time.Second + + // DirectSettle is how long after a view's first channel opens that the + // viewer makes its first direct attempt, so the first paint never waits on + // the path finding. + DirectSettle = 500 * time.Millisecond + + // DirectConnectWithin is the time one attempt gets to finish ICE, DTLS, + // SCTP, the handshake and the hello before it is abandoned. + DirectConnectWithin = 8 * time.Second + + // DirectBackoff is how long a viewer waits after each failed attempt before + // the next, ending in a ten-minute wait that repeats; DirectStableAfter is + // how long a direct tunnel must stay up before the ladder starts over. + DirectBackoff = []time.Duration{5 * time.Second, 15 * time.Second, 60 * time.Second, 5 * time.Minute, 10 * time.Minute} + + DirectStableAfter = 60 * time.Second + + // OfferTTL is how long a host keeps an attempt that has not produced a + // stream before it lets the attempt go. + OfferTTL = 12 * time.Second +) + +// DirectLimits are the limits a host serves a direct tunnel with: the road's +// own pacing and liveness, and everything else (the line cap, the credit +// windows, the write deadline) as for the relay, because those bound memory +// above the tunnel and not the cost of the road. +func DirectLimits() Limits { + l := DefaultLimits() + l.Rate = DirectRate + l.RateBurst = DirectRate + l.PingEvery = DirectPingEvery + l.DeadAfter = DirectDeadAfter + return l +} + +// Limits carries the byte, count, and duration caps for a live door link so a +// test or handshake payload can override individual values from the defaults. +type Limits struct { + MaxLine int `json:"max_line,omitempty"` + ChunkBytes int `json:"chunk_bytes,omitempty"` + ChannelWindow int `json:"channel_window,omitempty"` + LinkWindow int `json:"link_window,omitempty"` + QueueMax int `json:"queue_max,omitempty"` + RingBytes int `json:"ring_bytes,omitempty"` + Rate int `json:"rate,omitempty"` + RateBurst int `json:"rate_burst,omitempty"` + DailyBudget int64 `json:"daily_budget,omitempty"` + MaxLive int `json:"max_live,omitempty"` + MaxTunnelsPerDevice int `json:"max_tunnels_per_device,omitempty"` + MaxChannelsPerLink int `json:"max_channels_per_link,omitempty"` + FirstLineMax int `json:"first_line_max,omitempty"` + PingEvery time.Duration `json:"ping_every,omitempty"` + DeadAfter time.Duration `json:"dead_after,omitempty"` + ActiveWindow time.Duration `json:"active_window,omitempty"` + IdleDetach time.Duration `json:"idle_detach,omitempty"` + WriteDeadline time.Duration `json:"write_deadline,omitempty"` +} + +// DefaultLimits returns a Limits populated from the package constants and +// current duration variables. +func DefaultLimits() Limits { + return Limits{ + MaxLine: MaxLine, + ChunkBytes: ChunkBytes, + ChannelWindow: ChannelWindow, + LinkWindow: LinkWindow, + QueueMax: QueueMax, + RingBytes: RingBytes, + Rate: Rate, + RateBurst: RateBurst, + DailyBudget: DailyBudget, + MaxLive: MaxLive, + MaxTunnelsPerDevice: MaxTunnelsPerDevice, + MaxChannelsPerLink: MaxChannelsPerLink, + FirstLineMax: FirstLineMax, + PingEvery: PingEvery, + DeadAfter: DeadAfter, + ActiveWindow: ActiveWindow, + IdleDetach: IdleDetach, + WriteDeadline: WriteDeadline, + } +} + +// directDefaults fills the fields where a direct tunnel differs from a relay +// one, wherever the caller left them unset, so a direct tunnel served with a +// zero Limits is still paced and watched as the direct road is. +func (l Limits) directDefaults() Limits { + if l.Rate <= 0 { + l.Rate = DirectRate + } + if l.RateBurst <= 0 { + l.RateBurst = DirectRate + } + if l.PingEvery <= 0 { + l.PingEvery = DirectPingEvery + } + if l.DeadAfter <= 0 { + l.DeadAfter = DirectDeadAfter + } + return l +} + +// withDefaults fills any non-positive field in l from DefaultLimits so a test +// can set only the single limit it cares about in a config struct. +func (l Limits) withDefaults() Limits { + d := DefaultLimits() + if l.MaxLine <= 0 { + l.MaxLine = d.MaxLine + } + if l.ChunkBytes <= 0 { + l.ChunkBytes = d.ChunkBytes + } + if l.ChannelWindow <= 0 { + l.ChannelWindow = d.ChannelWindow + } + if l.LinkWindow <= 0 { + l.LinkWindow = d.LinkWindow + } + if l.QueueMax <= 0 { + l.QueueMax = d.QueueMax + } + if l.RingBytes <= 0 { + l.RingBytes = d.RingBytes + } + if l.Rate <= 0 { + l.Rate = d.Rate + } + if l.RateBurst <= 0 { + l.RateBurst = d.RateBurst + } + if l.DailyBudget <= 0 { + l.DailyBudget = d.DailyBudget + } + if l.MaxLive <= 0 { + l.MaxLive = d.MaxLive + } + if l.MaxTunnelsPerDevice <= 0 { + l.MaxTunnelsPerDevice = d.MaxTunnelsPerDevice + } + if l.MaxChannelsPerLink <= 0 { + l.MaxChannelsPerLink = d.MaxChannelsPerLink + } + if l.FirstLineMax <= 0 { + l.FirstLineMax = d.FirstLineMax + } + if l.PingEvery <= 0 { + l.PingEvery = d.PingEvery + } + if l.DeadAfter <= 0 { + l.DeadAfter = d.DeadAfter + } + if l.ActiveWindow <= 0 { + l.ActiveWindow = d.ActiveWindow + } + if l.IdleDetach <= 0 { + l.IdleDetach = d.IdleDetach + } + if l.WriteDeadline <= 0 { + l.WriteDeadline = d.WriteDeadline + } + return l +} diff --git a/internal/livedoor/link.go b/internal/livedoor/link.go new file mode 100644 index 0000000000..7d911cf6be --- /dev/null +++ b/internal/livedoor/link.go @@ -0,0 +1,1468 @@ +package livedoor + +import ( + "context" + "errors" + "fmt" + "io" + "runtime" + "sync" + "sync/atomic" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/relay" +) + +const ( + reconnectBase = 1 * time.Second + reconnectCap = 15 * time.Second +) + +// LinkConfig configures a viewer-side multiplexed Link to one host device. +// Dial returns an io.ReadWriteCloser that has already completed the tunnel +// handshake and device hello. +type LinkConfig struct { + Home string + Dial func(context.Context) (io.ReadWriteCloser, error) + Identity string + Host string + Clock Clock + Limits Limits + Active func() bool + OnState func(State) + HostName string + + // Direct, when non-nil, lets this link try the direct road after its relay + // view is open. A nil Direct means the link never tries it and behaves + // exactly as it did before the direct road existed. + Direct *DirectConfig + + // OnSignal is called with each signalling payload the host sends on the + // RELAY tunnel (channel 0). The caller feeds it to the direct + // implementation it built Direct from. It runs on the mux reader goroutine, + // so it must not block. + OnSignal func([]byte) +} + +type trackedChannel struct { + ch *Channel + chat string + endOnce sync.Once + mu sync.Mutex + localReason string +} + +func (tc *trackedChannel) setLocalReason(reason string) { + tc.mu.Lock() + if tc.localReason == "" { + tc.localReason = reason + } + tc.mu.Unlock() +} + +func (tc *trackedChannel) reason() string { + tc.mu.Lock() + r := tc.localReason + tc.mu.Unlock() + if r != "" { + return r + } + return tc.ch.Reason() +} + +type linkChannel struct { + *Channel + tc *trackedChannel +} + +func (lc *linkChannel) Reason() string { + return lc.tc.reason() +} + +func (lc *linkChannel) Read(p []byte) (int, error) { + n, err := lc.Channel.Read(p) + if err != nil { + if r := lc.tc.reason(); r != "" && errors.Is(err, ErrLinkClosed) { + return n, &ChannelError{Op: "close", Why: r, Err: io.EOF} + } + // A channel the link itself closed to change roads ends with a plain + // io.EOF, which a caller cannot tell from a host that hung up. The + // viewer-local road-change reason is what tells remote.Roam to redial at + // once, so every way such a channel can end reports it. + if lc.tc.reason() == ReasonRoadChange && (errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe)) { + return n, &ChannelError{Op: "close", Why: ReasonRoadChange, Err: io.EOF} + } + } + return n, err +} + +func (lc *linkChannel) Write(p []byte) (int, error) { + n, err := lc.Channel.Write(p) + if err != nil { + if r := lc.tc.reason(); r != "" && errors.Is(err, ErrLinkClosed) { + return n, &ChannelError{Op: "close", Why: r, Err: io.ErrClosedPipe} + } + if lc.tc.reason() == ReasonRoadChange && (errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe)) { + return n, &ChannelError{Op: "close", Why: ReasonRoadChange, Err: io.ErrClosedPipe} + } + } + return n, err +} + +// Link maintains at most one multiplexed viewer tunnel to a host computer, +// opening per-chat channels over it, sending liveness pings only while active, +// and detaching cleanly after IdleDetach of quiet. +type Link struct { + cfg LinkConfig + clock Clock + limits Limits + + dialMu sync.Mutex + framesWritten atomic.Int64 + + mu sync.Mutex + state State + permit pair.Permit + road string + mux *Mux + channels map[uint32]*trackedChannel + onChannelEnd func(chat, reason string) + lastHeard time.Time + lastTouch time.Time + lastActive time.Time + idleSince time.Time + lastPingSent time.Time + probeSentAt time.Time + probeDeadline time.Time + pingSeq uint32 + livenessTimer Timer + livenessAt time.Time + redialTimer Timer + redialAt time.Time + retryCount int + baseWait time.Duration + offlineCap bool + immediateRedial bool + budgetExhausted bool + revoked bool + lastReason string + closed bool + + // The road overlay. state above is always the RELAY state, and every relay + // handler keeps writing it. shown is what State() reports: it equals state + // while the relay carries, and it is the direct link's posture while the + // direct road carries. carrying is RoadRelay (or empty, which means the + // same) or RoadDirect. + shown State + carrying string + hostDirect bool + + // roadGen counts every change of the road (a swap, a fallback, an idle + // detach) and attemptTok every start or abandonment of an attempt, so an + // open or an attempt that raced a change can tell, under mu, that it is + // stale. directMux and directSince describe the direct tunnel that carries. + roadGen uint64 + attemptTok uint64 + direct *Link + directMux *Mux + directSince time.Time + dchannels map[*directChannel]struct{} + + // noAutoRedial is set by the outer link on the nested direct link: the + // outer ladder owns every direct redial, so the nested link never schedules + // one of its own. + noAutoRedial bool + + // The attempt ladder and the standby probe (link_direct.go). + dfails int + dtimer Timer + drun *directRun + ptimer Timer + sbProbed bool + sbProbeAt time.Time + sbWait chan struct{} + + loopOnce sync.Once + wakeCh chan struct{} + stopCh chan struct{} + stopOnce sync.Once +} + +// NewLink constructs a Link for one host device without starting any goroutine +// or dialling until the first Opener or reconnect Touch call. +func NewLink(cfg LinkConfig) *Link { + clk := cfg.Clock + if clk == nil { + clk = RealClock() + } + lim := cfg.Limits.withDefaults() + start := State{Kind: Connecting, Since: clk.Now()} + return &Link{ + cfg: cfg, + clock: clk, + limits: lim, + state: start, + shown: start, + carrying: RoadRelay, + channels: make(map[uint32]*trackedChannel), + dchannels: make(map[*directChannel]struct{}), + baseWait: reconnectBase, + wakeCh: make(chan struct{}, 1), + stopCh: make(chan struct{}), + } +} + +// OnChannelEnd registers a callback invoked once per ended channel with its +// closed-set reason string. +func (l *Link) OnChannelEnd(fn func(chat, reason string)) { + l.mu.Lock() + l.onChannelEnd = fn + l.mu.Unlock() +} + +// State returns the link's current State snapshot. +func (l *Link) State() State { + l.mu.Lock() + mux := l.mux + l.mu.Unlock() + if mux != nil { + select { + case <-mux.Done(): + l.handleTunnelDone(mux) + default: + } + } + l.mu.Lock() + defer l.mu.Unlock() + return l.shown +} + +// Road returns the road that carries the view right now, "relay" or "direct". +// It is State().Road, so it says "relay" until the direct road has taken over. +func (l *Link) Road() string { + return l.State().Road +} + +// SendSignal sends one signalling payload as an OpSignal frame on the current +// relay tunnel. It is how the direct-road implementation talks to the host +// before a direct path exists, and it fails when the link has no relay tunnel +// to send on. +func (l *Link) SendSignal(p []byte) error { + l.mu.Lock() + mux := l.mux + l.mu.Unlock() + if mux == nil { + return fmt.Errorf("%w: no relay tunnel to signal on", ErrLinkClosed) + } + return mux.SendSignal(p) +} + +// Close permanently shuts down the link, stops any pending liveness or redial +// timers, and closes the active tunnel if one is open. +func (l *Link) Close() { + var ( + mux *Mux + nested *Link + ) + func() { + l.mu.Lock() + defer l.mu.Unlock() + if l.closed { + return + } + l.closed = true + l.stopLivenessTimerLocked() + l.stopRedialTimerLocked() + mux = l.mux + l.mux = nil + l.channels = make(map[uint32]*trackedChannel) + nested = l.dropDirectLocked() + }() + + l.stopOnce.Do(func() { + close(l.stopCh) + }) + if mux != nil { + _ = mux.Close() + } + if nested != nil { + nested.Close() + } +} + +// Touch records a person action (key, scroll, or send), reconnecting the link +// if it had detached to Idle, or sending a single liveness probe ping if the +// link was connected and quiet for at least PingEvery. +func (l *Link) Touch() { + now := l.clock.Now() + l.mu.Lock() + if l.closed || l.revoked { + l.mu.Unlock() + return + } + wasIdle := l.state.Kind == Idle + mux := l.mux + wasActive := l.isActiveLocked(now) + l.lastTouch = now + if now.After(l.idleSince) { + l.idleSince = now + } + + var ( + sentProbe bool + beforeWrites int64 + ) + if mux != nil && !wasActive && l.carrying != RoadDirect { + if now.Sub(l.lastHeard) >= l.limits.PingEvery { + l.pingSeq++ + seq := l.pingSeq + l.lastPingSent = now + l.probeSentAt = now + l.probeDeadline = now.Add(l.limits.DeadAfter) + beforeWrites = l.framesWritten.Load() + _ = mux.SendPing(seq) + sentProbe = true + } + } + if mux != nil || l.carrying == RoadDirect { + l.resetLivenessTimerLocked(now) + } + l.mu.Unlock() + l.wake() + + if sentProbe && mux != nil { + // Wait briefly for the mux writer goroutine to complete writeFrame so + // the probe ping is on the wire before Touch returns. + deadline := time.Now().Add(50 * time.Millisecond) + for l.framesWritten.Load() == beforeWrites { + select { + case <-mux.Done(): + goto probeDone + default: + } + if time.Now().After(deadline) { + break + } + runtime.Gosched() + } + probeDone: + } + + if wasIdle && mux == nil { + l.startLoop() + _, _ = l.ensureConnected(context.Background()) + } +} + +// Opener returns a dialer for chat matching remote.Roaming.Dial. +func (l *Link) Opener(chat string) func() (io.ReadWriteCloser, error) { + openCtx := l.OpenerContext(chat) + return func() (io.ReadWriteCloser, error) { + return openCtx(context.Background()) + } +} + +// resumeAfterHostOff lifts the rest a host's "remote control is off" put this +// link in, because an open is somebody asking again. The host ended every view +// it had here and the link has not redialled since, which is the point; but a +// computer turned back on must be reachable without restarting this one, so the +// first open after it dials like any other. A link that was REMOVED stays +// revoked: that is permanent, and this is not. +func (l *Link) resumeAfterHostOff() { + l.mu.Lock() + if l.closed || !l.revoked || l.lastReason != ReasonRemoteControlOff { + l.mu.Unlock() + return + } + stale := l.mux + l.mu.Unlock() + if stale != nil { + // THE TUNNEL THE HOST ENDED THE VIEWS ON MAY NOT HAVE BEEN SEEN TO CLOSE YET: + // the host closes it right behind the reasons, and this open can land in the + // gap. It is closed here and settled while the link still rests, so its end + // is recorded as the host's (no timer, no "went offline") and the open below + // dials a tunnel of its own rather than a refusal on the one that is closing. + _ = stale.Close() + l.handleTunnelDone(stale) + } + + now := l.clock.Now() + var notify *State + l.mu.Lock() + if l.closed || !l.revoked || l.lastReason != ReasonRemoteControlOff { + l.mu.Unlock() + return + } + l.revoked = false + notify = l.setStateLocked(State{ + Kind: Connecting, + Since: now, + Permit: l.permit, + Road: l.road, + }) + l.mu.Unlock() + l.wake() + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } +} + +// openTries is how many times one OpenerContext call retries a channel that +// opened on a road the link then left: the open is repeated on the road that +// carries now, so a swap that commits while a channel is opening can never +// leave that channel behind on the road that was given up. +const openTries = 3 + +// errRoadMoved reports a channel that opened on a road the link left before the +// channel could be registered. It is internal: OpenerContext retries on it. +var errRoadMoved = errors.New("livedoor: the road changed while a channel was opening") + +// OpenerContext returns a context-aware channel opener for chat. While the +// direct road carries the view it opens the channel there; otherwise, or when +// the direct tunnel dies under the open, it connects the relay tunnel on first +// use or after detach and opens a new mux channel for chat on that. The opener +// is safe to call from many goroutines at once, one per open chat. +func (l *Link) OpenerContext(chat string) func(context.Context) (io.ReadWriteCloser, error) { + return func(ctx context.Context) (io.ReadWriteCloser, error) { + if ctx == nil { + ctx = context.Background() + } + l.startLoop() + l.resumeAfterHostOff() + + var lastErr error + for try := 0; try < openTries; try++ { + if rwc, handled, err := l.openDirect(ctx, chat); handled { + if !errors.Is(err, errRoadMoved) { + return rwc, err + } + lastErr = err + continue + } + rwc, err := l.openRelay(ctx, chat) + if !errors.Is(err, errRoadMoved) { + return rwc, err + } + lastErr = err + } + return nil, l.wrapReasonError(lastErr) + } +} + +// openRelay is the phase 1 opener: connect the relay tunnel if it is not up, +// open the channel on it, and register the channel with the link. +func (l *Link) openRelay(ctx context.Context, chat string) (io.ReadWriteCloser, error) { + // A standby that was probed and has not answered is never opened on: the + // open would wait on a tunnel that is already gone. + l.settleStandby(ctx) + + mux, err := l.ensureConnected(ctx) + if err != nil { + return nil, l.wrapReasonError(err) + } + + var ( + gen uint64 + moved bool + ) + func() { + l.mu.Lock() + defer l.mu.Unlock() + gen = l.roadGen + moved = l.carrying == RoadDirect + }() + if moved { + return nil, errRoadMoved + } + + ch, err := mux.Open(ctx, chat) + if err != nil { + var ref *RefusedError + if errors.As(err, &ref) && ref != nil { + l.noteOpenRefusal(ref.Reason) + return nil, &ReasonError{ + Reason: ref.Reason, + Host: l.cfg.HostName, + Err: err, + } + } + select { + case <-mux.Done(): + l.handleTunnelDone(mux) + default: + } + return nil, l.wrapReasonError(err) + } + + tc := &trackedChannel{ + ch: ch, + chat: chat, + } + stale := false + func() { + l.mu.Lock() + defer l.mu.Unlock() + if l.roadGen != gen || (l.carrying == RoadDirect && l.mux == mux) { + // A swap committed after this channel was opened and so could not + // have seen it. It is not registered; it is closed below, outside + // the lock, and the open is repeated on the road that carries now. + stale = true + return + } + if l.mux == mux && !l.closed { + now := l.clock.Now() + if l.channelCountLocked() == 0 && now.After(l.idleSince) { + l.idleSince = now + } + l.channels[ch.ID()] = tc + l.resetLivenessTimerLocked(now) + } + }() + if stale { + _ = ch.Close() + return nil, errRoadMoved + } + l.wake() + + guard.Go("livedoor.link.channel", func() { + select { + case <-ch.Done(): + l.handleChannelDone(mux, tc) + case <-l.stopCh: + } + }) + + l.maybeScheduleDirectAttempt() + return &linkChannel{Channel: ch, tc: tc}, nil +} + +func (l *Link) startLoop() { + l.loopOnce.Do(func() { + guard.Go("livedoor.link.loop", l.loop) + }) +} + +func (l *Link) wake() { + select { + case l.wakeCh <- struct{}{}: + default: + } +} + +func (l *Link) wrapReasonError(err error) error { + if err == nil { + return nil + } + var re *ReasonError + if errors.As(err, &re) { + return err + } + if reason, ok := ReasonOf(err); ok { + return &ReasonError{ + Reason: reason, + Host: l.cfg.HostName, + Err: err, + } + } + l.mu.Lock() + reason := l.lastReason + if l.state.Reason != "" { + reason = l.state.Reason + } + l.mu.Unlock() + return &ReasonError{ + Reason: reason, + Host: l.cfg.HostName, + Err: err, + } +} + +func (l *Link) noteOpenRefusal(reason string) { + now := l.clock.Now() + var notify *State + l.mu.Lock() + switch reason { + case ReasonRemoved: + l.revoked = true + l.lastReason = ReasonRemoved + l.stopLivenessTimerLocked() + l.stopRedialTimerLocked() + notify = l.setStateLocked(State{ + Kind: Revoked, + Reason: ReasonRemoved, + Since: now, + Permit: pair.Permit{}, + Road: l.road, + }) + case ReasonRemoteControlOff: + notify = l.markRevokedLocked(ReasonRemoteControlOff, now) + case ReasonBudget: + l.budgetExhausted = true + l.permit.Drive = false + l.lastReason = ReasonBudget + notify = l.setStateLocked(State{ + Kind: StateBudget, + Reason: ReasonBudget, + Since: now, + Permit: l.permit, + Road: l.road, + }) + } + l.mu.Unlock() + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } + l.settleRevocation() +} + +func (l *Link) ensureConnected(ctx context.Context) (*Mux, error) { + l.dialMu.Lock() + defer l.dialMu.Unlock() + + l.mu.Lock() + if l.closed { + l.mu.Unlock() + return nil, ErrLinkClosed + } + if l.revoked { + reason := l.state.Reason + if reason == "" { + reason = l.lastReason + } + if reason == "" { + reason = ReasonNotAllowed + } + l.mu.Unlock() + return nil, &ReasonError{Reason: reason, Host: l.cfg.HostName} + } + if mux := l.mux; mux != nil { + select { + case <-mux.Done(): + l.mu.Unlock() + l.handleTunnelDone(mux) + default: + l.mu.Unlock() + return mux, nil + } + } else { + l.mu.Unlock() + } + + return l.dialAndHandshake(ctx) +} + +func (l *Link) dialAndHandshake(ctx context.Context) (*Mux, error) { + l.mu.Lock() + if l.closed { + l.mu.Unlock() + return nil, ErrLinkClosed + } + if l.revoked { + reason := l.state.Reason + if reason == "" { + reason = ReasonNotAllowed + } + l.mu.Unlock() + return nil, &ReasonError{Reason: reason, Host: l.cfg.HostName} + } + l.stopRedialTimerLocked() + l.mu.Unlock() + + if l.cfg.Dial == nil { + return nil, &ReasonError{Host: l.cfg.HostName, Err: errors.New("livedoor: missing Dial function")} + } + + rwc, err := l.cfg.Dial(ctx) + if err != nil { + l.handleDialFailure(err) + return nil, l.wrapReasonError(err) + } + + now := l.clock.Now() + l.mu.Lock() + l.lastHeard = now + l.mu.Unlock() + + mux := NewMux(rwc, Viewer, MuxConfig{ + Clock: l.clock, + Limits: l.limits, + OnPong: func(uint32) { l.recordHeard() }, + OnFrameRead: func(int) { l.recordHeard() }, + OnFrameWritten: func(int) { l.framesWritten.Add(1) }, + OnSignal: l.cfg.OnSignal, + }) + + helloWait := l.limits.DeadAfter + if helloWait <= 0 { + helloWait = DeadAfter + } + helloTimer := l.clock.NewTimer(helloWait) + var ( + ack HelloAck + ackErr error + ) + select { + case <-mux.helloAckCh: + ack, _ = mux.HelloAck() + case <-mux.Done(): + if a, ok := mux.HelloAck(); ok { + ack = a + } else { + ackErr = ErrLinkClosed + } + case <-helloTimer.C(): + ackErr = ErrLinkClosed + case <-ctx.Done(): + ackErr = ctx.Err() + case <-l.stopCh: + ackErr = ErrLinkClosed + } + helloTimer.Stop() + + if ackErr != nil { + _ = mux.Close() + l.handleDialFailure(ackErr) + return nil, l.wrapReasonError(ackErr) + } + + now = l.clock.Now() + permit := pair.Permit{Watch: ack.Watch, Drive: ack.Drive} + road := ack.Road + if road == "" { + road = defaultRoad + } + + if !ack.Watch { + _ = mux.Close() + // A host that is off says so, so the refusal is not read as this computer's + // permit being empty: that would send a person to /devices to fix a switch + // that is not there, and would never be lifted by the host turning back on. + refusal := ReasonNotAllowed + if ack.Off { + refusal = ReasonRemoteControlOff + } + var notify *State + l.mu.Lock() + l.revoked = true + l.lastReason = refusal + l.permit = permit + l.road = road + l.stopLivenessTimerLocked() + l.stopRedialTimerLocked() + notify = l.setStateLocked(State{ + Kind: Revoked, + Reason: refusal, + Since: now, + Permit: permit, + Road: road, + }) + l.mu.Unlock() + l.wake() + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } + l.settleRevocation() + return nil, &ReasonError{Reason: refusal, Host: l.cfg.HostName} + } + + var notify *State + l.mu.Lock() + if l.closed { + l.mu.Unlock() + _ = mux.Close() + return nil, ErrLinkClosed + } + l.mux = mux + l.permit = permit + l.road = road + l.relayEstablishedLocked(ack.Direct) + l.lastHeard = now + l.lastPingSent = now + l.probeSentAt = time.Time{} + l.probeDeadline = time.Time{} + if l.idleSince.IsZero() || now.After(l.idleSince) { + l.idleSince = now + } + l.retryCount = 0 + l.baseWait = reconnectBase + l.offlineCap = false + l.immediateRedial = false + l.budgetExhausted = false + l.lastReason = "" + + kind := Live + if !ack.Drive { + kind = WatchOnly + } + notify = l.setStateLocked(State{ + Kind: kind, + Since: now, + Permit: permit, + Road: road, + }) + l.resetLivenessTimerLocked(now) + l.mu.Unlock() + + l.wake() + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } + return mux, nil +} + +func (l *Link) handleDialFailure(err error) { + now := l.clock.Now() + var notify *State + l.mu.Lock() + if l.closed || l.revoked { + l.mu.Unlock() + return + } + if reason, ok := ReasonOf(err); ok && (reason == ReasonRemoved || reason == ReasonNotAllowed) { + l.revoked = true + l.lastReason = reason + l.stopLivenessTimerLocked() + l.stopRedialTimerLocked() + notify = l.setStateLocked(State{ + Kind: Revoked, + Reason: reason, + Since: now, + Permit: pair.Permit{}, + Road: l.road, + }) + l.mu.Unlock() + l.wake() + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } + l.settleRevocation() + return + } + + if errors.Is(err, ErrHostOffline) { + l.offlineCap = true + notify = l.setStateLocked(State{ + Kind: WentOffline, + Since: now, + Permit: l.permit, + Road: l.road, + }) + } else if l.state.Kind != WentOffline { + notify = l.setStateLocked(State{ + Kind: Reconnecting, + Since: now, + Permit: l.permit, + Road: l.road, + }) + } + l.scheduleRedialLocked(now) + l.mu.Unlock() + + l.wake() + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } +} + +func (l *Link) recordHeard() { + now := l.clock.Now() + var woke bool + l.mu.Lock() + l.lastHeard = now + if !l.probeDeadline.IsZero() && !now.Before(l.probeSentAt) { + l.probeDeadline = time.Time{} + } + l.standbyAnsweredLocked(now) + if l.mux != nil && l.cfg.Active != nil && l.cfg.Active() { + l.lastActive = now + if now.After(l.idleSince) { + l.idleSince = now + } + // If the link transitioned from idle to active because a turn started + // streaming frames, switch the timer to active ping mode immediately. + if l.livenessTimer == nil || l.livenessAt.After(now.Add(l.limits.PingEvery)) { + l.resetLivenessTimerLocked(now) + woke = true + } + } + l.mu.Unlock() + if woke { + l.wake() + } +} + +func (l *Link) isActiveLocked(now time.Time) bool { + cfgActive := l.cfg.Active != nil && l.cfg.Active() + if cfgActive { + l.lastActive = now + if now.After(l.idleSince) { + l.idleSince = now + } + } + touchActive := !l.lastTouch.IsZero() && now.Sub(l.lastTouch) < l.limits.ActiveWindow + return cfgActive || touchActive +} + +// sameShown reports whether two states are the same to a person: the four +// fields OnState fires on. Since is deliberately left out, so a state that is +// written again keeps the time it began. +func sameShown(a, b State) bool { + return a.Kind == b.Kind && a.Reason == b.Reason && a.Permit == b.Permit && a.Road == b.Road +} + +// setStateLocked records a RELAY state and returns the one a caller must be +// told about, or nil. While the relay carries it is exactly the phase 1 rule: +// the state is stored and shown, and a change of Kind, Reason, Permit or Road is +// reported. While the direct road carries, a relay event is stored silently, +// because a person is looking at the direct road and a relay state (a spent +// budget, a tunnel that ended) is not about it. +func (l *Link) setStateLocked(next State) *State { + if l.carrying == RoadDirect { + if !sameShown(l.state, next) { + l.state = next + } + return nil + } + if sameShown(l.shown, next) { + return nil + } + l.state = next + l.shown = next + cp := next + return &cp +} + +// channelCountLocked counts the channels that keep the link attached: the +// relay's and the direct road's. Idle is decided over both, because a person +// looking at a view on the direct road is as present as one on the relay. +func (l *Link) channelCountLocked() int { + return len(l.channels) + len(l.dchannels) +} + +func (l *Link) stopLivenessTimerLocked() { + if l.livenessTimer != nil { + l.livenessTimer.Stop() + l.livenessTimer = nil + l.livenessAt = time.Time{} + } +} + +func (l *Link) stopRedialTimerLocked() { + if l.redialTimer != nil { + l.redialTimer.Stop() + l.redialTimer = nil + l.redialAt = time.Time{} + } +} + +func (l *Link) setLivenessTimerAtLocked(now, target time.Time) { + if l.livenessTimer != nil && l.livenessAt.Equal(target) { + return + } + l.stopLivenessTimerLocked() + wait := target.Sub(now) + if wait <= 0 { + wait = time.Nanosecond + } + l.livenessAt = target + l.livenessTimer = l.clock.NewTimer(wait) +} + +func (l *Link) resetLivenessTimerLocked(now time.Time) { + if l.closed || l.revoked { + l.stopLivenessTimerLocked() + return + } + if l.carrying == RoadDirect { + l.resetDirectIdleTimerLocked(now) + return + } + if l.mux == nil { + l.stopLivenessTimerLocked() + return + } + + if l.isActiveLocked(now) { + deadAt := l.lastHeard.Add(l.limits.PingEvery + l.limits.DeadAfter) + if !l.probeDeadline.IsZero() { + if l.lastHeard.Before(l.probeSentAt) { + deadAt = l.probeDeadline + } else { + l.probeDeadline = time.Time{} + } + } + + pingAt := l.lastPingSent.Add(l.limits.PingEvery) + nextAt := pingAt + if deadAt.Before(nextAt) { + nextAt = deadAt + } + if (l.cfg.Active == nil || !l.cfg.Active()) && !l.lastTouch.IsZero() { + activeEnd := l.lastTouch.Add(l.limits.ActiveWindow) + if activeEnd.After(now) && activeEnd.Before(nextAt) { + nextAt = activeEnd + } + } + l.setLivenessTimerAtLocked(now, nextAt) + return + } + + // While NOT active, never schedule a repeating ping tick. If no channels + // are open, schedule zero timers; otherwise arm only the single one-shot + // IdleDetach timer. + if l.channelCountLocked() == 0 { + l.stopLivenessTimerLocked() + return + } + if l.idleSince.IsZero() { + l.idleSince = now + } + detachAt := l.idleSince.Add(l.limits.IdleDetach) + l.setLivenessTimerAtLocked(now, detachAt) +} + +func (l *Link) scheduleRedialLocked(now time.Time) { + // A nested direct link never redials by itself (the outer ladder owns every + // direct redial), and the relay is never redialled while the direct road + // carries: it is dialled on demand when the direct road falls back. + if l.closed || l.revoked || l.redialTimer != nil || l.noAutoRedial || l.carrying == RoadDirect { + return + } + var wait time.Duration + switch { + case l.immediateRedial: + l.immediateRedial = false + wait = time.Nanosecond + case l.offlineCap: + l.offlineCap = false + l.baseWait = reconnectCap + if l.retryCount < 4 { + l.retryCount = 4 + } + wait = relay.Jitter(reconnectCap) + case l.retryCount == 0: + l.baseWait = reconnectBase + l.retryCount = 1 + wait = relay.FirstRetry() + default: + l.baseWait *= 2 + if l.baseWait > reconnectCap { + l.baseWait = reconnectCap + } + l.retryCount++ + wait = relay.Jitter(l.baseWait) + } + if wait <= 0 { + wait = time.Nanosecond + } + l.redialAt = now.Add(wait) + l.redialTimer = l.clock.NewTimer(wait) +} + +func (l *Link) handleLivenessTick() { + now := l.clock.Now() + l.mu.Lock() + mux := l.mux + l.livenessTimer = nil + l.livenessAt = time.Time{} + if l.carrying == RoadDirect && !l.closed && !l.revoked { + // The direct road carries: the relay is silent and only idleness is + // decided here. + l.mu.Unlock() + l.handleDirectIdleTick(now) + return + } + if l.closed || l.revoked || mux == nil { + l.mu.Unlock() + return + } + + if l.isActiveLocked(now) { + deadAt := l.lastHeard.Add(l.limits.PingEvery + l.limits.DeadAfter) + if !l.probeDeadline.IsZero() { + if l.lastHeard.Before(l.probeSentAt) { + deadAt = l.probeDeadline + } else { + l.probeDeadline = time.Time{} + } + } + + if !now.Before(deadAt) { + // Active host liveness deadline exceeded: close the tunnel, mark the + // host WentOffline, and schedule a jittered redial. + l.mux = nil + l.relayLostLocked() + l.channels = make(map[uint32]*trackedChannel) + l.retryCount = 0 + l.baseWait = reconnectBase + notify := l.setStateLocked(State{ + Kind: WentOffline, + Since: now, + Permit: l.permit, + Road: l.road, + }) + l.scheduleRedialLocked(now) + l.mu.Unlock() + + _ = mux.Close() + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } + return + } + + pingAt := l.lastPingSent.Add(l.limits.PingEvery) + if !now.Before(pingAt) { + l.pingSeq++ + seq := l.pingSeq + l.lastPingSent = now + _ = mux.SendPing(seq) + } + l.resetLivenessTimerLocked(now) + l.mu.Unlock() + return + } + + // Not active: check whether IdleDetach has elapsed. + if l.channelCountLocked() == 0 { + l.mu.Unlock() + return + } + detachAt := l.idleSince.Add(l.limits.IdleDetach) + if !now.Before(detachAt) { + l.detachIdleLocked(now, mux) + return + } + l.resetLivenessTimerLocked(now) + l.mu.Unlock() +} + +func (l *Link) detachIdleLocked(now time.Time, mux *Mux) { + l.mux = nil + l.stopLivenessTimerLocked() + l.stopRedialTimerLocked() + l.relayLostLocked() + l.bumpRoadGenLocked() + + ended := make([]*trackedChannel, 0, len(l.channels)) + for _, tc := range l.channels { + tc.setLocalReason(ReasonIdle) + ended = append(ended, tc) + } + l.channels = make(map[uint32]*trackedChannel) + onEnd := l.onChannelEnd + + notify := l.setStateLocked(State{ + Kind: Idle, + Reason: ReasonIdle, + Since: now, + Permit: l.permit, + Road: l.road, + }) + l.mu.Unlock() + + // Stamp the mux channels locally under mux.mu before closing the mux so no + // frame is written to the wire and Channel.Reason() reports "idle". + mux.mu.Lock() + for _, ch := range mux.channels { + if ch.reason == "" { + ch.reason = ReasonIdle + } + ch.ended = true + } + mux.mu.Unlock() + + _ = mux.Close() + + if onEnd != nil { + for _, tc := range ended { + tc := tc + tc.endOnce.Do(func() { + onEnd(tc.chat, ReasonIdle) + }) + } + } + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } +} + +// applyChannelReasonLocked is what a SPOKEN channel end changes in the link, +// for a relay channel and a direct one alike: the revoked, budget and +// permit-changed postures and the immediate-redial flags. It returns the state +// the caller must announce, or nil. current says whether the channel belonged to +// the tunnel that is current now (the relay mux for a relay channel, the nested +// direct mux for a direct one), because a channel of an old tunnel must not move +// the state of its replacement. +func (l *Link) applyChannelReasonLocked(reason string, now time.Time, current, onDirect bool) *State { + road := l.road + show := l.setStateLocked + shownKind := l.state.Kind + if onDirect { + road = RoadDirect + show = l.directShownLocked + shownKind = l.shown.Kind + } + + switch reason { + case ReasonRemoved: + return l.markRevokedLocked(ReasonRemoved, now) + case ReasonRemoteControlOff: + // THE HOST IS UP AND SAID WHY: a view that was open on it ends, no timer + // redials it, and the state says so in the host's own words. It is the + // revoked posture on purpose, and it differs from a removal in one way + // only: the next view a person opens dials again ([Link.resumeAfterHostOff]). + return l.markRevokedLocked(ReasonRemoteControlOff, now) + case ReasonBudget: + l.budgetExhausted = true + l.permit.Drive = false + l.lastReason = ReasonBudget + if current && !l.revoked { + return show(State{ + Kind: StateBudget, + Reason: ReasonBudget, + Since: now, + Permit: l.permit, + Road: road, + }) + } + case ReasonPermitChanged: + l.lastReason = ReasonPermitChanged + l.immediateRedial = true + l.permit.Drive = false + if current && !l.revoked && (shownKind == Live || shownKind == WatchOnly) { + return show(State{ + Kind: WatchOnly, + Reason: ReasonPermitChanged, + Since: now, + Permit: l.permit, + Road: road, + }) + } + case ReasonLagging: + l.immediateRedial = true + } + return nil +} + +// markRevokedLocked records that the host removed this viewer, stops every +// timer that would try again, and returns the Revoked state to announce. While +// the direct road carries the state is stored silently (it is a relay write); +// settleRevocation then takes the road down and announces it. +func (l *Link) markRevokedLocked(reason string, now time.Time) *State { + l.revoked = true + l.lastReason = reason + l.stopLivenessTimerLocked() + l.stopRedialTimerLocked() + return l.setStateLocked(State{ + Kind: Revoked, + Reason: reason, + Since: now, + Permit: pair.Permit{}, + Road: l.road, + }) +} + +func (l *Link) handleChannelDone(mux *Mux, tc *trackedChannel) { + reason := tc.reason() + now := l.clock.Now() + + var ( + notify *State + onEnd func(chat, reason string) + ) + l.mu.Lock() + if cur, ok := l.channels[tc.ch.ID()]; ok && cur == tc { + delete(l.channels, tc.ch.ID()) + } + onEnd = l.onChannelEnd + + notify = l.applyChannelReasonLocked(reason, now, l.mux == mux, false) + + if l.mux == mux && !l.closed && !l.revoked { + l.resetLivenessTimerLocked(now) + } + l.mu.Unlock() + l.wake() + + // A road-change is the link's own doing and is never spoken, so it is never + // reported as the end of a channel. + if reason != "" && reason != ReasonRoadChange && onEnd != nil { + tc.endOnce.Do(func() { + onEnd(tc.chat, reason) + }) + } + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } + l.settleRevocation() +} + +func (l *Link) handleTunnelDone(mux *Mux) { + now := l.clock.Now() + var ( + notify *State + ended []*trackedChannel + onEnd func(chat, reason string) + ) + + l.mu.Lock() + if l.mux != mux { + l.mu.Unlock() + return + } + l.mux = nil + l.stopLivenessTimerLocked() + if l.carrying == RoadDirect { + // The relay tunnel ended while it was only the silent standby of the + // direct road. Nothing a person sees depends on it, so it is dropped + // without a state change, a redial timer or a notification: it is dialled + // again on demand when the direct road falls back. + l.sbProbeAt = time.Time{} + l.releaseStandbyWaitLocked() + l.hostDirect = false + l.resetLivenessTimerLocked(now) + l.mu.Unlock() + l.wake() + return + } + l.relayLostLocked() + onEnd = l.onChannelEnd + + for _, tc := range l.channels { + ended = append(ended, tc) + switch tc.reason() { + case ReasonRemoved: + l.revoked = true + l.lastReason = ReasonRemoved + case ReasonRemoteControlOff: + l.revoked = true + l.lastReason = ReasonRemoteControlOff + case ReasonPermitChanged: + l.immediateRedial = true + l.lastReason = ReasonPermitChanged + case ReasonLagging: + l.immediateRedial = true + case ReasonBudget: + l.budgetExhausted = true + l.lastReason = ReasonBudget + } + } + l.channels = make(map[uint32]*trackedChannel) + + if !l.closed { + if l.revoked { + l.stopRedialTimerLocked() + reason := l.lastReason + if reason == "" { + reason = ReasonRemoved + } + notify = l.setStateLocked(State{ + Kind: Revoked, + Reason: reason, + Since: now, + Permit: pair.Permit{}, + Road: l.road, + }) + } else { + kind := Reconnecting + if !l.isActiveLocked(now) { + kind = WentOffline + } + notify = l.setStateLocked(State{ + Kind: kind, + Reason: l.lastReason, + Since: now, + Permit: l.permit, + Road: l.road, + }) + l.retryCount = 0 + l.baseWait = reconnectBase + l.scheduleRedialLocked(now) + } + } + l.mu.Unlock() + l.wake() + + if onEnd != nil { + for _, tc := range ended { + tc := tc + if r := tc.reason(); r != "" && r != ReasonRoadChange { + tc.endOnce.Do(func() { + onEnd(tc.chat, r) + }) + } + } + } + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } + l.settleRevocation() +} + +func (l *Link) handleRedialTick() { + l.mu.Lock() + l.redialTimer = nil + l.redialAt = time.Time{} + if l.closed || l.revoked || l.mux != nil { + l.mu.Unlock() + return + } + l.mu.Unlock() + + _, _ = l.ensureConnected(context.Background()) +} + +func (l *Link) loop() { + for { + l.mu.Lock() + if l.closed { + l.mu.Unlock() + return + } + var ( + livenessC <-chan time.Time + redialC <-chan time.Time + attemptC <-chan time.Time + probeC <-chan time.Time + muxDoneC <-chan struct{} + curMux = l.mux + curAttempt = l.dtimer + curProbe = l.ptimer + ) + if l.livenessTimer != nil { + livenessC = l.livenessTimer.C() + } + if l.redialTimer != nil { + redialC = l.redialTimer.C() + } + if l.dtimer != nil { + attemptC = l.dtimer.C() + } + if l.ptimer != nil { + probeC = l.ptimer.C() + } + if curMux != nil { + muxDoneC = curMux.Done() + } + l.mu.Unlock() + + select { + case <-l.stopCh: + return + case <-l.wakeCh: + case <-muxDoneC: + l.handleTunnelDone(curMux) + case <-livenessC: + l.handleLivenessTick() + case <-redialC: + l.handleRedialTick() + case <-attemptC: + l.handleAttemptTick(curAttempt) + case <-probeC: + l.handleDirectProbeTick(curProbe) + } + } +} diff --git a/internal/livedoor/link_direct.go b/internal/livedoor/link_direct.go new file mode 100644 index 0000000000..83591ea36e --- /dev/null +++ b/internal/livedoor/link_direct.go @@ -0,0 +1,1134 @@ +package livedoor + +import ( + "context" + "errors" + "io" + "sync" + "sync/atomic" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" +) + +// This file is the viewer's direct road. A Link that was given a DirectConfig +// keeps the relay view exactly as phase 1 does, and after the first channel is +// open it tries, quietly and on a ladder of waits, to build a second tunnel +// straight to the host. The second tunnel is a NESTED Link of the same type +// (so it has its own mux, its own liveness and its own state) whose every +// event is private to the outer link. When the nested link is Live the outer +// link swaps roads with a planned redial, and when it dies the outer link falls +// back the same way. A person sees only the road word change. +// +// THE OUTER LINK OWNS EVERYTHING THE PERSON SEES. The nested link never raises +// an OnState of the outer link by itself, never redials by itself, and is dialled +// only from an attempt. + +// outerSignaller lets the direct-road implementation signal through the outer +// link's CURRENT relay tunnel, so an attempt that outlives a reconnect talks on +// the tunnel that exists now. +type outerSignaller struct { + l *Link +} + +func (s outerSignaller) Send(payload []byte) error { + return s.l.SendSignal(payload) +} + +// directRun is one attempt to build the direct road. Its token says whether the +// attempt is still the current one, and its context is cancelled by the +// connect deadline, by closing the link, by an idle detach, by a revocation and +// by the end of the relay tunnel it started on. +type directRun struct { + tok uint64 + nested *Link + relay *Mux + ctx context.Context + cancel context.CancelFunc +} + +// directChannel is a channel opened on the nested link's tunnel, tracked and +// wrapped by the OUTER link so that the way it ends is the outer link's to +// describe: a tunnel that died under it is a planned redial, a reason the host +// spoke is passed through unchanged. +type directChannel struct { + l *Link + ch *Channel + mux *Mux + chat string + + closedLocally atomic.Bool + endOnce sync.Once + + mu sync.Mutex + localReason string +} + +func (dc *directChannel) setLocalReason(reason string) { + dc.mu.Lock() + defer dc.mu.Unlock() + if dc.localReason == "" { + dc.localReason = reason + } +} + +func (dc *directChannel) local() string { + dc.mu.Lock() + defer dc.mu.Unlock() + return dc.localReason +} + +// reason is the reason this channel ended with: the one the outer link gave it, +// else the one the host spoke. +func (dc *directChannel) reason() string { + if r := dc.local(); r != "" { + return r + } + return dc.ch.Reason() +} + +// Reason returns the closed-set reason the channel ended with, or "". +func (dc *directChannel) Reason() string { return dc.reason() } + +// ID returns the channel's wire identifier on the nested tunnel. +func (dc *directChannel) ID() uint32 { return dc.ch.ID() } + +// Done is closed when the channel ends for any reason. +func (dc *directChannel) Done() <-chan struct{} { return dc.ch.Done() } + +// Close closes the channel because the person asked to, which is never a road +// change. +func (dc *directChannel) Close() error { + dc.closedLocally.Store(true) + return dc.ch.Close() +} + +func (dc *directChannel) Read(p []byte) (int, error) { + n, err := dc.ch.Read(p) + if err != nil { + return n, dc.endError(err, io.EOF) + } + return n, nil +} + +func (dc *directChannel) Write(p []byte) (int, error) { + n, err := dc.ch.Write(p) + if err != nil { + return n, dc.endError(err, io.ErrClosedPipe) + } + return n, nil +} + +// endError says how a direct channel ended. ANY end that is not a reason the +// host spoke and not the person closing it is a planned redial, because the +// only things that can end it are the direct tunnel dying and the outer link +// moving the view, and both are answered the same way: open the channel again +// on the road that carries now. +func (dc *directChannel) endError(err, plain error) error { + if r := dc.local(); r != "" { + return &ChannelError{Op: "close", Why: r, Err: plain} + } + var ce *ChannelError + if errors.As(err, &ce) && ce != nil && ce.Why != "" { + return err + } + if dc.closedLocally.Load() || dc.l.isClosed() { + return err + } + if dc.ch.Reason() != "" { + return err + } + return &ChannelError{Op: "close", Why: ReasonRoadChange, Err: plain} +} + +func (l *Link) isClosed() bool { + l.mu.Lock() + defer l.mu.Unlock() + return l.closed +} + +// stampMuxChannels gives every channel of mux a local reason and marks it +// ended, so that no frame is written for it and Channel.Reason() reports the +// reason. It is how an idle detach ends channels "with nothing sent first". +func stampMuxChannels(mux *Mux, reason string) { + mux.mu.Lock() + defer mux.mu.Unlock() + for _, ch := range mux.channels { + if ch.reason == "" { + ch.reason = reason + } + ch.ended = true + } +} + +// detachWithReason closes a link for good with a reason, sending nothing and +// telling nobody: it stamps the mux channels, closes the mux and stops the +// loop. The outer link uses it on its nested direct link when it goes idle. +func (l *Link) detachWithReason(reason string) { + var mux *Mux + func() { + l.mu.Lock() + defer l.mu.Unlock() + if l.closed { + return + } + l.closed = true + l.stopLivenessTimerLocked() + l.stopRedialTimerLocked() + mux = l.mux + l.mux = nil + l.channels = make(map[uint32]*trackedChannel) + }() + l.stopOnce.Do(func() { + close(l.stopCh) + }) + if mux != nil { + stampMuxChannels(mux, reason) + _ = mux.Close() + } +} + +// heardAt is when the link last heard anything from its host. The outer link +// reads it from the nested link to see the first missed pong. +func (l *Link) heardAt() time.Time { + l.mu.Lock() + defer l.mu.Unlock() + return l.lastHeard +} + +// snapshotState is the link's state without the side effects State() has, so +// the outer link can read the nested one while holding its own lock. +func (l *Link) snapshotState() State { + l.mu.Lock() + defer l.mu.Unlock() + return l.state +} + +// bumpRoadGenLocked counts an idle detach as a change of road, but only on a +// link that has a direct road to change: a link without one behaves exactly as +// it did before there was one. +func (l *Link) bumpRoadGenLocked() { + if l.cfg.Direct != nil { + l.roadGen++ + } +} + +// relayEstablishedLocked records what a new relay tunnel says about the host +// and starts the ladder over. A new tunnel is a new host session, so an +// attempt that began on the old one is abandoned and the waits begin again. +func (l *Link) relayEstablishedLocked(hostDirect bool) { + l.hostDirect = hostDirect + l.abortAttemptLocked() + l.dfails = 0 + l.sbProbeAt = time.Time{} + l.releaseStandbyWaitLocked() +} + +// relayLostLocked records that the relay tunnel is gone for a reason that ends +// the view's use of it: whatever attempt was running on it cannot succeed. +func (l *Link) relayLostLocked() { + l.hostDirect = false + l.abortAttemptLocked() + l.sbProbeAt = time.Time{} + l.releaseStandbyWaitLocked() +} + +// abortAttemptLocked abandons the attempt that is running, if any, and the +// timer that would start the next one. The attempt's goroutine closes the nested +// link it was building, outside the lock, when its dial returns. +func (l *Link) abortAttemptLocked() { + l.attemptTok++ + if l.dtimer != nil { + l.dtimer.Stop() + l.dtimer = nil + } + if run := l.drun; run != nil { + run.cancel() + l.drun = nil + if l.direct == run.nested && l.carrying != RoadDirect { + l.direct = nil + } + } +} + +func (l *Link) stopProbeTimerLocked() { + if l.ptimer != nil { + l.ptimer.Stop() + l.ptimer = nil + } +} + +// dropDirectLocked takes the direct road away entirely: no attempt, no timer, +// no nested link, nothing carrying. It returns the nested link, which the +// caller closes after releasing the lock. +func (l *Link) dropDirectLocked() *Link { + nested := l.direct + l.abortAttemptLocked() + l.stopProbeTimerLocked() + l.sbProbeAt = time.Time{} + l.releaseStandbyWaitLocked() + l.direct = nil + l.directMux = nil + l.carrying = RoadRelay + l.dchannels = make(map[*directChannel]struct{}) + return nested +} + +// directShownLocked updates what State() reports from a direct posture and +// returns the one state to announce, or nil. Road is always "direct" here. +func (l *Link) directShownLocked(next State) *State { + next.Road = RoadDirect + if sameShown(l.shown, next) { + return nil + } + l.shown = next + cp := next + return &cp +} + +// showRelayLocked makes State() report the relay's own state again and returns +// the one state to announce, or nil. +func (l *Link) showRelayLocked() *State { + prev := l.shown + l.shown = l.state + if sameShown(prev, l.state) { + return nil + } + cp := l.state + return &cp +} + +// newNestedLink builds the link that will carry the direct road. Its Dial is the +// direct implementation's, signalling through this link's relay tunnel; its +// limits are the direct road's (a one-second ping and a three-second death); it +// is always active, because that ping IS its liveness and costs the relay +// nothing; and its OnState is private to this link. +func (l *Link) newNestedLink() *Link { + var nested *Link + nested = NewLink(LinkConfig{ + Home: l.cfg.Home, + Identity: l.cfg.Identity, + Host: l.cfg.Host, + HostName: l.cfg.HostName, + Clock: l.clock, + Limits: DirectLimits(), + Active: func() bool { return true }, + Dial: func(ctx context.Context) (io.ReadWriteCloser, error) { + if l.cfg.Direct == nil || l.cfg.Direct.Dial == nil { + return nil, &ReasonError{Host: l.cfg.HostName, Err: errors.New("livedoor: missing direct Dial function")} + } + return l.cfg.Direct.Dial(ctx, outerSignaller{l}) + }, + OnState: func(s State) { l.directState(nested, s) }, + }) + nested.noAutoRedial = true + return nested +} + +// directEligibleLocked says whether an attempt may start now: the host offered +// a direct road on THIS relay tunnel, the relay carries and is alive, a view is +// open, the link is not idle, revoked or closed, and no attempt is running. +func (l *Link) directEligibleLocked() bool { + if l.cfg.Direct == nil || l.cfg.Direct.Dial == nil || !l.hostDirect { + return false + } + if l.carrying == RoadDirect || l.closed || l.revoked || l.drun != nil { + return false + } + if l.mux == nil || len(l.channels) == 0 || l.state.Kind == Idle { + return false + } + select { + case <-l.mux.Done(): + return false + default: + } + return true +} + +// maybeScheduleDirectAttempt arms the one timer that starts the next attempt, +// if an attempt is allowed and none is already waiting. The first attempt of a +// relay tunnel waits DirectSettle after the first channel opens, so the first +// paint never waits on the path finding; later ones wait DirectBackoff after a +// failure. +func (l *Link) maybeScheduleDirectAttempt() { + if l.cfg.Direct == nil { + return + } + l.mu.Lock() + defer l.mu.Unlock() + l.armDirectAttemptLocked() +} + +func (l *Link) armDirectAttemptLocked() { + if l.dtimer != nil || !l.directEligibleLocked() { + return + } + wait := DirectSettle + if l.dfails > 0 && len(DirectBackoff) > 0 { + idx := l.dfails - 1 + if idx >= len(DirectBackoff) { + idx = len(DirectBackoff) - 1 + } + wait = DirectBackoff[idx] + } + l.dtimer = l.clock.NewTimer(wait) + l.wake() +} + +// handleAttemptTick starts an attempt when the attempt timer fires and an +// attempt is still allowed. It runs on the link's loop, so the attempt itself +// runs on its own goroutine. +func (l *Link) handleAttemptTick(fired Timer) { + var run *directRun + func() { + l.mu.Lock() + defer l.mu.Unlock() + if l.dtimer == nil || l.dtimer != fired { + return + } + l.dtimer = nil + if !l.directEligibleLocked() { + return + } + l.attemptTok++ + ctx, cancel := context.WithCancel(context.Background()) + run = &directRun{ + tok: l.attemptTok, + nested: l.newNestedLink(), + relay: l.mux, + ctx: ctx, + cancel: cancel, + } + l.drun = run + l.direct = run.nested + }() + if run == nil { + return + } + guard.Go("livedoor.link.direct-attempt", func() { + l.runDirectAttempt(run) + }) +} + +// runDirectAttempt dials the nested link, the one place it is ever dialled, and +// then either swaps roads or fails silently. The attempt gets DirectConnectWithin +// on the link's own clock, and it ends early when the link closes or the relay +// tunnel it started on ends. +func (l *Link) runDirectAttempt(run *directRun) { + deadline := l.clock.NewTimer(DirectConnectWithin) + finished := make(chan struct{}) + guard.Go("livedoor.link.direct-deadline", func() { + defer deadline.Stop() + select { + case <-deadline.C(): + run.cancel() + case <-run.relay.Done(): + run.cancel() + case <-l.stopCh: + run.cancel() + case <-finished: + } + }) + + run.nested.startLoop() + nmux, err := run.nested.ensureConnected(run.ctx) + close(finished) + // The context is cancelled only when the attempt fails: a direct tunnel that + // was built with it must outlive the attempt, and an implementation may tie + // the connection's lifetime to the context it was dialled with. + if err != nil { + l.directAttemptFailed(run, err) + return + } + l.directBecameLive(run, nmux) +} + +// directAttemptFailed ends an attempt without a word to anyone: no state, no +// notification, no banner. It counts the failure and arms the next wait, unless +// the attempt was abandoned on purpose (a stale token), in which case whatever +// abandoned it already decided what happens next. +func (l *Link) directAttemptFailed(run *directRun, err error) { + run.cancel() + func() { + l.mu.Lock() + defer l.mu.Unlock() + if l.drun == run { + l.drun = nil + } + if l.direct == run.nested && l.carrying != RoadDirect { + l.direct = nil + } + if l.attemptTok == run.tok && !l.closed { + l.dfails++ + l.armDirectAttemptLocked() + } + }() + run.nested.Close() + if reason, ok := ReasonOf(err); ok && reason == ReasonRemoved { + // The host said the removal itself on the direct road, which is the same + // news as on the relay: the whole link is revoked. + l.noteOpenRefusal(ReasonRemoved) + } +} + +// directBecameLive swaps the carrying road to the direct one. +// +// THE ORDER IS A LAW, and it is what makes a swap safe: (i) the direct road is +// recorded as the one that carries and the single state change is computed, so +// every open from this moment on goes direct; (ii) every channel the relay holds +// is given the local reason road-change and closed with a normal CLOSE, which +// ends its next Read or Write with a planned redial; (iii) the state change is +// delivered only after the locks are released. The relay tunnel stays attached +// and SILENT: no ping and no frame but those CLOSEs. +func (l *Link) directBecameLive(run *directRun, nmux *Mux) { + var ( + notify *State + swapped []*trackedChannel + ok bool + ) + func() { + l.mu.Lock() + defer l.mu.Unlock() + snap := run.nested.snapshotState() + if l.closed || l.revoked || l.attemptTok != run.tok || l.carrying == RoadDirect || + l.direct != run.nested || l.mux == nil || l.mux != run.relay || + l.state.Kind == Idle || len(l.channels) == 0 || + (snap.Kind != Live && snap.Kind != WatchOnly) { + return + } + select { + case <-nmux.Done(): + return + default: + } + ok = true + now := l.clock.Now() + l.drun = nil + + l.carrying = RoadDirect + l.roadGen++ + l.directMux = nmux + l.directSince = now + l.sbProbed = false + l.sbProbeAt = time.Time{} + l.releaseStandbyWaitLocked() + notify = l.directShownLocked(snap) + l.stopLivenessTimerLocked() + + for _, tc := range l.channels { + tc.setLocalReason(ReasonRoadChange) + swapped = append(swapped, tc) + } + l.channels = make(map[uint32]*trackedChannel) + l.resetLivenessTimerLocked(now) + l.armProbeLocked() + }() + if !ok { + l.directAttemptFailed(run, nil) + return + } + + for _, tc := range swapped { + // OnChannelEnd is never told about a road change: the channel's end is the + // link's own doing and not a thing the host said. + tc.endOnce.Do(func() {}) + _ = tc.ch.Close() + } + nested := run.nested + guard.Go("livedoor.link.direct-watch", func() { + select { + case <-nmux.Done(): + l.directWentDown(nested, nmux) + case <-l.stopCh: + } + }) + l.wake() + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } +} + +// directState consumes the nested link's OnState, which is private to this +// link. It only matters while the direct road carries: a nested link that is no +// longer Live ends the direct road, and one that changed permit updates what +// the person sees. A callback from a nested link that is not the current one is +// ignored, so an old tunnel's death cannot demote its replacement. +func (l *Link) directState(nested *Link, s State) { + var ( + notify *State + down bool + ) + func() { + l.mu.Lock() + defer l.mu.Unlock() + if l.direct != nested || l.carrying != RoadDirect { + return + } + switch s.Kind { + case Live, WatchOnly: + notify = l.directShownLocked(s) + default: + down = true + } + }() + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } + if down { + l.directWentDown(nested, nil) + } +} + +// directWentDown is the fallback: the direct road is gone and the relay carries +// again. nested and mux say which tunnel went down (mux nil means any), and a +// report about a tunnel that is not the current one is ignored. +// +// THE ORDER IS A LAW: (i) the relay is recorded as carrying and the one state +// change is computed; (ii) every direct channel is given the local reason +// road-change, so its next Read or Write reports a planned redial, and the +// nested link is closed after the lock is released; (iii) the ladder counts a +// failure unless the direct road had been up for DirectStableAfter; (iv) the +// relay standby is made usable: kept if it answered the probe, retired if it +// did not, and dialled on demand when there is none. +func (l *Link) directWentDown(nested *Link, mux *Mux) { + var ( + notify *State + retire *Mux + ping *Mux + pingSeq uint32 + dialRelay bool + ) + func() { + l.mu.Lock() + defer l.mu.Unlock() + if l.closed || l.carrying != RoadDirect || l.direct != nested || (mux != nil && l.directMux != mux) { + return + } + now := l.clock.Now() + stable := now.Sub(l.directSince) >= DirectStableAfter + + l.carrying = RoadRelay + l.roadGen++ + l.direct = nil + l.directMux = nil + l.stopProbeTimerLocked() + notify = l.showRelayLocked() + + for dc := range l.dchannels { + if dc.ch.Reason() == "" { + dc.setLocalReason(ReasonRoadChange) + } + } + l.dchannels = make(map[*directChannel]struct{}) + + if stable { + l.dfails = 0 + } else { + l.dfails++ + } + + standby := l.mux + if standby != nil { + select { + case <-standby.Done(): + l.mux = nil + standby = nil + default: + } + } + switch { + case standby == nil: + // Nothing to do here: the next open dials the relay, with phase 1's own + // dial, backoff and states. + case !l.sbProbeAt.IsZero(): + if !now.Before(l.sbProbeAt.Add(DirectPingEvery)) { + retire = standby + l.mux = nil + l.sbProbeAt = time.Time{} + l.releaseStandbyWaitLocked() + l.relayLostLocked() + dialRelay = true + } + case !l.sbProbed: + // The direct tunnel ended abruptly, before the first missed pong, so the + // standby has not been asked yet. Ask it now; it gets DirectPingEvery + // to answer before it is retired. + l.sbProbed = true + l.pingSeq++ + pingSeq = l.pingSeq + l.sbProbeAt = now + l.sbWait = make(chan struct{}) + ping = standby + } + l.armDirectAttemptLocked() + }() + // Closing the nested link is right when it was the current one, and harmless + // when the report was stale: either way it is a tunnel nobody uses. + nested.Close() + if retire != nil { + _ = retire.Close() + } + l.wake() + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } + if ping != nil { + _ = ping.SendPing(pingSeq) + guard.Go("livedoor.link.standby", func() { + if l.settleStandby(context.Background()) { + _, _ = l.ensureConnected(context.Background()) + } + }) + } + if dialRelay { + guard.Go("livedoor.link.standby-dial", func() { + _, _ = l.ensureConnected(context.Background()) + }) + } +} + +// armProbeLocked arms the ticker that watches the direct tunnel for its first +// missed pong. It exists only while the direct road carries. +func (l *Link) armProbeLocked() { + if l.ptimer != nil || l.carrying != RoadDirect || l.closed || l.revoked { + return + } + l.ptimer = l.clock.NewTimer(DirectPingEvery) + l.wake() +} + +// handleDirectProbeTick is the standby probe. The nested link pings every +// second and is dead three seconds after it last heard anything. At the FIRST +// missed pong, when it has heard nothing for more than one ping period, this +// asks the relay standby once whether it is alive, or starts dialling the relay +// at once if there is no standby, so the relay is up by the time the direct road +// is declared dead. The relay is pinged at most once per outage, and never +// otherwise while the direct road carries. +func (l *Link) handleDirectProbeTick(fired Timer) { + var ( + ping *Mux + pingSeq uint32 + dial bool + ) + func() { + l.mu.Lock() + defer l.mu.Unlock() + if l.ptimer == nil || l.ptimer != fired { + return + } + l.ptimer = nil + if l.carrying != RoadDirect || l.direct == nil || l.closed || l.revoked { + return + } + l.armProbeLocked() + now := l.clock.Now() + if l.sbProbed || now.Sub(l.direct.heardAt()) <= DirectPingEvery { + return + } + l.sbProbed = true + standby := l.mux + if standby != nil { + select { + case <-standby.Done(): + standby = nil + default: + } + } + if standby == nil { + dial = true + return + } + l.pingSeq++ + pingSeq = l.pingSeq + l.sbProbeAt = now + l.sbWait = make(chan struct{}) + ping = standby + }() + if ping != nil { + _ = ping.SendPing(pingSeq) + } + if dial { + guard.Go("livedoor.link.standby-dial", func() { + _, _ = l.ensureConnected(context.Background()) + }) + } +} + +// standbyAnsweredLocked records that the relay standby said something, which is +// the answer to the probe: the relay sends nothing on its own while the direct +// road carries. +func (l *Link) standbyAnsweredLocked(now time.Time) { + if l.sbProbeAt.IsZero() || now.Before(l.sbProbeAt) { + return + } + l.sbProbeAt = time.Time{} + l.releaseStandbyWaitLocked() +} + +func (l *Link) releaseStandbyWaitLocked() { + if l.sbWait != nil { + close(l.sbWait) + l.sbWait = nil + } +} + +// settleStandby waits for the answer to an outstanding standby probe and +// retires the standby if there is none within DirectPingEvery of the probe. It +// reports whether it retired one, in which case the caller dials the relay +// through ensureConnected (which serialises dials, so there is only ever one). +// With no probe outstanding it returns at once. +func (l *Link) settleStandby(ctx context.Context) bool { + if l.cfg.Direct == nil { + return false + } + for { + var ( + retired *Mux + wait chan struct{} + until time.Time + ) + func() { + l.mu.Lock() + defer l.mu.Unlock() + if l.carrying == RoadDirect || l.closed || l.sbProbeAt.IsZero() || l.mux == nil { + return + } + deadline := l.sbProbeAt.Add(DirectPingEvery) + if !l.clock.Now().Before(deadline) { + retired = l.mux + l.mux = nil + l.stopLivenessTimerLocked() + l.relayLostLocked() + return + } + wait = l.sbWait + until = deadline + }() + if retired != nil { + _ = retired.Close() + return true + } + if wait == nil { + return false + } + t := l.clock.NewTimer(until.Sub(l.clock.Now())) + select { + case <-wait: + t.Stop() + case <-t.C(): + case <-ctx.Done(): + t.Stop() + return false + case <-l.stopCh: + t.Stop() + return false + } + } +} + +// openDirect opens the chat on the direct road when it carries. It reports +// handled == false when the caller should go on to the relay: the direct road +// does not carry, or its tunnel died under the open (in which case the road is +// marked down first, so the relay path finds the relay carrying). A reason the +// host spoke is returned unchanged, because the relay would give the same +// answer. +func (l *Link) openDirect(ctx context.Context, chat string) (rwc io.ReadWriteCloser, handled bool, err error) { + var ( + nested *Link + mux *Mux + gen uint64 + ) + func() { + l.mu.Lock() + defer l.mu.Unlock() + if l.carrying != RoadDirect || l.closed || l.revoked || l.direct == nil || l.directMux == nil { + return + } + nested, mux, gen = l.direct, l.directMux, l.roadGen + }() + if mux == nil { + return nil, false, nil + } + select { + case <-mux.Done(): + l.directWentDown(nested, mux) + return nil, false, nil + default: + } + + ch, oerr := mux.Open(ctx, chat) + if oerr != nil { + var ref *RefusedError + if errors.As(oerr, &ref) && ref != nil { + l.noteOpenRefusal(ref.Reason) + return nil, true, &ReasonError{ + Reason: ref.Reason, + Host: l.cfg.HostName, + Err: oerr, + } + } + if ctx.Err() != nil { + return nil, true, l.wrapReasonError(oerr) + } + l.directWentDown(nested, mux) + return nil, false, nil + } + + dc := &directChannel{l: l, ch: ch, mux: mux, chat: chat} + var ( + stale bool + closed bool + ) + func() { + l.mu.Lock() + defer l.mu.Unlock() + if l.closed { + closed = true + return + } + if l.roadGen != gen || l.carrying != RoadDirect || l.direct != nested { + stale = true + return + } + now := l.clock.Now() + if l.channelCountLocked() == 0 && now.After(l.idleSince) { + l.idleSince = now + } + l.dchannels[dc] = struct{}{} + l.resetLivenessTimerLocked(now) + }() + if stale { + // A fallback committed while this channel was opening and so could not + // have seen it. It is closed outside the lock and the open is repeated. + _ = ch.Close() + return nil, true, errRoadMoved + } + if closed { + return dc, true, nil + } + l.wake() + guard.Go("livedoor.link.dchannel", func() { + select { + case <-ch.Done(): + l.handleDirectChannelDone(dc) + case <-l.stopCh: + } + }) + return dc, true, nil +} + +// handleDirectChannelDone is handleChannelDone for a channel of the direct road: +// a reason the host spoke has the same effect on the link it has on the relay, +// and a road change is never reported as the end of a channel. +func (l *Link) handleDirectChannelDone(dc *directChannel) { + reason := dc.reason() + now := l.clock.Now() + var ( + notify *State + onEnd func(chat, reason string) + ) + func() { + l.mu.Lock() + defer l.mu.Unlock() + delete(l.dchannels, dc) + onEnd = l.onChannelEnd + current := l.carrying == RoadDirect && l.directMux == dc.mux + notify = l.applyChannelReasonLocked(reason, now, current, true) + if current && !l.closed && !l.revoked { + l.resetLivenessTimerLocked(now) + } + }() + l.wake() + + if reason != "" && reason != ReasonRoadChange && onEnd != nil { + dc.endOnce.Do(func() { + onEnd(dc.chat, reason) + }) + } + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } + l.settleRevocation() +} + +// settleRevocation finishes a revocation that was recorded as a relay write: +// when the host has removed this viewer, no direct road may carry, be built or +// be attempted. It closes the nested link, ends the direct channels with the +// reason, and announces the revoked state if a direct road was what a person +// was looking at. It does nothing on a link that has no direct road. +func (l *Link) settleRevocation() { + if l.cfg.Direct == nil { + return + } + var ( + nested *Link + notify *State + ended []*directChannel + onEnd func(chat, reason string) + reason string + ) + func() { + l.mu.Lock() + defer l.mu.Unlock() + if !l.revoked { + return + } + if l.direct == nil && l.carrying != RoadDirect && l.drun == nil && l.dtimer == nil && + l.ptimer == nil && len(l.dchannels) == 0 { + return + } + reason = l.lastReason + if reason == "" { + reason = ReasonRemoved + } + onEnd = l.onChannelEnd + for dc := range l.dchannels { + dc.setLocalReason(reason) + ended = append(ended, dc) + } + wasDirect := l.carrying == RoadDirect + nested = l.dropDirectLocked() + if wasDirect { + l.roadGen++ + notify = l.showRelayLocked() + } + }() + if nested != nil { + nested.Close() + } + if onEnd != nil { + for _, dc := range ended { + dc := dc + dc.endOnce.Do(func() { + onEnd(dc.chat, reason) + }) + } + } + if notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*notify) + } +} + +// resetDirectIdleTimerLocked arms the one timer idleness needs while the direct +// road carries. There is no repeating relay ping and no relay liveness timer +// here: only a one-shot at the moment IdleDetach would elapse, or, while the +// person is active, a local re-check, which sends nothing to anyone. +func (l *Link) resetDirectIdleTimerLocked(now time.Time) { + if l.channelCountLocked() == 0 { + l.stopLivenessTimerLocked() + return + } + if l.isActiveLocked(now) { + next := now.Add(l.limits.PingEvery) + if l.cfg.Active == nil || !l.cfg.Active() { + if end := l.lastTouch.Add(l.limits.ActiveWindow); end.After(now) { + next = end + } + } + l.setLivenessTimerAtLocked(now, next) + return + } + if l.idleSince.IsZero() { + l.idleSince = now + } + l.setLivenessTimerAtLocked(now, l.idleSince.Add(l.limits.IdleDetach)) +} + +// directDetach is everything an idle detach of the direct road must do after the +// lock is released. +type directDetach struct { + relay *Mux + nested *Link + relayCh []*trackedChannel + directC []*directChannel + onEnd func(chat, reason string) + notify *State +} + +// handleDirectIdleTick decides idleness while the direct road carries. Idle is +// decided over relay and direct channels alike, and it belongs to this link, not +// to the nested link, whose ping would otherwise keep a view alive forever. +func (l *Link) handleDirectIdleTick(now time.Time) { + var detach *directDetach + func() { + l.mu.Lock() + defer l.mu.Unlock() + if l.carrying != RoadDirect || l.closed || l.revoked || l.channelCountLocked() == 0 { + return + } + if l.isActiveLocked(now) || now.Before(l.idleSince.Add(l.limits.IdleDetach)) { + l.resetDirectIdleTimerLocked(now) + return + } + detach = l.detachIdleDirectLocked(now) + }() + if detach != nil { + l.finishDirectDetach(detach) + } +} + +// detachIdleDirectLocked records an idle detach of BOTH roads: the relay mux +// and the nested link, one close each, nothing sent first. The outer state +// becomes Idle on the relay road, and the ladder and any attempt are cancelled. +func (l *Link) detachIdleDirectLocked(now time.Time) *directDetach { + d := &directDetach{relay: l.mux, nested: l.direct, onEnd: l.onChannelEnd} + l.mux = nil + l.carrying = RoadRelay + l.roadGen++ + l.direct = nil + l.directMux = nil + l.stopLivenessTimerLocked() + l.stopRedialTimerLocked() + l.stopProbeTimerLocked() + l.relayLostLocked() + l.dfails = 0 + + for _, tc := range l.channels { + tc.setLocalReason(ReasonIdle) + d.relayCh = append(d.relayCh, tc) + } + l.channels = make(map[uint32]*trackedChannel) + for dc := range l.dchannels { + dc.setLocalReason(ReasonIdle) + d.directC = append(d.directC, dc) + } + l.dchannels = make(map[*directChannel]struct{}) + + d.notify = l.setStateLocked(State{ + Kind: Idle, + Reason: ReasonIdle, + Since: now, + Permit: l.permit, + Road: l.road, + }) + return d +} + +func (l *Link) finishDirectDetach(d *directDetach) { + if d.relay != nil { + stampMuxChannels(d.relay, ReasonIdle) + _ = d.relay.Close() + } + if d.nested != nil { + d.nested.detachWithReason(ReasonIdle) + } + if d.onEnd != nil { + for _, tc := range d.relayCh { + tc := tc + tc.endOnce.Do(func() { + d.onEnd(tc.chat, ReasonIdle) + }) + } + for _, dc := range d.directC { + dc := dc + dc.endOnce.Do(func() { + d.onEnd(dc.chat, ReasonIdle) + }) + } + } + l.wake() + if d.notify != nil && l.cfg.OnState != nil { + l.cfg.OnState(*d.notify) + } +} diff --git a/internal/livedoor/link_direct_test.go b/internal/livedoor/link_direct_test.go new file mode 100644 index 0000000000..efecf43dd1 --- /dev/null +++ b/internal/livedoor/link_direct_test.go @@ -0,0 +1,1142 @@ +package livedoor + +import ( + "bytes" + "context" + "errors" + "io" + "sync" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" +) + +// The tests in this file are derived from the validation contract (SPEC-P2 V30 to +// V39 and section 3.2) and from the Link's specified behaviour (SPEC-LINK A, C to +// L), never from the Link's code. Time is the FakeClock and nothing else; every +// path is a net.Pipe with a real Serve on the far end. + +// V30: once the direct tunnel is up, the view's channels move onto it. Each relay +// channel ends with a planned redial that is never spoken, and the next open of +// the same chat is carried by the direct road, all inside the 3 s the contract +// allows (here, the settle delay and not one tick more). +func TestADirectLinkTakesTheChannelsOnceItsTunnelIsUp(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + chA := rig.openChat("chat-a") + chB := rig.openChat("chat-b") + if road := rig.speak(chA); road != RoadRelay { + t.Fatalf("the first paint was carried on %q, want the relay", road) + } + if road := rig.speak(chB); road != RoadRelay { + t.Fatalf("the second chat was carried on %q, want the relay", road) + } + if got := rig.link.State(); got.Kind != Live || got.Road != RoadRelay { + t.Fatalf("before the swap State() = %+v, want Live on the relay", got) + } + if n := rig.directDials.Load(); n != 0 { + t.Fatalf("a direct attempt began %d times before the settle delay", n) + } + + // The first attempt is due DirectSettle after the first channel opened, and + // not a millisecond before. + rig.waitAttemptArmed(DirectSettle) + rig.fc.Advance(DirectSettle - time.Millisecond) + quiesce() + if n := rig.directDials.Load(); n != 0 { + t.Fatalf("the attempt began %v early", time.Millisecond) + } + rig.fc.Advance(time.Millisecond) + rig.waitRoad(RoadDirect) + + if got := rig.link.State(); got.Kind != Live || got.Road != RoadDirect || got.Reason != "" { + t.Fatalf("after the swap State() = %+v, want Live on direct with no reason", got) + } + for name, ch := range map[string]io.ReadWriteCloser{"chat-a": chA, "chat-b": chB} { + err := rig.endOf(ch) + if !isPlanned(err) { + t.Fatalf("%s's relay channel ended with %v, want a planned redial", name, err) + } + if why, ok := ReasonOf(err); !ok || why != ReasonRoadChange { + t.Fatalf("%s ended for %q (%v), want %q", name, why, ok, ReasonRoadChange) + } + if _, werr := ch.Write([]byte("typed after the swap\n")); !isPlanned(werr) { + t.Fatalf("a write on %s's ended relay channel returned %v, want the same planned redial", name, werr) + } + } + // THE PLANNED END IS NEVER SPOKEN: OnChannelEnd is not told a road change. + if ended := rig.endedList(); len(ended) != 0 { + t.Fatalf("OnChannelEnd was told %v for a swap, want nothing", ended) + } + + // What a roaming client does next: open the same chats again. Both land on + // the direct road, and the holder says so. + if road := rig.speak(rig.openChat("chat-a")); road != RoadDirect { + t.Fatalf("chat-a reopened on %q, want direct", road) + } + if road := rig.speak(rig.openChat("chat-b")); road != RoadDirect { + t.Fatalf("chat-b reopened on %q, want direct", road) + } + if got := rig.opensOn(RoadRelay); len(got) != 2 { + t.Fatalf("the relay host resolved %v, want only the two first opens", got) + } + if got := rig.opensOn(RoadDirect); len(got) != 2 { + t.Fatalf("the direct host resolved %v, want the two reopens", got) + } + if n := rig.relayDials.Load(); n != 1 { + t.Fatalf("the relay was dialled %d times, want once", n) + } + if n := rig.directDials.Load(); n != 1 { + t.Fatalf("the direct road was dialled %d times, want once", n) + } +} + +// V30: the road word flips in the state with exactly ONE OnState call in each +// direction, with no intermediate Reconnecting or Idle, and no banner. +func TestTheRoadWordFlipsInTheStateAndNotifiesOnce(t *testing.T) { + t.Run("relay to direct", func(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + rig.speak(rig.openChat("chat-a")) + rig.waitState(Live, RoadRelay) + quiesce() + base := rig.link.State() + n := rig.stateCount() + + rig.swapToDirect() + within(t, "the flip to be notified", func() bool { return rig.stateCount() >= n+1 }) + quiesce() + got := rig.statesFrom(n) + if len(got) != 1 { + t.Fatalf("the flip notified %d times (%+v), want exactly once", len(got), got) + } + if got[0].Kind != Live || got[0].Road != RoadDirect || got[0].Reason != "" { + t.Fatalf("the notification was %+v, want Live on direct with no reason", got[0]) + } + if got[0].Permit.Watch != base.Permit.Watch || got[0].Permit.Drive != base.Permit.Drive { + t.Fatalf("the permit changed across the swap: %+v then %+v", base.Permit, got[0].Permit) + } + // Time on a healthy direct road raises nothing more. + rig.advanceHealthy(rig.latest(RoadDirect), 3*time.Second) + if more := rig.statesFrom(n); len(more) != 1 { + t.Fatalf("a quiet direct road notified again: %+v", more) + } + if st := rig.link.State(); st.Kind != Live || st.Road != RoadDirect { + t.Fatalf("State() = %+v, want Live on direct", st) + } + }) + + t.Run("direct back to relay", func(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + rig.speak(rig.openChat("chat-a")) + rig.swapToDirect() + rig.speak(rig.openChat("chat-a")) + quiesce() + n := rig.stateCount() + + rig.swapToRelay() + within(t, "the flip back to be notified", func() bool { return rig.stateCount() >= n+1 }) + quiesce() + got := rig.statesFrom(n) + if len(got) != 1 { + t.Fatalf("the fallback notified %d times (%+v), want exactly once with no Reconnecting or WentOffline between", len(got), got) + } + if got[0].Kind != Live || got[0].Road != RoadRelay { + t.Fatalf("the notification was %+v, want Live on the relay", got[0]) + } + }) +} + +// V30: the first paint never waits on the direct attempt. The first relay channel +// opens and reads before any attempt exists, and while an attempt's dial is stuck +// the relay still opens channels, reads them and answers every call the Link has. +func TestTheFirstPaintNeverWaitsOnTheDirectAttempt(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + release := make(chan struct{}) + var once sync.Once + t.Cleanup(func() { once.Do(func() { close(release) }) }) + rig.setDirect(func(ctx context.Context, _ int, _ Signaller) (io.ReadWriteCloser, error) { + select { + case <-release: + return nil, errors.New("released") + case <-ctx.Done(): + return nil, ctx.Err() + } + }) + + // The first paint: opened and read with the clock never moved and no + // attempt begun. + if road := rig.speak(rig.openChat("chat-a")); road != RoadRelay { + t.Fatalf("the first paint was carried on %q, want the relay", road) + } + if n := rig.directDials.Load(); n != 0 { + t.Fatalf("a direct dial began (%d) before the first paint was done", n) + } + + // The attempt begins and its dial is stuck. + rig.waitAttemptArmed(DirectSettle) + rig.fc.Advance(DirectSettle) + within(t, "the attempt's dial to begin", func() bool { return rig.directDials.Load() == 1 }) + nStates := rig.stateCount() + + // With the dial stuck, a second chat opens and paints on the relay, and the + // Link answers its own calls. + if road := rig.speak(rig.openChat("chat-b")); road != RoadRelay { + t.Fatalf("a chat opened during the attempt was carried on %q, want the relay", road) + } + bounded(t, "State, Road and Touch during an attempt", func() { + _ = rig.link.State() + _ = rig.link.Road() + rig.link.Touch() + }) + if rig.link.Road() != RoadRelay { + t.Fatalf("the road read %q while the attempt was stuck, want the relay", rig.link.Road()) + } + if n := rig.directDials.Load(); n != 1 { + t.Fatalf("the stuck attempt was dialled %d times, want once", n) + } + if got := rig.statesFrom(nStates); len(got) != 0 { + t.Fatalf("a stuck attempt raised %+v, want nothing", got) + } + + once.Do(func() { close(release) }) + within(t, "the released dial to return", func() bool { return rig.directDone.Load() == 1 }) + quiesce() + if got := rig.statesFrom(nStates); len(got) != 0 { + t.Fatalf("a failed attempt raised %+v, want nothing", got) + } +} + +// V32: an attempt that never connects is abandoned after DirectConnectWithin on +// the fake clock and leaves the view exactly as it was: the same State, no +// OnState, no channel ended, no relay redial, and the retries are as silent. +func TestADirectAttemptThatNeverConnectsLeavesTheViewOnTheRelayWithNoStateChange(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + rig.setDirect(func(ctx context.Context, _ int, _ Signaller) (io.ReadWriteCloser, error) { + <-ctx.Done() + return nil, ctx.Err() + }) + ch := rig.openChat("chat-a") + if road := rig.speak(ch); road != RoadRelay { + t.Fatalf("the first paint was carried on %q, want the relay", road) + } + quiesce() + before := rig.link.State() + nStates := rig.stateCount() + + assertUntouched := func(when string) { + t.Helper() + got := rig.link.State() + if got.Kind != before.Kind || got.Reason != before.Reason || got.Road != before.Road || !got.Since.Equal(before.Since) || got.Permit.Watch != before.Permit.Watch || got.Permit.Drive != before.Permit.Drive { + t.Fatalf("%s: State() = %+v, was %+v", when, got, before) + } + if more := rig.statesFrom(nStates); len(more) != 0 { + t.Fatalf("%s: OnState was called with %+v", when, more) + } + if ended := rig.endedList(); len(ended) != 0 { + t.Fatalf("%s: channels ended: %v", when, ended) + } + if _, err := ch.Write([]byte("the view is still here\n")); err != nil { + t.Fatalf("%s: the view's channel no longer takes writes: %v", when, err) + } + if n := rig.relayDials.Load(); n != 1 { + t.Fatalf("%s: the relay was dialled %d times, want once", when, n) + } + } + + rig.waitAttemptArmed(DirectSettle) + rig.fc.Advance(DirectSettle) + within(t, "the first attempt to begin", func() bool { return rig.directDials.Load() == 1 }) + + // It is abandoned after DirectConnectWithin of the fake clock, not before. + rig.waitAttemptArmed(DirectConnectWithin) + rig.fc.Advance(DirectConnectWithin - time.Millisecond) + quiesce() + if n := rig.directDone.Load(); n != 0 { + t.Fatalf("the attempt was abandoned %v early", time.Millisecond) + } + assertUntouched("while the attempt is still within its time") + rig.fc.Advance(time.Millisecond) + within(t, "the attempt to be abandoned", func() bool { return rig.directDone.Load() == 1 }) + quiesce() + assertUntouched("after the first attempt was abandoned") + + // The retry comes after the first rung and is as silent. + rig.ladderStep(DirectBackoff[0]) + rig.waitAttemptArmed(DirectConnectWithin) + rig.fc.Advance(DirectConnectWithin) + within(t, "the second attempt to be abandoned", func() bool { return rig.directDone.Load() == 2 }) + quiesce() + assertUntouched("after the second attempt was abandoned") +} + +// V32: the attempt times on the fake clock climb DirectSettle, then +// DirectBackoff (5 s, 15 s, 60 s, 5 min, 10 min, 10 min again); the ladder starts +// over after a direct link stayed up DirectStableAfter and on every new relay +// tunnel, and a direct link that dies young does not start it over. +func TestDirectRetriesBackOffFiveFifteenSixtyThreeHundredSixHundredAndResetAfterAMinuteUp(t *testing.T) { + t.Run("the climb", func(t *testing.T) { + rig := newDirectRig(t, rigOpts{idleDetach: 24 * time.Hour}) + rig.failDirect() + rig.speak(rig.openChat("chat-a")) + for _, want := range []time.Duration{ + DirectSettle, + DirectBackoff[0], DirectBackoff[1], DirectBackoff[2], DirectBackoff[3], DirectBackoff[4], DirectBackoff[4], + } { + rig.ladderStep(want) + } + quiesce() + if got := rig.link.State(); got.Kind != Live || got.Road != RoadRelay { + t.Fatalf("after seven failed attempts State() = %+v, want Live on the relay", got) + } + if n := rig.stateCount(); n > 2 { + t.Fatalf("failed attempts raised OnState: %+v", rig.statesFrom(0)) + } + }) + + // connectOnFourth makes the first three attempts fail and the fourth succeed, + // so the ladder has climbed to its 60 s rung when the road comes up. + connectOnFourth := func(t *testing.T) *directRig { + rig := newDirectRig(t, rigOpts{idleDetach: 24 * time.Hour}) + rig.setDirect(func(_ context.Context, n int, _ Signaller) (io.ReadWriteCloser, error) { + if n <= 3 { + return nil, errors.New("no direct path") + } + return rig.newTunnel(RoadDirect), nil + }) + rig.speak(rig.openChat("chat-a")) + rig.ladderStep(DirectSettle) + rig.ladderStep(DirectBackoff[0]) + rig.ladderStep(DirectBackoff[1]) + rig.ladderStep(DirectBackoff[2]) + rig.waitRoad(RoadDirect) + return rig + } + + t.Run("a direct link that stayed up a minute starts the ladder over", func(t *testing.T) { + rig := connectOnFourth(t) + direct := rig.latest(RoadDirect) + rig.advanceHealthy(direct, DirectStableAfter+time.Second) + before := rig.directDials.Load() + rig.swapToRelay() + // An attempt needs a channel to move, so the roaming client's redial is + // played here: the chat is opened again, and now on the relay. + if road := rig.speak(rig.openChat("chat-b")); road != RoadRelay { + t.Fatalf("the reopened chat was carried on %q, want the relay", road) + } + // A reset ladder tries again within the first rung; one that kept + // climbing would wait minutes. + for i := 0; i < int(DirectBackoff[0]/(100*time.Millisecond))+10 && rig.directDials.Load() == before; i++ { + rig.advanceFine(100 * time.Millisecond) + } + within(t, "a new attempt within the first rung after a stable link", func() bool { return rig.directDials.Load() > before }) + }) + + t.Run("a direct link that died young keeps the ladder climbing", func(t *testing.T) { + rig := connectOnFourth(t) + direct := rig.latest(RoadDirect) + rig.advanceHealthy(direct, 10*time.Second) + rig.swapToRelay() + // An attempt needs a channel to move, so the roaming client's redial is + // played here: the chat is opened again, and now on the relay. + if road := rig.speak(rig.openChat("chat-b")); road != RoadRelay { + t.Fatalf("the reopened chat was carried on %q, want the relay", road) + } + // It was a failure like the three before it: the next wait is the + // fourth rung, five minutes, not the first. + rig.ladderStep(DirectBackoff[3]) + }) + + t.Run("a new relay tunnel starts the ladder over", func(t *testing.T) { + rig := newDirectRig(t, rigOpts{idleDetach: 24 * time.Hour}) + rig.failDirect() + rig.speak(rig.openChat("chat-a")) + rig.ladderStep(DirectSettle) + rig.ladderStep(DirectBackoff[0]) + rig.ladderStep(DirectBackoff[1]) + rig.waitAttemptArmed(DirectBackoff[2]) + + rig.tunnel(RoadRelay, 1).kill() + within(t, "the Link to notice its relay tunnel is gone", func() bool { return rig.link.State().Kind != Live }) + if road := rig.speak(rig.askAgainAfterDrop("chat-b")); road != RoadRelay { + t.Fatalf("the reopened chat was carried on %q, want the relay", road) + } + // How many dials it takes to get a new tunnel (the Link's own redial and a + // roaming client's open may both dial) is phase 1's business; that there is + // a new one is the premise of this case. + if n := rig.relayDials.Load(); n < 2 { + t.Fatalf("the relay was dialled %d times, want a second tunnel", n) + } + // The first attempt of the new tunnel is the settle delay again, and + // not the 60 s the old one had climbed to. + rig.ladderStep(DirectSettle) + }) +} + +// V33: a direct path that dies without a close is noticed at lastHeard+3 s, the +// channels end with the planned redial, and the view is back on the relay by 3.1 s +// from the stall when the relay standby is alive, with the standby probed once at +// the first missed pong and no relay dial, no state but the one road flip. An +// abrupt close of the direct stream falls back at once. +func TestADeadDirectLinkEndsItsChannelsPlannedAndTheRelayTakesThemWithinFiveSeconds(t *testing.T) { + t.Run("a stalled path with a live standby", func(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + rig.speak(rig.openChat("chat-a")) + rig.swapToDirect() + ch := rig.openChat("chat-a") + if road := rig.speak(ch); road != RoadDirect { + t.Fatalf("chat-a was carried on %q after the swap, want direct", road) + } + direct := rig.latest(RoadDirect) + relay := rig.tunnel(RoadRelay, 1) + rig.advanceHealthy(direct, 3*time.Second) + quiesce() + nStates := rig.stateCount() + relayMark := relay.viewer.sent.mark() + + rig.alignOnPong(direct) + direct.stall() + stalledAt := rig.fc.Now() + + // Nothing is probed before a pong has been missed. + rig.advanceFine(900 * time.Millisecond) + if n := relay.viewer.sent.opsSince(relayMark, OpPing); n != 0 { + t.Fatalf("the standby was probed %d times before any pong was missed", n) + } + // The probe goes out once, at the first missed pong, well before the + // road is declared dead. + rig.advanceFine(1600 * time.Millisecond) + within(t, "the standby probe", func() bool { return relay.viewer.sent.opsSince(relayMark, OpPing) >= 1 }) + if rig.link.Road() != RoadDirect { + t.Fatalf("the road was declared dead %v into the silence, want after three seconds", rig.fc.Now().Sub(stalledAt)) + } + rig.advanceFine(600 * time.Millisecond) + rig.waitRoad(RoadRelay) + if elapsed := rig.fc.Now().Sub(stalledAt); elapsed > 3100*time.Millisecond { + t.Fatalf("the view was back on the relay %v after the stall, want within 3.1 s with a live standby", elapsed) + } + if n := relay.viewer.sent.opsSince(relayMark, OpPing); n != 1 { + t.Fatalf("the standby was probed %d times in one outage, want exactly once", n) + } + + err := rig.endOf(ch) + if !isPlanned(err) { + t.Fatalf("the direct channel ended with %v, want a planned redial", err) + } + within(t, "the fallback to be notified", func() bool { return rig.stateCount() > nStates }) + quiesce() + got := rig.statesFrom(nStates) + if len(got) != 1 || got[0].Kind != Live || got[0].Road != RoadRelay { + t.Fatalf("the fallback raised %+v, want exactly one Live on the relay (no Reconnecting, no WentOffline)", got) + } + if n := rig.relayDials.Load(); n != 1 { + t.Fatalf("the relay was dialled %d times, want the standby reused", n) + } + // The roaming client's redial lands on the standby, with no dial. + if road := rig.speak(rig.openChat("chat-a")); road != RoadRelay { + t.Fatalf("chat-a reopened on %q, want the relay", road) + } + if rec := rig.lastOpen(); rec.road != RoadRelay || rec.tunnel != 1 { + t.Fatalf("the reopen reached the host as %+v, want the first relay tunnel", rec) + } + if n := rig.relayDials.Load(); n != 1 { + t.Fatalf("reopening on the standby dialled the relay %d times", n) + } + if ended := rig.endedList(); len(ended) != 0 { + t.Fatalf("OnChannelEnd was told %v, want nothing for a planned redial", ended) + } + }) + + t.Run("an abrupt close of the direct stream", func(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + rig.speak(rig.openChat("chat-a")) + rig.swapToDirect() + ch := rig.openChat("chat-a") + rig.speak(ch) + relay := rig.tunnel(RoadRelay, 1) + quiesce() + nStates := rig.stateCount() + relayMark := relay.viewer.sent.mark() + + rig.swapToRelay() + if !isPlanned(rig.endOf(ch)) { + t.Fatal("an abruptly closed direct stream did not end its channel with the planned redial") + } + quiesce() + if got := rig.statesFrom(nStates); len(got) != 1 || got[0].Kind != Live || got[0].Road != RoadRelay { + t.Fatalf("the fallback raised %+v, want exactly one Live on the relay", got) + } + if n := relay.viewer.sent.opsSince(relayMark, OpPing); n > 1 { + t.Fatalf("the standby was probed %d times, want at most once", n) + } + if n := rig.relayDials.Load(); n != 1 { + t.Fatalf("the relay was dialled %d times, want the standby reused", n) + } + if road := rig.speak(rig.openChat("chat-a")); road != RoadRelay { + t.Fatalf("chat-a reopened on %q, want the relay", road) + } + }) +} + +// V33: when the relay standby is gone while direct carries, nothing is done about +// it quietly; at the FIRST missed pong the relay is dialled in parallel, so it is +// already up when the direct road is declared dead at lastHeard+3 s, and the +// view is on the relay by 3.1 s with no further dial. +func TestADeadStandbyIsRedialledInParallelAtTheFirstMissedPong(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + rig.speak(rig.openChat("chat-a")) + rig.swapToDirect() + ch := rig.openChat("chat-a") + if road := rig.speak(ch); road != RoadDirect { + t.Fatalf("chat-a was carried on %q after the swap, want direct", road) + } + direct := rig.latest(RoadDirect) + relay := rig.tunnel(RoadRelay, 1) + rig.advanceHealthy(direct, time.Second) + quiesce() + nStates := rig.stateCount() + + // The standby relay tunnel dies while direct carries. The viewer drops it + // silently: no dial, no state, no notification. + relay.kill() + rig.advanceHealthy(direct, 5*time.Second) + if n := rig.relayDials.Load(); n != 1 { + t.Fatalf("the relay was redialled (%d dials) while direct carried and was healthy", n) + } + if st := rig.link.State(); st.Kind != Live || st.Road != RoadDirect { + t.Fatalf("State() = %+v after the standby died, want Live on direct", st) + } + if got := rig.statesFrom(nStates); len(got) != 0 { + t.Fatalf("the standby's death raised %+v, want nothing", got) + } + + // Now the direct path goes silent. + rig.alignOnPong(direct) + direct.stall() + stalledAt := rig.fc.Now() + rig.advanceFine(900 * time.Millisecond) + if n := rig.relayDials.Load(); n != 1 { + t.Fatalf("the relay was dialled (%d) before any pong was missed", n) + } + // At the first missed pong the relay is dialled, in parallel, while direct + // is still the road. + rig.advanceFine(1600 * time.Millisecond) + within(t, "the parallel relay dial", func() bool { return rig.relayDials.Load() == 2 }) + if rig.link.Road() != RoadDirect { + t.Fatalf("the road was declared dead %v into the silence, want after three seconds", rig.fc.Now().Sub(stalledAt)) + } + rig.advanceFine(600 * time.Millisecond) + rig.waitRoad(RoadRelay) + if elapsed := rig.fc.Now().Sub(stalledAt); elapsed > 3100*time.Millisecond { + t.Fatalf("the view was back on the relay %v after the stall, want about 3.1 s", elapsed) + } + if n := rig.relayDials.Load(); n != 2 { + t.Fatalf("the relay was dialled %d times, want the one parallel dial", n) + } + if !isPlanned(rig.endOf(ch)) { + t.Fatal("the dead direct channel did not end with the planned redial") + } + within(t, "the fallback to be notified", func() bool { return rig.stateCount() > nStates }) + quiesce() + got := rig.statesFrom(nStates) + if len(got) != 1 || got[0].Kind != Live || got[0].Road != RoadRelay { + t.Fatalf("the fallback raised %+v, want exactly one Live on the relay (no WentOffline)", got) + } + // The roaming client's redial opens on the relay that was dialled in + // parallel and dials nothing more. + if road := rig.speak(rig.openChat("chat-a")); road != RoadRelay { + t.Fatalf("chat-a reopened on %q, want the relay", road) + } + if rec := rig.lastOpen(); rec.road != RoadRelay || rec.tunnel != 2 { + t.Fatalf("the reopen reached the host as %+v, want the second relay tunnel", rec) + } + if n := rig.relayDials.Load(); n != 2 { + t.Fatalf("the relay was dialled %d times in all, want 2", n) + } +} + +// V33 and D7: while the direct link carries and is healthy the relay standby is +// left alone. It is never redialled, never pinged and never sent any frame, even +// across a span longer than every keepalive the relay has had, and even while the +// view is active (a running turn), which on the relay alone pings every 3 s. +func TestTheRelayLinkIsNotRedialledWhileTheDirectLinkCarries(t *testing.T) { + rig := newDirectRig(t, rigOpts{active: true}) + rig.speak(rig.openChat("chat-a")) + rig.swapToDirect() + if road := rig.speak(rig.openChat("chat-a")); road != RoadDirect { + t.Fatalf("chat-a was carried on %q after the swap, want direct", road) + } + direct := rig.latest(RoadDirect) + relay := rig.tunnel(RoadRelay, 1) + rig.advanceHealthy(direct, time.Second) + quiesce() + relayMark := relay.viewer.sent.mark() + hostMark := relay.hostTap.mark() + nStates := rig.stateCount() + + rig.advanceHealthy(direct, 6*time.Minute) + + if n := rig.relayDials.Load(); n != 1 { + t.Fatalf("the relay was dialled %d times while direct carried, want once in all", n) + } + if frames := relay.viewer.sent.since(relayMark); len(frames) != 0 { + t.Fatalf("the standby sent %v in six minutes on direct, want nothing", frames) + } + if frames := relay.hostTap.since(hostMark); len(frames) != 0 { + t.Fatalf("the host sent %v on the standby in six minutes, want nothing", frames) + } + if n := relay.viewer.sent.count(OpPing); n != 0 { + t.Fatalf("the standby was pinged %d times while direct was healthy", n) + } + if relay.viewer.closed.Load() { + t.Fatal("the standby relay tunnel was closed while direct carried") + } + if st := rig.link.State(); st.Kind != Live || st.Road != RoadDirect { + t.Fatalf("State() = %+v, want Live on direct", st) + } + if got := rig.statesFrom(nStates); len(got) != 0 { + t.Fatalf("six quiet minutes raised %+v", got) + } +} + +// V39: a direct view with no key, scroll or send for IdleDetach closes both roads, +// one close each and nothing sent first, tells OnChannelEnd `idle` once for the +// one channel, sends nothing on the relay while it is idle, cancels the ladder, +// and a key afterwards reattaches on the relay and upgrades again. +func TestAnIdleDirectViewDetachesBothRoadsWithOneCloseAndNothingSentOnTheRelay(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + rig.speak(rig.openChat("chat-a")) + t0 := rig.fc.Now() + rig.swapToDirect() + ch := rig.openChat("chat-a") + if road := rig.speak(ch); road != RoadDirect { + t.Fatalf("chat-a was carried on %q after the swap, want direct", road) + } + direct := rig.latest(RoadDirect) + relay := rig.tunnel(RoadRelay, 1) + rig.advanceHealthy(direct, time.Second) + quiesce() + relayMark := relay.viewer.sent.mark() + + // Ten minutes less a second of nothing: still live, still direct, nothing on + // the relay. + rig.advanceHealthy(direct, t0.Add(IdleDetach-time.Second).Sub(rig.fc.Now())) + if st := rig.link.State(); st.Kind != Live || st.Road != RoadDirect { + t.Fatalf("at 9m59s State() = %+v, want Live on direct", st) + } + if ended := rig.endedList(); len(ended) != 0 { + t.Fatalf("a channel ended before the idle time: %v", ended) + } + if frames := relay.viewer.sent.since(relayMark); len(frames) != 0 { + t.Fatalf("the relay carried %v during the idle spell, want nothing", frames) + } + + // Past ten minutes both roads detach. + directMark := direct.viewer.sent.mark() + rig.advanceFine(3 * time.Second) + within(t, "the view to go idle", func() bool { return rig.link.State().Kind == Idle }) + if st := rig.link.State(); st.Reason != ReasonIdle || st.Road != RoadRelay { + t.Fatalf("State() = %+v after the detach, want Idle for %q with the road back to relay", st, ReasonIdle) + } + within(t, "the relay tunnel to be closed", relay.viewer.closed.Load) + within(t, "the direct tunnel to be closed", direct.viewer.closed.Load) + if frames := relay.viewer.sent.since(relayMark); len(frames) != 0 { + t.Fatalf("the detach put %v on the relay, want one close and nothing sent first", frames) + } + for _, op := range []uint8{OpClose, OpReset, OpData, OpOpen, OpSignal} { + if n := direct.viewer.sent.opsSince(directMark, op); n != 0 { + t.Fatalf("the detach put %d frames of op %d on the direct tunnel, want one close and nothing sent first", n, op) + } + } + within(t, "OnChannelEnd to be told the idle end", func() bool { return len(rig.endedList()) >= 1 }) + quiesce() + if ended := rig.endedList(); len(ended) != 1 || ended[0] != "chat-a:"+ReasonIdle { + t.Fatalf("OnChannelEnd was told %v, want exactly [chat-a:%s]", ended, ReasonIdle) + } + err := rig.endOf(ch) + if why, ok := ReasonOf(err); !ok || why != ReasonIdle || isPlanned(err) { + t.Fatalf("the direct channel ended with %v, want the spoken reason %q", err, ReasonIdle) + } + within(t, "every timer to be gone once idle", func() bool { return rig.fc.BlockedTimers() == 0 }) + + // A key reattaches on the relay and the first channel after it upgrades again. + rig.link.Touch() + within(t, "the relay to be dialled again", func() bool { return rig.relayDials.Load() == 2 }) + rig.waitState(Live, RoadRelay) + if road := rig.speak(rig.openChat("chat-a")); road != RoadRelay { + t.Fatalf("the first channel after the key was carried on %q, want the relay", road) + } + if moved := rig.runToNextAttempt(); moved != DirectSettle { + t.Fatalf("the first attempt after the key came after %v, want the settle delay %v", moved, DirectSettle) + } + rig.waitRoad(RoadDirect) + if n := rig.directDials.Load(); n != 2 { + t.Fatalf("the direct road was dialled %d times, want a second attempt after the key", n) + } +} + +// K1 (road generation): a channel whose relay open completes AFTER the swap +// committed never stays on the relay. The open is retried on the direct road, the +// channel it hands back is a direct one, and the relay channel it abandoned is +// closed without ever being reported as ended. +func TestAChannelOpenedAsTheSwapCommitsNeverStaysOnTheRelay(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + rig.speak(rig.openChat("chat-a")) + + // The host holds the relay's resolution of chat-x, so the viewer's open is in + // flight on the relay while the swap commits. + gate := rig.holdNextOpen(RoadRelay, "chat-x") + type result struct { + ch io.ReadWriteCloser + err error + } + done := make(chan result, 1) + guard.Go("livedoor.test.direct.k1.open", func() { + ch, err := rig.openChatErr("chat-x") + done <- result{ch: ch, err: err} + }) + select { + case <-gate.entered: + case <-time.After(10 * time.Second): + t.Fatal("the relay open never reached the host") + } + rig.swapToDirect() + + // The open completes on the relay now. + close(gate.release) + var res result + select { + case res = <-done: + case <-time.After(10 * time.Second): + t.Fatal("the open that straddled the swap never returned") + } + if res.err != nil { + t.Fatalf("the open that straddled the swap failed: %v", res.err) + } + if road := rig.speak(res.ch); road != RoadDirect { + t.Fatalf("the channel that was opening on the relay as the swap committed is carried on %q, want direct", road) + } + if got := rig.opensOn(RoadDirect); len(got) == 0 || got[len(got)-1] != "chat-x" { + t.Fatalf("the direct host resolved %v, want chat-x retried there", got) + } + // The abandoned relay channel was closed: one CLOSE for chat-a at the swap, and + // one for the channel that must not stay. + relay := rig.tunnel(RoadRelay, 1) + within(t, "the abandoned relay channel to be closed", func() bool { + return relay.viewer.sent.count(OpClose)+relay.viewer.sent.count(OpReset) >= 2 + }) + if ended := rig.endedList(); len(ended) != 0 { + t.Fatalf("OnChannelEnd was told %v, want nothing for a channel that was never published", ended) + } + if st := rig.link.State(); st.Kind != Live || st.Road != RoadDirect { + t.Fatalf("State() = %+v, want Live on direct", st) + } +} + +// K2 (attempt token): a candidate direct tunnel that finishes dialling after the +// view went idle, after its relay tunnel was replaced, after the link was +// revoked or after Close never commits a swap: the road does not change, nothing +// is notified, and the stale candidate's tunnel is closed. +func TestAStaleAttemptCannotCommitAfterIdleOrANewRelayTunnel(t *testing.T) { + // staleRig is a rig whose first direct dial ignores its context and returns a + // ready tunnel only when released: a candidate that finishes late. Later + // dials fail at once, so only that one candidate is ever in play. + staleRig := func(t *testing.T) (*directRig, func()) { + rig := newDirectRig(t, rigOpts{}) + release := make(chan struct{}) + var once sync.Once + releaseFn := func() { once.Do(func() { close(release) }) } + t.Cleanup(releaseFn) + rig.setDirect(func(_ context.Context, n int, _ Signaller) (io.ReadWriteCloser, error) { + if n > 1 { + return nil, errors.New("no direct path") + } + <-release + return rig.newTunnel(RoadDirect), nil + }) + rig.speak(rig.openChat("chat-a")) + rig.runToNextAttempt() + return rig, releaseFn + } + // settled is what must hold once the late candidate has been dealt with. + settled := func(t *testing.T, rig *directRig) { + t.Helper() + within(t, "the late candidate's tunnel to exist", func() bool { return len(rig.tunnelsOn(RoadDirect)) == 1 }) + candidate := rig.tunnelsOn(RoadDirect)[0] + within(t, "the stale candidate to be closed", candidate.viewer.closed.Load) + quiesce() + if rig.link.Road() == RoadDirect { + t.Fatal("a stale candidate committed the swap") + } + for _, st := range rig.statesFrom(0) { + if st.Road == RoadDirect { + t.Fatalf("a stale candidate was notified as the road: %+v", rig.statesFrom(0)) + } + } + for _, ended := range rig.endedList() { + if bytes.Contains([]byte(ended), []byte(ReasonRoadChange)) { + t.Fatalf("a stale candidate swapped a channel: %v", rig.endedList()) + } + } + } + + t.Run("after the view went idle", func(t *testing.T) { + rig, release := staleRig(t) + rig.fc.Advance(IdleDetach + time.Second) + within(t, "the view to go idle", func() bool { return rig.link.State().Kind == Idle }) + release() + settled(t, rig) + if st := rig.link.State(); st.Kind != Idle { + t.Fatalf("State() = %+v after a stale candidate, want it still Idle", st) + } + }) + + t.Run("after a new relay tunnel replaced the old one", func(t *testing.T) { + rig, release := staleRig(t) + rig.tunnel(RoadRelay, 1).kill() + within(t, "the Link to notice its relay tunnel is gone", func() bool { return rig.link.State().Kind != Live }) + ch := rig.askAgainAfterDrop("chat-b") + if road := rig.speak(ch); road != RoadRelay { + t.Fatalf("the reopened chat was carried on %q, want the relay", road) + } + // How many dials it takes to get a new tunnel (the Link's own redial and a + // roaming client's open may both dial) is phase 1's business; that there is + // a new one is the premise of this case. + if n := rig.relayDials.Load(); n < 2 { + t.Fatalf("the relay was dialled %d times, want a second tunnel", n) + } + release() + settled(t, rig) + if st := rig.link.State(); st.Kind != Live || st.Road != RoadRelay { + t.Fatalf("State() = %+v after a stale candidate, want Live on the relay", st) + } + if _, err := ch.Write([]byte("still on the relay\n")); err != nil { + t.Fatalf("the new tunnel's channel was swapped away by a stale candidate: %v", err) + } + }) + + t.Run("after Close", func(t *testing.T) { + rig, release := staleRig(t) + rig.link.Close() + release() + settled(t, rig) + }) + + t.Run("after a revocation", func(t *testing.T) { + rig, release := staleRig(t) + rig.relayReg.Revoke(rig.peer.Device) + within(t, "the view to be revoked", func() bool { return rig.link.State().Kind == Revoked }) + release() + settled(t, rig) + if st := rig.link.State(); st.Kind != Revoked { + t.Fatalf("State() = %+v after a stale candidate, want it still Revoked", st) + } + }) +} + +// K3 (standby probe has a deadline): when the direct road dies together with the +// relay standby (a whole network gone), the standby cannot answer its probe, so at +// the fallback it is retired, ONE relay dial is started and no more, and the +// channels the roaming client redials open on the new tunnel, never on the +// standby that is known unanswered. +func TestAnUnansweredStandbyIsRetiredAtTheFallbackAndOneRelayDialIsStarted(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + rig.speak(rig.openChat("chat-a")) + rig.swapToDirect() + ch := rig.openChat("chat-a") + if road := rig.speak(ch); road != RoadDirect { + t.Fatalf("chat-a was carried on %q after the swap, want direct", road) + } + direct := rig.latest(RoadDirect) + relay1 := rig.tunnel(RoadRelay, 1) + rig.advanceHealthy(direct, 3*time.Second) + quiesce() + nStates := rig.stateCount() + relayMark := relay1.viewer.sent.mark() + + // Everything goes dark at once. + rig.alignOnPong(direct) + direct.stall() + relay1.stall() + stalledAt := rig.fc.Now() + + rig.advanceFine(2500 * time.Millisecond) + within(t, "the standby to be probed", func() bool { return relay1.viewer.sent.opsSince(relayMark, OpPing) >= 1 }) + if n := relay1.viewer.sent.opsSince(relayMark, OpPing); n != 1 { + t.Fatalf("the standby was probed %d times in one outage, want exactly once", n) + } + if rig.link.Road() != RoadDirect { + t.Fatalf("the road was declared dead %v into the silence, want after three seconds", rig.fc.Now().Sub(stalledAt)) + } + + // The direct road is declared dead; the standby that never answered is + // retired and exactly one relay dial replaces it. + rig.advanceFine(600 * time.Millisecond) + rig.waitRoad(RoadRelay) + within(t, "the unanswered standby to be retired", relay1.viewer.closed.Load) + within(t, "the relay to be dialled once", func() bool { return rig.relayDials.Load() == 2 }) + rig.advanceFine(10 * time.Second) + if n := rig.relayDials.Load(); n != 2 { + t.Fatalf("the relay was dialled %d times, want the one dial and no second", n) + } + if !isPlanned(rig.endOf(ch)) { + t.Fatal("the dead direct channel did not end with the planned redial") + } + rig.waitState(Live, RoadRelay) + for _, st := range rig.statesFrom(nStates) { + if st.Kind == WentOffline { + t.Fatalf("a network that came back raised a went-offline banner: %+v", rig.statesFrom(nStates)) + } + } + + // The opener never uses the standby that did not answer. + if road := rig.speak(rig.openChat("chat-a")); road != RoadRelay { + t.Fatalf("chat-a reopened on %q, want the relay", road) + } + if rec := rig.lastOpen(); rec.road != RoadRelay || rec.tunnel != 2 { + t.Fatalf("the reopen reached the host as %+v, want the NEW relay tunnel, never the retired standby", rec) + } + if elapsed := rig.fc.Now().Sub(stalledAt); elapsed < 3*time.Second { + t.Fatalf("the test measured %v, want a span past the three-second bound", elapsed) + } +} + +// spokenOutcome is everything a person or a caller can see of a channel that the +// host ended with a reason. +type spokenOutcome struct { + readReason string + planned bool + ended []string + kind StateKind + reason string + watch, drive bool + reopenOK bool + reopenReason string +} + +// settledStates waits until the Link has stopped changing state, which is the +// moment a comparison between two Links is fair. +func settledStates(rig *directRig) { + for stable := 0; stable < 4; { + n := rig.stateCount() + quiesce() + if rig.stateCount() == n { + stable++ + } else { + stable = 0 + } + } +} + +// spokenEnd runs one scenario: a chat is open on the carrying road (the relay for +// a link with no direct config, direct once swapped otherwise), the host speaks +// reason on that road's channels and leaves the tunnel up, and the result is what +// was seen. +func spokenEnd(t *testing.T, onDirect bool, reason string) (*directRig, spokenOutcome) { + t.Helper() + rig := newDirectRig(t, rigOpts{noDirect: !onDirect}) + ch := rig.openChat("chat-a") + rig.speak(ch) + reg := rig.relayReg + if onDirect { + rig.swapToDirect() + ch = rig.openChat("chat-a") + if road := rig.speak(ch); road != RoadDirect { + t.Fatalf("the chat was carried on %q, want direct", road) + } + reg = rig.directReg + } + hostSays(t, reg, rig.peer.Device, reason) + err := rig.endOf(ch) + var out spokenOutcome + out.readReason, _ = ReasonOf(err) + out.planned = isPlanned(err) + within(t, "OnChannelEnd to be told", func() bool { return len(rig.endedList()) >= 1 }) + settledStates(rig) + out.ended = rig.endedList() + st := rig.link.State() + out.kind, out.reason, out.watch, out.drive = st.Kind, st.Reason, st.Permit.Watch, st.Permit.Drive + reopened, rerr := rig.askAgainAfterDropErr("chat-a") + out.reopenOK = rerr == nil + out.reopenReason, _ = ReasonOf(rerr) + if reopened != nil { + _ = reopened.Close() + } + return rig, out +} + +// E: a reason the HOST speaks on a direct channel takes the same handling as on a +// relay channel. Each reason is run on a link with no direct config (the phase 1 +// behaviour, the oracle) and on a link carried by the direct road, and what the +// person or caller can see must agree. A spoken removal also revokes the whole +// link, closes the nested one and never schedules another attempt. +func TestAHostSpokenReasonOnADirectChannelTakesTheSameHandlingAsOnARelayChannel(t *testing.T) { + for _, reason := range []string{ReasonRemoved, ReasonPermitChanged, ReasonBudget, ReasonLagging} { + reason := reason + t.Run(reason, func(t *testing.T) { + _, want := spokenEnd(t, false, reason) + rig, got := spokenEnd(t, true, reason) + if want.readReason != reason { + t.Fatalf("the oracle's channel ended for %q, want %q: the scenario is wrong", want.readReason, reason) + } + if got.readReason != reason || got.planned { + t.Fatalf("the direct channel ended for %q (planned %v), want the spoken %q", got.readReason, got.planned, reason) + } + if len(got.ended) != 1 || got.ended[0] != "chat-a:"+reason { + t.Fatalf("OnChannelEnd was told %v, want exactly [chat-a:%s]", got.ended, reason) + } + if got.kind != want.kind || got.reason != want.reason || got.watch != want.watch || got.drive != want.drive { + t.Fatalf("the direct link settled as kind=%v reason=%q watch=%v drive=%v; the relay link, given the same words, as kind=%v reason=%q watch=%v drive=%v", + got.kind, got.reason, got.watch, got.drive, want.kind, want.reason, want.watch, want.drive) + } + if got.reopenOK != want.reopenOK || got.reopenReason != want.reopenReason { + t.Fatalf("reopening after %q: direct link ok=%v reason=%q; relay link ok=%v reason=%q", reason, got.reopenOK, got.reopenReason, want.reopenOK, want.reopenReason) + } + if reason == ReasonLagging && rig.link.Road() != RoadDirect { + t.Fatalf("a lagging channel moved the road to %q; the tunnel stays and so does the road", rig.link.Road()) + } + if reason != ReasonRemoved { + return + } + // A removal ends it all: the link is revoked for good, nothing is + // scheduled and no road is ever dialled again. + if got.kind != Revoked || got.reason != ReasonRemoved { + t.Fatalf("State() = kind %v reason %q after a removal, want Revoked for %q", got.kind, got.reason, ReasonRemoved) + } + dials := rig.relayDials.Load() + rig.directDials.Load() + rig.fc.Advance(2 * time.Hour) + quiesce() + if after := rig.relayDials.Load() + rig.directDials.Load(); after != dials { + t.Fatalf("a revoked link dialled %d more times in two hours", after-dials) + } + if n := rig.fc.BlockedTimers(); n != 0 { + t.Fatalf("a revoked link still holds %d timers", n) + } + if st := rig.link.State(); st.Kind != Revoked { + t.Fatalf("State() = %+v two hours after a removal, want Revoked", st) + } + }) + } +} + +// J1: with no DirectConfig the Link behaves as it did before the direct road +// existed even when the host offers it: no signalling frame, no attempt timer, +// no ping, the road word is the relay's, and the only timer a view holds is the +// idle detach. +func TestWithNoDirectConfigTheLinkNeverSignalsNeverTimersAndReportsTheRelayRoad(t *testing.T) { + rig := newDirectRig(t, rigOpts{noDirect: true}) + chA := rig.openChat("chat-a") + chB := rig.openChat("chat-b") + if road := rig.speak(chA); road != RoadRelay { + t.Fatalf("chat-a was carried on %q, want the relay", road) + } + rig.speak(chB) + relay := rig.tunnel(RoadRelay, 1) + if st := rig.link.State(); st.Kind != Live || st.Road != RoadRelay || rig.link.Road() != RoadRelay { + t.Fatalf("State() = %+v, Road() = %q, want Live on the relay", st, rig.link.Road()) + } + within(t, "the idle timer to be the only timer", func() bool { return rig.fc.BlockedTimers() == 1 }) + + rig.fc.Advance(5 * time.Minute) + quiesce() + for name, op := range map[string]uint8{"signal": OpSignal, "ping": OpPing, "close": OpClose, "reset": OpReset} { + if n := relay.viewer.sent.count(op); n != 0 { + t.Fatalf("a view with no direct config sent %d %s frames in five quiet minutes", n, name) + } + } + if n := rig.fc.BlockedTimers(); n != 1 { + t.Fatalf("a view with no direct config holds %d timers, want only the idle detach", n) + } + if n := rig.host.offers(); n != 0 { + t.Fatalf("the host was offered a direct road %d times by a link that has none", n) + } + if n := rig.relayDials.Load(); n != 1 { + t.Fatalf("the relay was dialled %d times, want once", n) + } + for _, st := range rig.statesFrom(0) { + if st.Road == RoadDirect { + t.Fatalf("a link with no direct config reported %+v", st) + } + } + if ended := rig.endedList(); len(ended) != 0 { + t.Fatalf("channels ended: %v", ended) + } +} + +// A (the public surface): the signalling a direct-road implementation needs rides +// the relay tunnel. SendSignal puts one OpSignal frame on channel 0 of the relay +// tunnel and fails when there is none; the host's frames come back through +// LinkConfig.OnSignal; and the Signaller a direct dial is handed is the same road. +func TestSignalsRideTheRelayTunnelBothWaysAndFailWithNoTunnel(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + if err := rig.link.SendSignal([]byte("x")); err == nil { + t.Fatal("SendSignal succeeded on a link with no relay tunnel") + } + + offer, err := EncodeSignal(Signal{T: SignalOffer, ID: "attempt-1", SDP: "v=0"}) + if err != nil { + t.Fatal(err) + } + cand, err := EncodeSignal(Signal{T: SignalCandidate, ID: "attempt-1", C: "candidate:1"}) + if err != nil { + t.Fatal(err) + } + answer, err := EncodeSignal(Signal{T: SignalAnswer, ID: "attempt-1", SDP: "v=0 answered"}) + if err != nil { + t.Fatal(err) + } + sent := make(chan error, 1) + rig.setDirect(func(ctx context.Context, _ int, s Signaller) (io.ReadWriteCloser, error) { + sent <- s.Send(offer) + <-ctx.Done() + return nil, ctx.Err() + }) + rig.speak(rig.openChat("chat-a")) + rig.waitAttemptArmed(DirectSettle) + rig.fc.Advance(DirectSettle) + select { + case err := <-sent: + if err != nil { + t.Fatalf("the direct dial's Signaller failed: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("the direct dial never sent its offer") + } + within(t, "the host to be offered", func() bool { return rig.host.offers() == 1 }) + rig.host.mu.Lock() + gotOffer := append([]byte(nil), rig.host.payloads[0]...) + hostSide := rig.host.signals[0] + rig.host.mu.Unlock() + if !bytes.Equal(gotOffer, offer) { + t.Fatalf("the host was offered %q, want %q", gotOffer, offer) + } + + // The host's answer reaches OnSignal. + if err := hostSide.Send(answer); err != nil { + t.Fatal(err) + } + within(t, "the answer to reach OnSignal", func() bool { return len(rig.signalsGot()) == 1 }) + if got := rig.signalsGot()[0]; !bytes.Equal(got, answer) { + t.Fatalf("OnSignal was handed %q, want %q", got, answer) + } + + // The link's own SendSignal reaches the host's session for that attempt. + if err := rig.link.SendSignal(cand); err != nil { + t.Fatalf("SendSignal failed with a relay tunnel up: %v", err) + } + within(t, "the candidate to reach the host's session", func() bool { return len(rig.host.session(0).deliveries()) == 1 }) + if got := rig.host.session(0).deliveries()[0]; !bytes.Equal(got, cand) { + t.Fatalf("the host's session was delivered %q, want %q", got, cand) + } + + // Both frames crossed the relay tunnel, on channel 0. + relay := rig.tunnel(RoadRelay, 1) + var signals []tapFrame + for _, fr := range relay.viewer.sent.since(0) { + if fr.op == OpSignal { + signals = append(signals, fr) + } + } + if len(signals) != 2 || signals[0].channel != 0 || signals[1].channel != 0 { + t.Fatalf("the relay tunnel carried %+v, want the offer and the candidate on channel 0", signals) + } +} diff --git a/internal/livedoor/link_test.go b/internal/livedoor/link_test.go new file mode 100644 index 0000000000..1458a88627 --- /dev/null +++ b/internal/livedoor/link_test.go @@ -0,0 +1,1110 @@ +package livedoor + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/remote" +) + +// countingRWC wraps an io.ReadWriteCloser and counts every byte and write call +// sent by the viewer mux onto the underlying tunnel. +type countingRWC struct { + rwc io.ReadWriteCloser + writes atomic.Int64 + written atomic.Int64 + closed atomic.Bool + closeCh chan struct{} + once sync.Once +} + +func newCountingRWC(rwc io.ReadWriteCloser) *countingRWC { + return &countingRWC{ + rwc: rwc, + closeCh: make(chan struct{}), + } +} + +func (c *countingRWC) Read(p []byte) (int, error) { + return c.rwc.Read(p) +} + +func (c *countingRWC) Write(p []byte) (int, error) { + n, err := c.rwc.Write(p) + if n > 0 { + c.writes.Add(1) + c.written.Add(int64(n)) + } + return n, err +} + +func (c *countingRWC) Close() error { + c.closed.Store(true) + c.once.Do(func() { + close(c.closeCh) + }) + return c.rwc.Close() +} + +func (c *countingRWC) ResetCounts() { + c.writes.Store(0) + c.written.Store(0) +} + +// startStubHostResolver returns a Resolver backed by the hand-made stub holder +// pattern from serve_test.go so Serve can accept viewer channels over net.Pipe. +func startStubHostResolver(t *testing.T) Resolver { + t.Helper() + return fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.link.stubHolder", func() { + defer holderSide.Close() + scan := newLineScanner(holderSide, MaxLine) + line, err := scan.ReadLine(FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f) != nil { + return + } + var h remote.Hello + if json.Unmarshal(f.Payload, &h) != nil { + return + } + wPayload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: h.Workspace, + SessionFile: h.Session, + Model: "test-model", + Remote: h.Remote, + }) + wFrame, _ := json.Marshal(remote.Frame{ + Kind: "welcome", + Payload: wPayload, + }) + _, _ = holderSide.Write(append(wFrame, '\n')) + _, _ = io.Copy(io.Discard, holderSide) + }) + return routerSide, Route{ + Kind: "daemon", + PID: 7001, + Session: "/work/p/" + chat + "/transcript.jsonl", + Workspace: "/work/p", + }, nil + }) +} + +// nextPendingTimerWait returns the duration from fc.Now() until the earliest +// pending timer on fc. +func nextPendingTimerWait(t *testing.T, fc *FakeClock) time.Duration { + t.Helper() + fc.WaitForTimers(1) + fc.mu.Lock() + defer fc.mu.Unlock() + if len(fc.pending) == 0 { + t.Fatal("expected at least 1 pending timer on FakeClock, found 0") + } + best := fc.pending[0] + for _, tm := range fc.pending[1:] { + if tm.at.Before(best.at) { + best = tm + } + } + return best.at.Sub(fc.now) +} + +// TestAnActiveViewerSaysTheHostIsGoneWithinTheDeadline verifies contract V7a: +// an active view (Touch every virtual second) whose host stops answering stays +// Live at +8.9 s, transitions to WentOffline past +9 s, closes the tunnel, and +// schedules a pending redial timer. +func TestAnActiveViewerSaysTheHostIsGoneWithinTheDeadline(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + + var ( + mutePings atomic.Bool + firstConn *countingRWC + dialCalled atomic.Int32 + ) + + link := NewLink(LinkConfig{ + Clock: fc, + HostName: "Desktop", + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + n := dialCalled.Add(1) + vSide, hSide := net.Pipe() + t.Cleanup(func() { + _ = vSide.Close() + _ = hSide.Close() + }) + counted := newCountingRWC(vSide) + if n == 1 { + firstConn = counted + } + + // Host frame loop answers HELLO_ACK and OPEN, and answers PING only + // while mutePings is false; once muted, it drains and discards frames + // without ever replying so the host is silently gone. + guard.Go("livedoor.test.v7a.host", func() { + defer hSide.Close() + ackPayload, _ := json.Marshal(HelloAck{ + V: 1, + Watch: true, + Drive: true, + Road: "relay", + Limits: DefaultLimits(), + }) + _, _ = writeFrame(hSide, frame{ + op: OpHelloAck, + channel: 0, + payload: ackPayload, + }, ChunkBytes) + + for { + f, err := readFrame(hSide, ChunkBytes, nil) + if err != nil { + return + } + if mutePings.Load() { + continue + } + switch f.op { + case OpOpen: + _, _ = writeFrame(hSide, frame{ + op: OpOpened, + channel: f.channel, + }, ChunkBytes) + case OpPing: + _, _ = writeFrame(hSide, frame{ + op: OpPong, + channel: 0, + payload: f.payload, + }, ChunkBytes) + } + } + }) + return counted, nil + }, + }) + t.Cleanup(link.Close) + + ch, err := link.OpenerContext("chat-v7a")(ctx) + if err != nil { + t.Fatalf("OpenerContext(chat-v7a) failed: %v", err) + } + defer ch.Close() + + if got := link.State().Kind; got != Live { + t.Fatalf("initial State().Kind = %v, want %v", got, Live) + } + + // Host stops answering right after the channel opens; the person acts every + // virtual second. + mutePings.Store(true) + link.Touch() + + for sec := 1; sec <= 8; sec++ { + fc.Advance(time.Second) + eventually(t, "liveness timer to be armed", func() bool { + return fc.BlockedTimers() >= 1 + }) + link.Touch() + if got := link.State().Kind; got != Live { + t.Fatalf("at +%ds State().Kind = %v, want %v", sec, got, Live) + } + } + + // At +8.9 s the link must still be Live and the tunnel still open. + fc.Advance(900 * time.Millisecond) + if got := link.State().Kind; got != Live { + t.Fatalf("at +8.9s State().Kind = %v, want %v", got, Live) + } + if firstConn.closed.Load() { + t.Fatal("at +8.9s the tunnel was already closed, want still open") + } + + // Past +9 s (PingEvery 3s + DeadAfter 6s), State is WentOffline, the tunnel + // has been closed, and a pending redial timer exists on the fake clock. + fc.Advance(200 * time.Millisecond) + eventually(t, "past +9s State().Kind to become WentOffline", func() bool { + return link.State().Kind == WentOffline + }) + eventually(t, "past +9s the tunnel to be closed", firstConn.closed.Load) + eventually(t, "past +9s a pending redial timer to be scheduled", func() bool { + return fc.BlockedTimers() >= 1 + }) +} + +// TestAnIdleViewerSendsNothingAndLearnsFromTheCloseOrThePresenceSignal verifies +// contract V7b and V15: an idle foreground view (no Touch, not Active) writes +// zero bytes across 10 virtual minutes minus a second, has zero pending timers +// and zero writes when idle with no channels, transitions to WentOffline +// immediately when the host closes the tunnel, and sends exactly one PING on a +// Touch after a quiet spell. +func TestAnIdleViewerSendsNothingAndLearnsFromTheCloseOrThePresenceSignal(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + + var ( + curCounted *countingRWC + curHostEnd net.Conn + ) + + link := NewLink(LinkConfig{ + Clock: fc, + HostName: "Desktop", + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + vSide, hSide := net.Pipe() + t.Cleanup(func() { + _ = vSide.Close() + _ = hSide.Close() + }) + counted := newCountingRWC(vSide) + curCounted = counted + curHostEnd = hSide + + hMux := NewMux(hSide, Host, MuxConfig{}) + t.Cleanup(func() { _ = hMux.Close() }) + _ = hMux.SendHelloAck(HelloAck{ + V: 1, + Watch: true, + Drive: true, + Road: "relay", + Limits: DefaultLimits(), + }) + guard.Go("livedoor.test.v7b.accept", func() { + for { + ch, _, err := hMux.Accept(ctx) + if err != nil { + return + } + _ = ch.Accept() + } + }) + return counted, nil + }, + }) + t.Cleanup(link.Close) + + // 1. Open and then close a channel so the link is idle with no channels: + // verify zero timers pending and zero writes while idle with no channels. + ch0, err := link.OpenerContext("chat-temp")(ctx) + if err != nil { + t.Fatalf("OpenerContext(chat-temp) failed: %v", err) + } + _ = ch0.Close() + eventually(t, "idle timer teardown and channel close flush", func() bool { + return fc.BlockedTimers() == 0 && curCounted.writes.Load() >= 2 + }) + curCounted.ResetCounts() + if got := fc.BlockedTimers(); got != 0 { + t.Fatalf("BlockedTimers() while idle with no channels = %d, want 0", got) + } + fc.Advance(5 * time.Minute) + if got := curCounted.written.Load(); got != 0 { + t.Fatalf("bytes written while idle with no channels = %d, want 0", got) + } + + // 2. Open a foreground channel and leave it idle (no Touch, not Active) for + // 10 virtual minutes minus a second: assert ZERO bytes written. + ch1, err := link.OpenerContext("chat-idle")(ctx) + if err != nil { + t.Fatalf("OpenerContext(chat-idle) failed: %v", err) + } + defer ch1.Close() + + // Wait for the open frame to flush and the single idle detach timer to arm, then zero the counter. + eventually(t, "open frame flush and idle detach timer arm", func() bool { + return fc.BlockedTimers() == 1 && curCounted.writes.Load() >= 1 + }) + curCounted.ResetCounts() + + fc.Advance(IdleDetach - time.Second) + if got := link.State().Kind; got != Live { + t.Fatalf("at 9m59s State().Kind = %v, want %v", got, Live) + } + if got := curCounted.written.Load(); got != 0 { + t.Fatalf("bytes written during 9m59s idle spell = %d, want 0", got) + } + + // 3. A Touch() after a quiet spell sends exactly one PING. + link.Touch() + eventually(t, "probe PING write after Touch()", func() bool { + return curCounted.writes.Load() >= 1 + }) + if writes := curCounted.writes.Load(); writes != 1 { + t.Fatalf("writes after Touch() following quiet spell = %d, want 1", writes) + } + const pingFrameSize = frameHeaderBytes + 4 + if bytesWritten := curCounted.written.Load(); bytesWritten != pingFrameSize { + t.Fatalf("bytes written by probe PING = %d, want %d", bytesWritten, pingFrameSize) + } + + // Wait for the host's PONG to arrive and advance past ActiveWindow (30s) so + // the link returns to an idle posture before testing an immediate host close. + eventually(t, "host PONG to be recorded by the viewer link", func() bool { + link.mu.Lock() + defer link.mu.Unlock() + return link.probeDeadline.IsZero() && link.lastHeard.Equal(fc.Now()) + }) + fc.Advance(ActiveWindow + time.Second) + eventually(t, "active window expiry to re-arm single idle detach timer", func() bool { + return fc.BlockedTimers() == 1 + }) + curCounted.ResetCounts() + + // 4. When the host closes the tunnel while the viewer is idle, State becomes + // WentOffline immediately with no 3s wait. + _ = curHostEnd.Close() + eventually(t, "State().Kind to become WentOffline after host closed tunnel", func() bool { + return link.State().Kind == WentOffline + }) + if got := curCounted.written.Load(); got != 0 { + t.Fatalf("bytes written when host closed idle tunnel = %d, want 0", got) + } +} + +// TestAViewerIdleForTenMinutesDetachesWithOneCloseAndKeepsItsView verifies +// contract V24: an idle viewer with open channels is still Live at 9m59s, +// detaches at 10m01s with State Idle, closes the tunnel with zero bytes written +// during the idle spell and at detach, reports reason "idle" to OnChannelEnd +// once for every open channel, and reconnects on a later Touch(). +func TestAViewerIdleForTenMinutesDetachesWithOneCloseAndKeepsItsView(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + resolver := startStubHostResolver(t) + peer := Peer{ + Device: "dev-v24", + Label: "laptop", + Permit: pair.Permit{Watch: true, Drive: true}, + } + + var ( + dialCount atomic.Int32 + firstCount *countingRWC + ) + + link := NewLink(LinkConfig{ + Clock: fc, + HostName: "Desktop", + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + n := dialCount.Add(1) + vSide, hSide := net.Pipe() + t.Cleanup(func() { + _ = vSide.Close() + _ = hSide.Close() + }) + counted := newCountingRWC(vSide) + if n == 1 { + firstCount = counted + } + guard.Go("livedoor.test.v24.serve", func() { + _ = Serve(ctx, hSide, peer, ServeConfig{ + Resolver: resolver, + Host: "Desktop", + Road: "relay", + }) + }) + return counted, nil + }, + }) + t.Cleanup(link.Close) + + var ( + endMu sync.Mutex + endedChats = make(map[string][]string) + ) + link.OnChannelEnd(func(chat, reason string) { + endMu.Lock() + endedChats[chat] = append(endedChats[chat], reason) + endMu.Unlock() + }) + + ch1, err := link.OpenerContext("chat-a")(ctx) + if err != nil { + t.Fatalf("OpenerContext(chat-a) failed: %v", err) + } + ch2, err := link.OpenerContext("chat-b")(ctx) + if err != nil { + t.Fatalf("OpenerContext(chat-b) failed: %v", err) + } + if got := dialCount.Load(); got != 1 { + t.Fatalf("dialCount for two chats on one Link = %d, want 1", got) + } + + eventually(t, "open frames to flush and idle detach timer to arm", func() bool { + return fc.BlockedTimers() == 1 && firstCount.writes.Load() >= 2 + }) + firstCount.ResetCounts() + + // Boundary 9m59s: still Live, tunnel open, zero bytes written. + fc.Advance(9*time.Minute + 59*time.Second) + if got := link.State().Kind; got != Live { + t.Fatalf("at 9m59s State().Kind = %v, want %v", got, Live) + } + if firstCount.closed.Load() { + t.Fatal("at 9m59s tunnel was already closed") + } + if got := firstCount.written.Load(); got != 0 { + t.Fatalf("at 9m59s bytes written = %d, want 0", got) + } + + // Boundary 10m01s: State Idle, tunnel closed, zero bytes written at detach, + // and every channel ended with reason "idle". + fc.Advance(2 * time.Second) + eventually(t, "at 10m01s State().Kind to become Idle", func() bool { + return link.State().Kind == Idle + }) + if got := link.State().Reason; got != ReasonIdle { + t.Fatalf("at 10m01s State().Reason = %q, want %q", got, ReasonIdle) + } + eventually(t, "the tunnel to be closed on idle detach at 10m01s", firstCount.closed.Load) + if got := firstCount.written.Load(); got != 0 { + t.Fatalf("bytes written during idle spell and detach = %d, want 0 (one close is the whole cost)", got) + } + eventually(t, "no timers to be pending after idle detach", func() bool { return fc.BlockedTimers() == 0 }) + + eventually(t, "both channels to report the idle end", func() bool { + endMu.Lock() + defer endMu.Unlock() + return len(endedChats["chat-a"]) > 0 && len(endedChats["chat-b"]) > 0 + }) + endMu.Lock() + gotA := append([]string(nil), endedChats["chat-a"]...) + gotB := append([]string(nil), endedChats["chat-b"]...) + endMu.Unlock() + if len(gotA) != 1 || gotA[0] != ReasonIdle { + t.Fatalf("OnChannelEnd for chat-a = %v, want [%q]", gotA, ReasonIdle) + } + if len(gotB) != 1 || gotB[0] != ReasonIdle { + t.Fatalf("OnChannelEnd for chat-b = %v, want [%q]", gotB, ReasonIdle) + } + + var buf [32]byte + _, err1 := ch1.Read(buf[:]) + if r, ok := ReasonOf(err1); !ok || r != ReasonIdle { + t.Fatalf("ReasonOf(ch1.Read) = (%q, %v) err=%v, want (%q, true)", r, ok, err1, ReasonIdle) + } + _, err2 := ch2.Read(buf[:]) + if r, ok := ReasonOf(err2); !ok || r != ReasonIdle { + t.Fatalf("ReasonOf(ch2.Read) = (%q, %v) err=%v, want (%q, true)", r, ok, err2, ReasonIdle) + } + + // A later Touch() reconnects the link. + link.Touch() + if got := link.State().Kind; got != Live { + t.Fatalf("State().Kind after Touch() = %v, want %v", got, Live) + } + if got := dialCount.Load(); got != 2 { + t.Fatalf("dialCount after Touch() reconnect = %d, want 2", got) + } +} + +// TestARunningTurnKeepsTheLinkActive verifies contract V24: when cfg.Active +// returns true, the link does not detach after 30 virtual minutes and continues +// sending liveness pings every 3 seconds (PingEvery). +func TestARunningTurnKeepsTheLinkActive(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + + var ( + hostPings atomic.Int64 + counted *countingRWC + ) + + link := NewLink(LinkConfig{ + Clock: fc, + HostName: "Desktop", + Active: func() bool { return true }, + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + vSide, hSide := net.Pipe() + t.Cleanup(func() { + _ = vSide.Close() + _ = hSide.Close() + }) + counted = newCountingRWC(vSide) + hMux := NewMux(hSide, Host, MuxConfig{ + OnFrameRead: func(n int) { + if n == frameHeaderBytes+4 { + hostPings.Add(1) + } + }, + }) + t.Cleanup(func() { _ = hMux.Close() }) + _ = hMux.SendHelloAck(HelloAck{ + V: 1, + Watch: true, + Drive: true, + Road: "relay", + Limits: DefaultLimits(), + }) + guard.Go("livedoor.test.v24active.accept", func() { + for { + ch, _, err := hMux.Accept(ctx) + if err != nil { + return + } + _ = ch.Accept() + } + }) + return counted, nil + }, + }) + t.Cleanup(link.Close) + + ch, err := link.OpenerContext("chat-turn")(ctx) + if err != nil { + t.Fatalf("OpenerContext(chat-turn) failed: %v", err) + } + defer ch.Close() + + eventually(t, "open frame to flush and active liveness timer to arm", func() bool { + return fc.BlockedTimers() == 1 && counted.writes.Load() >= 1 + }) + counted.ResetCounts() + hostPings.Store(0) + + steps := int((30 * time.Minute) / PingEvery) + for i := 1; i <= steps; i++ { + fc.Advance(PingEvery) + wantHeard := fc.Now() + // Wait for the ping-pong round trip over net.Pipe and the next liveness + // timer registration to complete at this virtual timestamp before + // advancing the fake clock again. + eventually(t, fmt.Sprintf("ping #%d round trip", i), func() bool { + if counted.writes.Load() < int64(i) || hostPings.Load() < int64(i) || fc.BlockedTimers() < 1 { + return false + } + link.mu.Lock() + heard := link.lastHeard + link.mu.Unlock() + return heard.Equal(wantHeard) + }) + if got := link.State().Kind; got != Live { + t.Fatalf("at step %d (%v) State().Kind = %v, want %v", i, time.Duration(i)*PingEvery, got, Live) + } + } + + if got := counted.writes.Load(); got != int64(steps) { + t.Fatalf("after 30 virtual minutes writes = %d, want %d pings (one every %v)", got, steps, PingEvery) + } +} + +// TestTheFirstRetryAfterADropWaitsAJitteredSecondAndThenDoubles verifies +// contract (reconnect): after an active tunnel drops, the first retry wait is +// within [1 s, 6 s) and subsequent retries wait within [0.75, 1.25) x doubled +// (2 s, 4 s, 8 s, 15 s cap) on the fake clock. +func TestTheFirstRetryAfterADropWaitsAJitteredSecondAndThenDoubles(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + + var ( + dialCount atomic.Int32 + allowDial atomic.Bool + hostConn net.Conn + ) + allowDial.Store(true) + + link := NewLink(LinkConfig{ + Clock: fc, + HostName: "Desktop", + Active: func() bool { return true }, + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + dialCount.Add(1) + if !allowDial.Load() { + return nil, errors.New("connection refused") + } + vSide, hSide := net.Pipe() + t.Cleanup(func() { + _ = vSide.Close() + _ = hSide.Close() + }) + hostConn = hSide + hMux := NewMux(hSide, Host, MuxConfig{}) + t.Cleanup(func() { _ = hMux.Close() }) + _ = hMux.SendHelloAck(HelloAck{ + V: 1, + Watch: true, + Drive: true, + Road: "relay", + Limits: DefaultLimits(), + }) + guard.Go("livedoor.test.backoff.accept", func() { + for { + ch, _, err := hMux.Accept(ctx) + if err != nil { + return + } + _ = ch.Accept() + } + }) + return vSide, nil + }, + }) + t.Cleanup(link.Close) + + ch, err := link.OpenerContext("chat-roam")(ctx) + if err != nil { + t.Fatalf("initial OpenerContext failed: %v", err) + } + defer ch.Close() + + if got := dialCount.Load(); got != 1 { + t.Fatalf("initial dialCount = %d, want 1", got) + } + + // Drop the active tunnel and keep dials failing through the backoff ramp. + allowDial.Store(false) + _ = hostConn.Close() + + // Wait for the closed pipe to be observed and State to transition to Reconnecting. + eventually(t, "State().Kind to become Reconnecting after active tunnel drop", func() bool { + return link.State().Kind == Reconnecting + }) + wait1 := nextPendingTimerWait(t, fc) + if wait1 < time.Second || wait1 >= 6*time.Second { + t.Fatalf("first retry wait = %v, want in [1s, 6s)", wait1) + } + + // Advance to 1ms before wait1: dial must not have fired yet. + fc.Advance(wait1 - time.Millisecond) + if got := dialCount.Load(); got != 1 { + t.Fatalf("dialCount 1ms before first retry = %d, want 1", got) + } + // Advance past wait1: first retry fires (dialCount -> 2) and schedules wait2. + fc.Advance(2 * time.Millisecond) + eventually(t, "dialCount to reach 2 at first retry", func() bool { + return dialCount.Load() == 2 + }) + + expectedDoubled := []time.Duration{ + 2 * time.Second, + 4 * time.Second, + 8 * time.Second, + 15 * time.Second, + 15 * time.Second, + } + for i, base := range expectedDoubled { + low := time.Duration(float64(base) * 0.75) + high := time.Duration(float64(base) * 1.25) + wait := nextPendingTimerWait(t, fc) + if wait < low || wait >= high { + t.Fatalf("retry #%d (base %v) wait = %v, want in [%v, %v)", i+2, base, wait, low, high) + } + + if i == len(expectedDoubled)-1 { + allowDial.Store(true) + } + before := dialCount.Load() + fc.Advance(wait - time.Millisecond) + if got := dialCount.Load(); got != before { + t.Fatalf("retry #%d fired early at %v", i+2, wait-time.Millisecond) + } + fc.Advance(2 * time.Millisecond) + eventually(t, fmt.Sprintf("retry #%d to fire at %v", i+2, wait), func() bool { + return dialCount.Load() == before+1 + }) + } + + eventually(t, "State().Kind to become Live after successful retry", func() bool { + return link.State().Kind == Live + }) +} + +// TestALaggingChannelReopensAtOnceWithNoWaitAndTheTunnelStays verifies contract +// (reconnect exception): when a single channel ends with reason "lagging" (or +// "permit-changed"), the tunnel stays open with zero redial wait and the very +// next Opener call opens a new channel on the same tunnel immediately. +func TestALaggingChannelReopensAtOnceWithNoWaitAndTheTunnelStays(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + + var ( + dialCount atomic.Int32 + acceptStep atomic.Int32 + hostCh1Ch = make(chan *Channel, 1) + ) + + link := NewLink(LinkConfig{ + Clock: fc, + HostName: "Desktop", + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + dialCount.Add(1) + vSide, hSide := net.Pipe() + t.Cleanup(func() { + _ = vSide.Close() + _ = hSide.Close() + }) + hMux := NewMux(hSide, Host, MuxConfig{}) + t.Cleanup(func() { _ = hMux.Close() }) + _ = hMux.SendHelloAck(HelloAck{ + V: 1, + Watch: true, + Drive: true, + Road: "relay", + Limits: DefaultLimits(), + }) + guard.Go("livedoor.test.lagging.accept", func() { + for { + ch, _, err := hMux.Accept(ctx) + if err != nil { + return + } + _ = ch.Accept() + if acceptStep.Add(1) == 1 { + hostCh1Ch <- ch + } + } + }) + return vSide, nil + }, + }) + t.Cleanup(link.Close) + + endedReason := make(chan string, 1) + link.OnChannelEnd(func(chat, reason string) { + endedReason <- reason + }) + + ch1, err := link.OpenerContext("chat-lag")(ctx) + if err != nil { + t.Fatalf("first OpenerContext(chat-lag) failed: %v", err) + } + hostCh1 := <-hostCh1Ch + + // Host resets channel 1 with ReasonLagging. + if err := hostCh1.Reset(ReasonLagging); err != nil { + t.Fatalf("hostCh1.Reset(ReasonLagging) failed: %v", err) + } + + var buf [32]byte + _, readErr := ch1.Read(buf[:]) + if r, ok := ReasonOf(readErr); !ok || r != ReasonLagging { + t.Fatalf("ReasonOf(ch1.Read) = (%q, %v), want (%q, true)", r, ok, ReasonLagging) + } + if got := <-endedReason; got != ReasonLagging { + t.Fatalf("OnChannelEnd reason = %q, want %q", got, ReasonLagging) + } + + // The tunnel must still be Live and the next Opener call must succeed at + // once without advancing the clock or opening a second tunnel. + if got := link.State().Kind; got != Live { + t.Fatalf("State().Kind after lagging channel reset = %v, want %v", got, Live) + } + ch2, err := link.OpenerContext("chat-lag")(ctx) + if err != nil { + t.Fatalf("second OpenerContext(chat-lag) failed: %v", err) + } + defer ch2.Close() + + if got := dialCount.Load(); got != 1 { + t.Fatalf("dialCount after reopening lagging channel = %d, want 1 (same tunnel)", got) + } +} + +// TestRemovedStopsTheRetriesForGood verifies contract (reconnect exception): +// when the host revokes the viewer with reason "removed", State becomes Revoked +// with Reason "removed", all retries stop for good, and subsequent Opener calls +// fail with ReasonRemoved without dialling again. +func TestRemovedStopsTheRetriesForGood(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + reg := NewRegistry() + resolver := startStubHostResolver(t) + peer := Peer{ + Device: "dev-removed", + Label: "laptop", + Permit: pair.Permit{Watch: true, Drive: true}, + } + + var dialCount atomic.Int32 + link := NewLink(LinkConfig{ + Clock: fc, + HostName: "Desktop", + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + dialCount.Add(1) + vSide, hSide := net.Pipe() + t.Cleanup(func() { + _ = vSide.Close() + _ = hSide.Close() + }) + guard.Go("livedoor.test.removed.serve", func() { + _ = Serve(ctx, hSide, peer, ServeConfig{ + Resolver: resolver, + Registry: reg, + Host: "Desktop", + Road: "relay", + }) + }) + return vSide, nil + }, + }) + t.Cleanup(link.Close) + + ch, err := link.OpenerContext("chat-revoked")(ctx) + if err != nil { + t.Fatalf("OpenerContext(chat-revoked) failed: %v", err) + } + + reg.Revoke(peer.Device) + + var buf [32]byte + _, readErr := ch.Read(buf[:]) + if r, ok := ReasonOf(readErr); !ok || r != ReasonRemoved { + t.Fatalf("ReasonOf(ch.Read) after Revoke = (%q, %v), want (%q, true)", r, ok, ReasonRemoved) + } + + eventually(t, "State() to become Revoked with no blocked timers after Revoke", func() bool { + return link.State().Kind == Revoked && fc.BlockedTimers() == 0 + }) + st := link.State() + if st.Kind != Revoked || st.Reason != ReasonRemoved { + t.Fatalf("State() after Revoke = %+v, want Kind=%v Reason=%q", st, Revoked, ReasonRemoved) + } + if got := fc.BlockedTimers(); got != 0 { + t.Fatalf("BlockedTimers() after Revoke = %d, want 0 (retries must stop for good)", got) + } + + fc.Advance(time.Hour) + if got := dialCount.Load(); got != 1 { + t.Fatalf("dialCount after advancing 1h post-Revoke = %d, want 1", got) + } + + _, openErr := link.OpenerContext("chat-revoked")(ctx) + if r, ok := ReasonOf(openErr); !ok || r != ReasonRemoved { + t.Fatalf("Opener after Revoke returned %v (ReasonOf=%q, %v), want %q", openErr, r, ok, ReasonRemoved) + } + if got := dialCount.Load(); got != 1 { + t.Fatalf("dialCount after Opener call post-Revoke = %d, want 1", got) + } +} + +// TestNoLiveDoorMeansTheHostIsOfflineAndIsNotPolled verifies contract +// (reconnect exception): when Dial returns an error wrapping ErrHostOffline, +// State transitions immediately to WentOffline and the redial timer goes +// straight to the 15 s cap without polling at 1 s, 2 s, 4 s, or 8 s. +func TestNoLiveDoorMeansTheHostIsOfflineAndIsNotPolled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + + var dialCount atomic.Int32 + link := NewLink(LinkConfig{ + Clock: fc, + HostName: "Desktop", + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + dialCount.Add(1) + return nil, fmt.Errorf("relay 404: %w", ErrHostOffline) + }, + }) + t.Cleanup(link.Close) + + _, err := link.OpenerContext("chat-offline")(ctx) + if err == nil { + t.Fatal("OpenerContext against offline host succeeded, want error") + } + if !errors.Is(err, ErrHostOffline) { + t.Fatalf("OpenerContext error %v does not wrap ErrHostOffline", err) + } + if got := link.State().Kind; got != WentOffline { + t.Fatalf("State().Kind after ErrHostOffline = %v, want %v", got, WentOffline) + } + + // The scheduled wait must go straight to the 15s cap x [0.75, 1.25) = + // [11.25s, 18.75s), never polling at 1s..10s. + wait := nextPendingTimerWait(t, fc) + low := time.Duration(float64(15*time.Second) * 0.75) + high := time.Duration(float64(15*time.Second) * 1.25) + if wait < low || wait >= high { + t.Fatalf("redial wait after ErrHostOffline = %v, want in [%v, %v)", wait, low, high) + } + + fc.Advance(10 * time.Second) + if got := dialCount.Load(); got != 1 { + t.Fatalf("dialCount after 10s = %d, want 1 (must not poll missing host)", got) + } +} + +// TestTheOpenerErrorSpeaksTheHostsWords verifies contract (words): when the +// host refuses a channel with "not-running" (or HELLO_ACK denies watch / sets +// watch-only), Opener returns a *ReasonError whose Error() equals +// chatlist.LiveSaid("not-running", HostName) and ReasonOf extracts the reason. +func TestTheOpenerErrorSpeaksTheHostsWords(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + + // 1. Host with Drive:false sets State to WatchOnly with State.Permit, and a + // chat that is not running refuses with ReasonNotRunning. + peer := Peer{ + Device: "dev-words", + Label: "laptop", + Permit: pair.Permit{Watch: true, Drive: false}, + } + link := NewLink(LinkConfig{ + Clock: fc, + HostName: "StudioMac", + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + vSide, hSide := net.Pipe() + t.Cleanup(func() { + _ = vSide.Close() + _ = hSide.Close() + }) + guard.Go("livedoor.test.words.serve", func() { + _ = Serve(ctx, hSide, peer, ServeConfig{ + Resolver: nil, // nil resolver refuses every channel with ReasonNotRunning + Host: "StudioMac", + Road: "relay", + }) + }) + return vSide, nil + }, + }) + t.Cleanup(link.Close) + + _, err := link.Opener("missing-chat")() + if err == nil { + t.Fatal("Opener(missing-chat) succeeded, want refusal") + } + + var re *ReasonError + if !errors.As(err, &re) { + t.Fatalf("Opener error type = %T (%v), want *ReasonError", err, err) + } + wantSaid := chatlist.LiveSaid(ReasonNotRunning, "StudioMac") + if err.Error() != wantSaid { + t.Fatalf("err.Error() = %q, want %q", err.Error(), wantSaid) + } + if reason, ok := ReasonOf(err); !ok || reason != ReasonNotRunning { + t.Fatalf("ReasonOf(err) = (%q, %v), want (%q, true)", reason, ok, ReasonNotRunning) + } + + st := link.State() + if st.Kind != WatchOnly || !st.Permit.Watch || st.Permit.Drive { + t.Fatalf("State() with drive:false HELLO_ACK = %+v, want Kind=WatchOnly Permit={Watch:true Drive:false}", st) + } + + // 2. Host with Watch:false sets State to Revoked with reason "not-allowed" + // and makes every Opener fail with "not-allowed". + deniedPeer := Peer{ + Device: "dev-denied", + Label: "laptop", + Permit: pair.Permit{Watch: false, Drive: false}, + } + var deniedDials atomic.Int32 + deniedLink := NewLink(LinkConfig{ + Clock: fc, + HostName: "StudioMac", + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + deniedDials.Add(1) + vSide, hSide := net.Pipe() + t.Cleanup(func() { + _ = vSide.Close() + _ = hSide.Close() + }) + guard.Go("livedoor.test.words.serveDenied", func() { + _ = Serve(ctx, hSide, deniedPeer, ServeConfig{ + Host: "StudioMac", + Road: "relay", + }) + }) + return vSide, nil + }, + }) + t.Cleanup(deniedLink.Close) + + _, err1 := deniedLink.Opener("any-chat")() + if reason, ok := ReasonOf(err1); !ok || reason != ReasonNotAllowed { + t.Fatalf("ReasonOf(err1) on watch:false = (%q, %v), want (%q, true)", reason, ok, ReasonNotAllowed) + } + if err1.Error() != chatlist.LiveSaid(ReasonNotAllowed, "StudioMac") { + t.Fatalf("err1.Error() = %q, want %q", err1.Error(), chatlist.LiveSaid(ReasonNotAllowed, "StudioMac")) + } + if got := deniedLink.State(); got.Kind != Revoked || got.Reason != ReasonNotAllowed { + t.Fatalf("deniedLink.State() = %+v, want Kind=Revoked Reason=%q", got, ReasonNotAllowed) + } + + // A second Opener call must also fail with not-allowed without dialling again. + _, err2 := deniedLink.Opener("other-chat")() + if reason, ok := ReasonOf(err2); !ok || reason != ReasonNotAllowed { + t.Fatalf("ReasonOf(err2) on second opener = (%q, %v), want (%q, true)", reason, ok, ReasonNotAllowed) + } + if got := deniedDials.Load(); got != 1 { + t.Fatalf("deniedDials = %d, want 1", got) + } +} + +// TestEveryReasonConstantHasWordsInChatlist verifies contract (words +// consistency): every Reason* constant of the mux has a distinct, non-fallback +// chatlist.LiveSaid sentence, and chatlist.LiveIdle names the exact minutes of +// IdleDetach. +func TestEveryReasonConstantHasWordsInChatlist(t *testing.T) { + const host = "Desktop" + fallback := chatlist.LiveSaid("unknown-reason-sentinel", host) + + reasons := []string{ + ReasonNotRunning, + ReasonNotAllowed, + ReasonHolderGone, + ReasonHolderOld, + ReasonRemoved, + ReasonPermitChanged, + ReasonLagging, + ReasonFrameTooLarge, + ReasonBudget, + ReasonIdle, + ReasonHostClosing, + ReasonTooMany, + ReasonRemoteControlOff, + } + + seen := make(map[string]string, len(reasons)) + for _, r := range reasons { + said := chatlist.LiveSaid(r, host) + if strings.TrimSpace(said) == "" { + t.Fatalf("reason %q produced an empty sentence", r) + } + if said == fallback { + t.Fatalf("reason %q fell back to the generic sentence %q", r, fallback) + } + if prev, dup := seen[said]; dup { + t.Fatalf("reasons %q and %q share the same sentence %q", r, prev, said) + } + seen[said] = r + } + + wantMinutes := fmt.Sprint(int(IdleDetach / time.Minute)) + if !strings.Contains(chatlist.LiveIdle, wantMinutes) { + t.Fatalf("chatlist.LiveIdle = %q, does not contain IdleDetach minutes %q", chatlist.LiveIdle, wantMinutes) + } +} diff --git a/internal/livedoor/listen.go b/internal/livedoor/listen.go new file mode 100644 index 0000000000..fa373e7517 --- /dev/null +++ b/internal/livedoor/listen.go @@ -0,0 +1,352 @@ +package livedoor + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/buildinfo" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/home" + "github.com/Agent-Field/codeaf/internal/remote" +) + +const staleDialTimeout = 100 * time.Millisecond + +type registryEntry struct { + PID int `json:"pid"` + Socket string `json:"socket"` + Build string `json:"build"` +} + +// Listener accepts local holder connections for desk and in-process sessions +// and publishes the holder's PID and relative socket name under /v3/live. +type Listener struct { + ln net.Listener + open func(transcript string) (*remote.Session, bool) + jsonPath string + sockPath string + + mu sync.Mutex + closed bool + // conns is every accepted connection, each with the chat its hello named + // ("" until that hello has been resolved), which is what lets CloseChat end + // one chat's viewers and no others. + conns map[net.Conn]string + wg sync.WaitGroup + closeOnce sync.Once +} + +// Listen binds /v3/live/.sock, sweeps stale registry files of dead +// processes in that directory, writes /v3/live/.json atomically with +// mode 0600, and serves accepted connections with remote.ServeAttach. +func Listen(homeDir string, open func(transcript string) (*remote.Session, bool), tr Transport) (*Listener, error) { + homeDir = strings.TrimSpace(homeDir) + if homeDir == "" { + homeDir = home.Dir() + } + if tr == nil { + tr = UnixTransport() + } + pid := os.Getpid() + dir := filepath.Join(homeDir, "v3", "live") + sockName := strconv.Itoa(pid) + ".sock" + sockPath := filepath.Join(dir, sockName) + jsonPath := filepath.Join(dir, strconv.Itoa(pid)+".json") + + if err := checkUnixSocketPath(sockPath); err != nil { + return nil, err + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, fmt.Errorf("livedoor: create live registry dir: %w", err) + } + _ = os.Chmod(dir, 0o700) + + sweepStaleRegistry(dir, pid, tr) + _ = os.Remove(sockPath) + + ln, err := tr.Listen(sockPath) + if err != nil { + return nil, err + } + _ = os.Chmod(sockPath, 0o600) + + entry := registryEntry{ + PID: pid, + Socket: sockName, + Build: currentBuildString(), + } + if err := writeRegistryAtomic(dir, jsonPath, entry); err != nil { + _ = ln.Close() + _ = os.Remove(sockPath) + return nil, err + } + + l := &Listener{ + ln: ln, + open: open, + jsonPath: jsonPath, + sockPath: sockPath, + conns: make(map[net.Conn]string), + } + l.wg.Add(1) + guard.Go("livedoor.listen.accept", l.acceptLoop) + return l, nil +} + +// Path returns the path of the registry JSON file written by this Listener. +func (l *Listener) Path() string { + return l.jsonPath +} + +// Close stops accepting connections, closes any active served connections, and +// removes both the registry JSON file and the unix socket file. +func (l *Listener) Close() error { + l.closeOnce.Do(func() { + l.mu.Lock() + l.closed = true + conns := make([]net.Conn, 0, len(l.conns)) + for c := range l.conns { + conns = append(conns, c) + } + l.mu.Unlock() + + _ = l.ln.Close() + for _, c := range conns { + _ = c.Close() + } + l.wg.Wait() + _ = os.Remove(l.jsonPath) + _ = os.Remove(l.sockPath) + }) + return nil +} + +func (l *Listener) acceptLoop() { + defer l.wg.Done() + for { + conn, err := l.ln.Accept() + if err != nil { + return + } + l.mu.Lock() + if l.closed { + l.mu.Unlock() + _ = conn.Close() + return + } + l.conns[conn] = "" + l.wg.Add(1) + l.mu.Unlock() + + guard.Go("livedoor.listen.conn", func() { + defer func() { + l.mu.Lock() + delete(l.conns, conn) + l.mu.Unlock() + _ = conn.Close() + l.wg.Done() + }() + _ = remote.ServeAttach(conn, conn, remote.AttachOptions{ + Open: func(hello remote.Hello) (*remote.Session, error) { + if hello.New { + return nil, errors.New("that conversation is not open here") + } + target := strings.TrimSpace(hello.Session) + if target != "" && l.open != nil { + // THE CONNECTION IS FILED UNDER ITS CHAT BEFORE THE CHAT IS + // ASKED FOR, and unfiled again if the answer is no. The + // holder lets a chat go (drops it from what open answers) + // and only then calls CloseChat, so a hello that lands in + // between is either filed in time to be closed or refused. + l.file(conn, target) + if sess, ok := l.open(target); ok && sess != nil { + return sess, nil + } + l.file(conn, "") + } + return nil, errors.New("that conversation is not open here") + }, + }) + }) + } +} + +// file records which chat a connection opened, under the spelling CloseChat +// compares by. +func (l *Listener) file(conn net.Conn, chat string) { + key := "" + if chat != "" { + key = chatKey(chat) + } + l.mu.Lock() + defer l.mu.Unlock() + if _, ok := l.conns[conn]; ok { + l.conns[conn] = key + } +} + +// CloseChat ends every viewer connection this listener has handed to chat, and +// only those, and says how many it ended. IT IS WHAT A HOLDER CALLS WHEN IT LETS +// A CHAT GO: a closed remote.Session tells its attached windows nothing and +// leaves their pipes open, while the live door's router reads the end of the +// holder's local connection as the holder having gone and ends the viewer's +// channel with `holder-gone`, the word every viewer already says for it. Without +// this a viewer of a chat the holder closed would sit on a view nobody feeds. +// +// The chat is compared by its physical path, so a symlinked spelling (the macOS +// temporary folder is one) names the same chat the holder's own spelling does. +func (l *Listener) CloseChat(chat string) int { + key := chatKey(chat) + if key == "" { + return 0 + } + l.mu.Lock() + var doomed []net.Conn + for c, k := range l.conns { + if k == key { + doomed = append(doomed, c) + } + } + l.mu.Unlock() + for _, c := range doomed { + _ = c.Close() + } + return len(doomed) +} + +// CloseAllChats ends every viewer connection this listener has handed to any +// chat, and says how many it ended. It is what turning remote control off does +// for the people already looking, beside the door's own refusal of anyone new: +// each viewer reads the end of the holder's connection as the holder having gone, +// exactly as it does for one chat (see [Listener.CloseChat]). A connection that +// has not yet opened a chat is not a viewer of one and is left to its own +// refusal. +func (l *Listener) CloseAllChats() int { + l.mu.Lock() + var doomed []net.Conn + for c, k := range l.conns { + if k != "" { + doomed = append(doomed, c) + } + } + l.mu.Unlock() + for _, c := range doomed { + _ = c.Close() + } + return len(doomed) +} + +// chatKey is the one spelling of a transcript path the listener compares by: the +// cleaned path with every symlink resolved, falling back to the resolved folder +// for a file that does not exist yet. +func chatKey(transcript string) string { + transcript = strings.TrimSpace(transcript) + if transcript == "" { + return "" + } + path := filepath.Clean(transcript) + if physical, err := filepath.EvalSymlinks(path); err == nil { + return physical + } + if dir, err := filepath.EvalSymlinks(filepath.Dir(path)); err == nil { + return filepath.Join(dir, filepath.Base(path)) + } + return path +} + +func writeRegistryAtomic(dir, jsonPath string, entry registryEntry) error { + raw, err := json.Marshal(entry) + if err != nil { + return err + } + tmp, err := os.CreateTemp(dir, ".live-*.tmp") + if err != nil { + return err + } + tmpName := tmp.Name() + _ = tmp.Chmod(0o600) + if _, err := tmp.Write(raw); err != nil { + _ = tmp.Close() + _ = os.Remove(tmpName) + return err + } + if err := tmp.Close(); err != nil { + _ = os.Remove(tmpName) + return err + } + if err := os.Rename(tmpName, jsonPath); err != nil { + _ = os.Remove(tmpName) + return err + } + _ = os.Chmod(jsonPath, 0o600) + return nil +} + +// sweepStaleRegistry removes any .json file in dir belonging to another +// process whose socket no longer accepts a connection. +func sweepStaleRegistry(dir string, selfPID int, tr Transport) { + entries, err := os.ReadDir(dir) + if err != nil { + return + } + for _, d := range entries { + if d.IsDir() { + continue + } + name := d.Name() + if !strings.HasSuffix(name, ".json") || strings.HasPrefix(name, ".") { + continue + } + stem := strings.TrimSuffix(name, ".json") + filePID, err := strconv.Atoi(stem) + if err != nil || filePID == selfPID { + continue + } + jsonFile := filepath.Join(dir, name) + raw, err := os.ReadFile(jsonFile) + if err != nil { + continue + } + var reg registryEntry + if err := json.Unmarshal(raw, ®); err != nil || reg.PID <= 0 || !validRelativeSocketName(strings.TrimSpace(reg.Socket)) { + _ = os.Remove(jsonFile) + continue + } + sockFile := filepath.Join(dir, strings.TrimSpace(reg.Socket)) + ctx, cancel := context.WithTimeout(context.Background(), staleDialTimeout) + conn, dialErr := tr.Dial(ctx, sockFile) + cancel() + if dialErr != nil { + // A DIAL THAT TIMED OUT IS A BUSY HOLDER, NOT A DEAD ONE. Only a + // refusal or a missing socket proves nobody is listening, and + // removing a live holder's file would make its chats unreachable + // until it restarted. + if errors.Is(dialErr, context.DeadlineExceeded) || errors.Is(dialErr, os.ErrDeadlineExceeded) { + continue + } + _ = os.Remove(jsonFile) + _ = os.Remove(sockFile) + continue + } + _ = conn.Close() + } +} + +// currentBuildString is the build stamp the presence file and the whois +// answer already carry, read once, so a registry file names the same build the +// rest of the product says. +var currentBuildString = sync.OnceValue(func() string { + if b := strings.TrimSpace(buildinfo.String()); b != "" && !strings.ContainsAny(b, `/\`) { + return b + } + return "dev" +}) diff --git a/internal/livedoor/listen_test.go b/internal/livedoor/listen_test.go new file mode 100644 index 0000000000..6a6cae03d3 --- /dev/null +++ b/internal/livedoor/listen_test.go @@ -0,0 +1,370 @@ +package livedoor + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" +) + +// TestAListenerServesAChatItHoldsAndRefusesOneItDoesNotAndWritesItsRegistryFile +// verifies contract V29: Listen removes stale registry files of dead PIDs, +// writes a 0600 registry JSON file with the current PID and a relative socket +// name containing no "/", welcomes a client that sends a Join hello for a held +// transcript, refuses an unknown transcript with a refusal sentence without +// booting anything, and removes both files on an idempotent Close. +func TestAListenerServesAChatItHoldsAndRefusesOneItDoesNotAndWritesItsRegistryFile(t *testing.T) { + homeDir := shortTempDir(t) + liveDir := filepath.Join(homeDir, "v3", "live") + if err := os.MkdirAll(liveDir, 0o700); err != nil { + t.Fatalf("MkdirAll(%q) failed: %v", liveDir, err) + } + + // Seed a stale registry file of a dead PID before calling Listen. + staleJSON := filepath.Join(liveDir, "999999.json") + staleSock := filepath.Join(liveDir, "999999.sock") + if err := os.WriteFile(staleJSON, []byte(`{"pid":999999,"socket":"999999.sock","build":"old"}`), 0o600); err != nil { + t.Fatalf("WriteFile stale json failed: %v", err) + } + if err := os.WriteFile(staleSock, []byte{}, 0o600); err != nil { + t.Fatalf("WriteFile stale sock failed: %v", err) + } + + heldTranscript := filepath.Join(homeDir, "v3", "projects", "p", "chat-1", "transcript.jsonl") + heldSession := remote.NewSession(&remote.Engine{ + Agent: &minimalWrappedAgent{title: "Held Chat"}, + Workspace: "/work/p", + SessionFile: heldTranscript, + }, true) + t.Cleanup(func() { _ = heldSession.Close() }) + + var openCalls atomic.Int32 + tr := UnixTransport() + ln, err := Listen(homeDir, func(transcript string) (*remote.Session, bool) { + openCalls.Add(1) + if filepath.Clean(transcript) == filepath.Clean(heldTranscript) { + return heldSession, true + } + return nil, false + }, tr) + if err != nil { + t.Fatalf("Listen failed: %v", err) + } + t.Cleanup(func() { _ = ln.Close() }) + + // Stale file of the dead PID must have been removed by Listen. + if _, err := os.Stat(staleJSON); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("stale registry file %q still exists after Listen (err=%v)", staleJSON, err) + } + + // Verify the registry JSON file exists with mode 0600, holds the right PID, + // and carries no "/" anywhere in its raw JSON bytes. + jsonPath := ln.Path() + info, err := os.Stat(jsonPath) + if err != nil { + t.Fatalf("Stat(%q) failed: %v", jsonPath, err) + } + if runtime.GOOS != "windows" { + if perm := info.Mode().Perm(); perm != 0o600 { + t.Fatalf("registry JSON mode = %04o, want 0600", perm) + } + } + rawJSON, err := os.ReadFile(jsonPath) + if err != nil { + t.Fatalf("ReadFile(%q) failed: %v", jsonPath, err) + } + if strings.Contains(string(rawJSON), "/") || strings.Contains(string(rawJSON), `\`) { + t.Fatalf("registry JSON contains a path separator: %s", rawJSON) + } + + var entry struct { + PID int `json:"pid"` + Socket string `json:"socket"` + Build string `json:"build"` + } + if err := json.Unmarshal(rawJSON, &entry); err != nil { + t.Fatalf("Unmarshal registry JSON failed: %v", err) + } + if entry.PID != os.Getpid() { + t.Fatalf("registry PID = %d, want %d", entry.PID, os.Getpid()) + } + if entry.Socket == "" || filepath.IsAbs(entry.Socket) { + t.Fatalf("registry socket = %q, want non-empty relative name", entry.Socket) + } + if strings.TrimSpace(entry.Build) == "" { + t.Fatalf("registry build is empty in %s", rawJSON) + } + + sockPath := filepath.Join(liveDir, entry.Socket) + + // 1. Dialing and sending a Join hello for the held transcript receives a welcome. + conn1, err := tr.Dial(context.Background(), sockPath) + if err != nil { + t.Fatalf("Dial(%q) for held transcript failed: %v", sockPath, err) + } + client, err := remote.Dial(conn1, "desk", remote.Hello{ + Workspace: "/work/p", + Session: heldTranscript, + Join: true, + }) + if err != nil { + _ = conn1.Close() + t.Fatalf("remote.Dial for held transcript failed: %v", err) + } + if got := client.Welcome().SessionFile; got != heldTranscript { + _ = client.Close() + t.Fatalf("Welcome().SessionFile = %q, want %q", got, heldTranscript) + } + if got := client.Agent().Title(); got != "Held Chat" { + _ = client.Close() + t.Fatalf("client.Agent().Title() = %q, want %q", got, "Held Chat") + } + _ = client.Close() + + // 2. Dialing and sending a Join hello for an unknown transcript gets a refusal + // sentence ("that conversation is not open here") and never boots one. + conn2, err := tr.Dial(context.Background(), sockPath) + if err != nil { + t.Fatalf("Dial(%q) for unknown transcript failed: %v", sockPath, err) + } + otherTranscript := filepath.Join(homeDir, "v3", "projects", "p", "chat-2", "transcript.jsonl") + badClient, err := remote.Dial(conn2, "desk", remote.Hello{ + Workspace: "/work/p", + Session: otherTranscript, + Join: true, + }) + if err == nil { + _ = badClient.Close() + t.Fatal("remote.Dial for unknown transcript succeeded, want refusal error") + } + if !strings.Contains(err.Error(), "that conversation is not open here") { + t.Fatalf("refusal error = %q, want substring %q", err.Error(), "that conversation is not open here") + } + if got := openCalls.Load(); got != 2 { + t.Fatalf("open callback called %d times, want 2", got) + } + + // 3. Close removes both the JSON file and the socket file, and a second Close is a no-op. + if err := ln.Close(); err != nil { + t.Fatalf("first Close() failed: %v", err) + } + if _, err := os.Stat(jsonPath); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("registry JSON %q still exists after Close (err=%v)", jsonPath, err) + } + if _, err := os.Stat(sockPath); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("socket file %q still exists after Close (err=%v)", sockPath, err) + } + if err := ln.Close(); err != nil { + t.Fatalf("second Close() failed: %v", err) + } +} + +// TestCloseChatEndsEveryViewerOfThatChatAndNoOtherAndHoldsUnderASymlinkedSpelling +// verifies the phase-1 completion of lane C: when a holder lets one chat go, +// every connection that opened THAT chat ends (a viewer reads it as the holder +// having gone) and a connection to any other chat of the same holder is left +// alone, whichever spelling of the path either side used. +func TestCloseChatEndsEveryViewerOfThatChatAndNoOtherAndHoldsUnderASymlinkedSpelling(t *testing.T) { + homeDir := shortTempDir(t) + physical := filepath.Join(homeDir, "physical") + if err := os.MkdirAll(physical, 0o700); err != nil { + t.Fatal(err) + } + linked := filepath.Join(homeDir, "linked") + if err := os.Symlink(physical, linked); err != nil { + t.Skipf("symlinks are not available here: %v", err) + } + chatA := filepath.Join(physical, "a.jsonl") + chatB := filepath.Join(physical, "b.jsonl") + held := func(file string) *remote.Session { + sess := remote.NewSession(&remote.Engine{Agent: &minimalWrappedAgent{title: file}, Workspace: "/work/p", SessionFile: file}, true) + t.Cleanup(func() { _ = sess.Close() }) + return sess + } + sessions := map[string]*remote.Session{chatKey(chatA): held(chatA), chatKey(chatB): held(chatB)} + + tr := UnixTransport() + ln, err := Listen(homeDir, func(transcript string) (*remote.Session, bool) { + sess, ok := sessions[chatKey(transcript)] + return sess, ok + }, tr) + if err != nil { + t.Fatalf("Listen failed: %v", err) + } + t.Cleanup(func() { _ = ln.Close() }) + sock := filepath.Join(homeDir, "v3", "live", strconv.Itoa(os.Getpid())+".sock") + + view := func(file string) *remote.Client { + t.Helper() + conn, err := tr.Dial(context.Background(), sock) + if err != nil { + t.Fatalf("Dial: %v", err) + } + client, err := remote.Dial(conn, "laptop", remote.Hello{Workspace: "/work/p", Session: file, Join: true}) + if err != nil { + _ = conn.Close() + t.Fatalf("remote.Dial %s: %v", file, err) + } + t.Cleanup(func() { _ = client.Close() }) + return client + } + // Two viewers of chat A and one of chat B. The viewers name the chat the way + // the session runs it; it is the HOLDER'S call that is spelled through the + // symlink below, because a holder may know its chat by another spelling than + // the one a viewer's hello carried. + a1 := view(chatA) + a2 := view(chatA) + b := view(chatB) + + if n := ln.CloseChat(filepath.Join(linked, "a.jsonl")); n != 2 { + t.Fatalf("CloseChat ended %d connections, want the 2 viewers of that chat", n) + } + for name, client := range map[string]*remote.Client{"first viewer of A": a1, "second viewer of A": a2} { + deadline := time.Now().Add(5 * time.Second) + for client.Err() == nil && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if client.Err() == nil { + t.Fatalf("%s was still connected after its chat was closed", name) + } + } + if err := b.Err(); err != nil { + t.Fatalf("a viewer of another chat was ended with the first: %v", err) + } + if _, err := b.Ping(); err != nil { + t.Fatalf("the other chat's viewer cannot call: %v", err) + } + if n := ln.CloseChat(filepath.Join(physical, "unknown.jsonl")); n != 0 { + t.Fatalf("CloseChat of a chat nobody opened ended %d connections", n) + } + if n := ln.CloseChat(""); n != 0 { + t.Fatalf("CloseChat of nothing ended %d connections", n) + } +} + +// TestCloseAllChatsEndsTheViewersOfEveryChatAndLeavesTheListenerServing is what +// turning remote control off asks of the listener: every viewer of every chat +// ends, and the listener is still there to refuse a new one itself. +func TestCloseAllChatsEndsTheViewersOfEveryChatAndLeavesTheListenerServing(t *testing.T) { + homeDir := shortTempDir(t) + chats := []string{filepath.Join(homeDir, "a.jsonl"), filepath.Join(homeDir, "b.jsonl")} + sessions := map[string]*remote.Session{} + for _, file := range chats { + sess := remote.NewSession(&remote.Engine{Agent: &minimalWrappedAgent{title: file}, Workspace: "/work/p", SessionFile: file}, true) + t.Cleanup(func() { _ = sess.Close() }) + sessions[chatKey(file)] = sess + } + tr := UnixTransport() + ln, err := Listen(homeDir, func(transcript string) (*remote.Session, bool) { + sess, ok := sessions[chatKey(transcript)] + return sess, ok + }, tr) + if err != nil { + t.Fatalf("Listen failed: %v", err) + } + t.Cleanup(func() { _ = ln.Close() }) + sock := filepath.Join(homeDir, "v3", "live", strconv.Itoa(os.Getpid())+".sock") + var viewers []*remote.Client + for _, file := range chats { + conn, err := tr.Dial(context.Background(), sock) + if err != nil { + t.Fatalf("Dial: %v", err) + } + client, err := remote.Dial(conn, "laptop", remote.Hello{Workspace: "/work/p", Session: file, Join: true}) + if err != nil { + _ = conn.Close() + t.Fatalf("remote.Dial %s: %v", file, err) + } + t.Cleanup(func() { _ = client.Close() }) + viewers = append(viewers, client) + } + + if n := ln.CloseAllChats(); n != len(chats) { + t.Fatalf("CloseAllChats ended %d connections, want the %d viewers", n, len(chats)) + } + for i, client := range viewers { + deadline := time.Now().Add(5 * time.Second) + for client.Err() == nil && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + if client.Err() == nil { + t.Fatalf("viewer %d was still connected after every chat was closed", i) + } + } + if n := ln.CloseAllChats(); n != 0 { + t.Fatalf("a second CloseAllChats ended %d connections, want none left", n) + } + conn, err := tr.Dial(context.Background(), sock) + if err != nil { + t.Fatalf("the listener stopped serving after CloseAllChats: %v", err) + } + _ = conn.Close() +} + +// minimalWrappedAgent is the smallest implementation of remote.WrappedAgent +// needed to back a real remote.Session in package livedoor's tests. +type minimalWrappedAgent struct { + title string +} + +func (m *minimalWrappedAgent) Submit(context.Context, string) (<-chan session.Event, error) { + ch := make(chan session.Event) + close(ch) + return ch, nil +} + +func (m *minimalWrappedAgent) SubmitImage(context.Context, string, []session.Image) (<-chan session.Event, error) { + ch := make(chan session.Event) + close(ch) + return ch, nil +} + +func (m *minimalWrappedAgent) FollowUp(string) (<-chan session.Event, error) { + ch := make(chan session.Event) + close(ch) + return ch, nil +} + +func (m *minimalWrappedAgent) Steer(string) (<-chan session.Event, error) { + ch := make(chan session.Event) + close(ch) + return ch, nil +} + +func (m *minimalWrappedAgent) Interrupt() {} +func (m *minimalWrappedAgent) InterruptFor(session.StopDoor) {} +func (m *minimalWrappedAgent) Compact(context.Context) error { return nil } +func (m *minimalWrappedAgent) Close() error { return nil } +func (m *minimalWrappedAgent) Model() string { return "stub-model" } +func (m *minimalWrappedAgent) SetModel(string) {} +func (m *minimalWrappedAgent) SetContextWindow(int) {} +func (m *minimalWrappedAgent) ReasoningFor(string) string { return "" } +func (m *minimalWrappedAgent) ReasoningLevels() map[string]string { + return nil +} +func (m *minimalWrappedAgent) SetReasoningFor(string, string) {} +func (m *minimalWrappedAgent) ResolveConsent(uint64, bool) {} +func (m *minimalWrappedAgent) ResolveConsentRemember(uint64, bool, session.ConsentScope) {} +func (m *minimalWrappedAgent) ResolveHarness(uint64, bool, string) {} +func (m *minimalWrappedAgent) ResolveConnect(string, bool) {} +func (m *minimalWrappedAgent) ResolveConnectKey(string, string) {} +func (m *minimalWrappedAgent) NoteConnected(string, string) {} +func (m *minimalWrappedAgent) Title() string { return m.title } +func (m *minimalWrappedAgent) Usage() session.Usage { return session.Usage{} } +func (m *minimalWrappedAgent) ContextTokens() int { return 0 } +func (m *minimalWrappedAgent) Transcript() []session.DisplayEntry { return nil } +func (m *minimalWrappedAgent) EarlierHistory() session.EarlierHistory { + return session.EarlierHistory{} +} +func (m *minimalWrappedAgent) RewindPoints() []session.RewindPoint { return nil } +func (m *minimalWrappedAgent) RewindAt(int) ([]session.DisplayEntry, error) { return nil, nil } diff --git a/internal/livedoor/mux.go b/internal/livedoor/mux.go new file mode 100644 index 0000000000..ed186bb784 --- /dev/null +++ b/internal/livedoor/mux.go @@ -0,0 +1,1273 @@ +package livedoor + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" +) + +// Role distinguishes the viewer that dials and opens odd-numbered channels from +// the host that accepts them. +type Role int + +const ( + Viewer Role = iota + Host +) + +// ErrLinkClosed reports that the underlying multiplexer link has been closed. +var ErrLinkClosed = errors.New("livedoor: link closed") + +// ErrProtocol reports that the peer violated the multiplexer wire contract. +var ErrProtocol = errors.New("livedoor: protocol error") + +// ErrSignalTooLarge reports a signalling payload over SignalMax, which the +// sender refuses to send and the receiver refuses to read. +var ErrSignalTooLarge = fmt.Errorf("%w: signal over SignalMax", ErrProtocol) + +// ErrTooManySignals reports that a link carried more than SignalRate signalling +// frames in a minute. The sender refuses to send the one that would be over, and +// a receiver closes the link on it. +var ErrTooManySignals = fmt.Errorf("%w: too many signalling frames", ErrProtocol) + +// ErrInvalidRole reports that an operation belongs to the opposite mux role. +var ErrInvalidRole = errors.New("livedoor: operation not valid for role") + +// RefusedError is returned by Open when the host or local channel cap refuses +// a channel request with a closed-vocabulary reason. +type RefusedError struct { + Reason string +} + +func (e *RefusedError) Error() string { + return "livedoor: channel refused: " + e.Reason +} + +// ChannelError is returned by Channel Read or Write when a channel ends with a +// remote or local reset or reason-bearing close. +type ChannelError struct { + Op string + Why string + Err error +} + +func (e *ChannelError) Error() string { + if e.Why == "" { + return "livedoor: channel " + e.Op + } + return "livedoor: channel " + e.Op + ": " + e.Why +} + +// Reason returns the closed-enum reason string that ended the channel. +func (e *ChannelError) Reason() string { + return e.Why +} + +// PlannedRedial reports whether the channel ended on purpose for an immediate +// viewer road switch so remote.Roam skips its initial redial pause. +func (e *ChannelError) PlannedRedial() bool { + return e != nil && e.Why == ReasonRoadChange +} + +// EndsView reports that the host ended this view on purpose and said why, so +// that dialling it again cannot change anything: remote.Roam buries a client +// whose link ended this way and says the host's sentence, where an ordinary +// drop is redialled for the whole of its window. The set is closed and has one +// member, because every other reason either has a redial that works (a quiet +// spell, a lagging view, a changed permit) or already stops one (a removal, +// which the link refuses on every dial). +func (e *ChannelError) EndsView() bool { + return e != nil && e.Why == ReasonRemoteControlOff +} + +func (e *ChannelError) Unwrap() error { + return e.Err +} + +// OpenRequest is the payload carried by OpOpen on a newly opened channel. +type OpenRequest struct { + Chat string `json:"chat"` + V int `json:"v"` +} + +// HelloAck is the payload carried by OpHelloAck on channel 0 after the +// host checks the viewer's permit. +type HelloAck struct { + V int `json:"v"` + Watch bool `json:"watch"` + Drive bool `json:"drive"` + Road string `json:"road"` + Limits Limits `json:"limits"` + // Direct says the host will take an offer for a direct road on this link: + // its remote control is on, its road is not forced to the relay, and it has + // room for another direct tunnel. ADDITIVE: an older host never sets it and + // an older viewer ignores it, so nobody offers to a host that cannot answer. + Direct bool `json:"direct,omitempty"` + // Off says that Watch is false BECAUSE the person turned remote control off on + // the host, not because this computer's permit has no watching in it. It is + // what a refused dial can say, since a refusal that never opened a channel + // has no channel reset to carry [ReasonRemoteControlOff]. ADDITIVE for the + // same reason Direct is: an older host never sets it, and an older viewer + // ignores it and reads the Watch that is false as it always did. + Off bool `json:"off,omitempty"` +} + +// MuxConfig configures a Mux over an io.ReadWriteCloser. +type MuxConfig struct { + Clock Clock + Limits Limits + OnPong func(seq uint32) + // OnSignal is handed each signalling payload that arrives, in order. It runs + // on the link's reader goroutine, so it must not block; a handler that has + // work to do queues it. + OnSignal func(payload []byte) + OnFrameWritten func(n int) + OnFrameRead func(n int) +} + +type acceptItem struct { + ch *Channel + req OpenRequest +} + +type outChunk struct { + data []byte + done chan error +} + +// Mux multiplexes flow-controlled channels over a single io.ReadWriteCloser. +type Mux struct { + rwc io.ReadWriteCloser + role Role + cfg MuxConfig + clock Clock + limits Limits + + mu sync.Mutex + cond *sync.Cond + closed bool + closeErr error + nextChanID uint32 + channels map[uint32]*Channel + channelOrder []uint32 + rrIndex int + ctrlQueue []frame + linkSendCredit int + linkRecvAllowance int + linkUnreturnedBytes int + totalBufferedBytes int + + tokens float64 + lastRefill time.Time + + // signalsIn and signalsOut are the times of the signalling frames this link + // received and sent in the last minute, kept to hold both to SignalRate. + signalsIn []time.Time + signalsOut []time.Time + + helloAck HelloAck + hasHelloAck bool + helloAckOnce sync.Once + helloAckCh chan struct{} + + acceptCh chan acceptItem + writeWake chan struct{} + done chan struct{} + closeOnce sync.Once +} + +// NewMux starts the reader and writer goroutines over rwc under guard.Go. +func NewMux(rwc io.ReadWriteCloser, role Role, cfg MuxConfig) *Mux { + clk := cfg.Clock + if clk == nil { + clk = RealClock() + } + lim := cfg.Limits.withDefaults() + m := &Mux{ + rwc: rwc, + role: role, + cfg: cfg, + clock: clk, + limits: lim, + channels: make(map[uint32]*Channel), + linkSendCredit: lim.LinkWindow, + linkRecvAllowance: lim.LinkWindow, + tokens: float64(lim.RateBurst), + lastRefill: clk.Now(), + helloAckCh: make(chan struct{}), + acceptCh: make(chan acceptItem, lim.MaxChannelsPerLink), + writeWake: make(chan struct{}, 1), + done: make(chan struct{}), + } + m.cond = sync.NewCond(&m.mu) + guard.Go("livedoor.mux.reader", m.readerLoop) + guard.Go("livedoor.mux.writer", m.writerLoop) + return m +} + +// Done returns a channel that closes when the multiplexer link closes. +func (m *Mux) Done() <-chan struct{} { + return m.done +} + +// Close closes the multiplexer and underlying transport once, waking every +// blocked Read, Write, Open, Accept, and WaitHelloAck. +func (m *Mux) Close() error { + return m.shutdown(ErrLinkClosed) +} + +func (m *Mux) fail(err error) { + if err == nil { + err = ErrProtocol + } + _ = m.shutdown(err) +} + +func (m *Mux) shutdown(cause error) error { + var rwcErr error + m.closeOnce.Do(func() { + m.mu.Lock() + m.closed = true + if m.closeErr == nil { + m.closeErr = cause + } + for _, ch := range m.channels { + ch.failLocked(ErrLinkClosed) + } + m.cond.Broadcast() + m.mu.Unlock() + + close(m.done) + m.wakeWriter() + rwcErr = m.rwc.Close() + }) + return rwcErr +} + +func (m *Mux) wakeWriter() { + select { + case m.writeWake <- struct{}{}: + default: + } +} + +func (m *Mux) enqueueControlLocked(f frame) { + if m.closed { + return + } + m.ctrlQueue = append(m.ctrlQueue, f) + m.wakeWriter() +} + +func (m *Mux) removeChannelLocked(ch *Channel) { + if _, ok := m.channels[ch.id]; !ok { + return + } + delete(m.channels, ch.id) + for i, id := range m.channelOrder { + if id == ch.id { + m.channelOrder = append(m.channelOrder[:i], m.channelOrder[i+1:]...) + if m.rrIndex > i { + m.rrIndex-- + } + break + } + } + // Release any unread bytes that had already deducted from the link receive + // allowance so closing or resetting a channel never leaks link credit. + bufLen := len(ch.readBuf) + unread := bufLen + ch.unreturnedBytes + ch.readBuf = nil + ch.unreturnedBytes = 0 + if unread > 0 { + m.totalBufferedBytes -= bufLen + if m.totalBufferedBytes < 0 { + m.totalBufferedBytes = 0 + } + m.linkUnreturnedBytes += unread + m.maybeSendLinkCreditLocked() + } + // Refund any unsent data chunks that had reserved link send credit. + for _, chunk := range ch.outQueue { + m.linkSendCredit += len(chunk.data) + if chunk.done != nil { + chunk.done <- ch.writeErrLocked() + close(chunk.done) + } + } + ch.outQueue = nil + m.cond.Broadcast() +} + +func (m *Mux) maybeSendLinkCreditLocked() { + if m.closed || m.linkUnreturnedBytes <= 0 { + return + } + if m.linkUnreturnedBytes >= m.limits.LinkWindow/4 || m.totalBufferedBytes == 0 { + grant := m.linkUnreturnedBytes + m.linkUnreturnedBytes = 0 + m.linkRecvAllowance += grant + m.enqueueControlLocked(frame{ + op: OpCredit, + channel: 0, + payload: encodeUint32(uint32(grant)), + }) + } +} + +// Open opens a new odd-numbered channel from the viewer side and waits for the +// host to reply with OpOpened or OpRefused. +func (m *Mux) Open(ctx context.Context, chat string) (*Channel, error) { + if m.role != Viewer { + return nil, ErrInvalidRole + } + m.mu.Lock() + if m.closed { + m.mu.Unlock() + return nil, ErrLinkClosed + } + if len(m.channels) >= m.limits.MaxChannelsPerLink { + m.mu.Unlock() + return nil, &RefusedError{Reason: ReasonTooMany} + } + if m.nextChanID == 0 { + m.nextChanID = 1 + } else { + m.nextChanID += 2 + } + id := m.nextChanID + ch := newChannel(m, id) + m.channels[id] = ch + m.channelOrder = append(m.channelOrder, id) + + payload, err := json.Marshal(OpenRequest{Chat: chat, V: 1}) + if err != nil { + delete(m.channels, id) + m.mu.Unlock() + return nil, err + } + m.enqueueControlLocked(frame{ + op: OpOpen, + channel: id, + payload: payload, + }) + m.mu.Unlock() + + select { + case <-ch.openedCh: + m.mu.Lock() + refused := ch.refused + reason := ch.reason + closed := m.closed + m.mu.Unlock() + if refused { + return nil, &RefusedError{Reason: reason} + } + if closed { + return nil, ErrLinkClosed + } + return ch, nil + case <-m.done: + m.mu.Lock() + refused, reason := ch.refused, ch.reason + m.mu.Unlock() + if refused { + return nil, &RefusedError{Reason: reason} + } + return nil, ErrLinkClosed + case <-ctx.Done(): + m.mu.Lock() + if !ch.opened && !ch.ended { + ch.ended = true + ch.closeDone() + m.removeChannelLocked(ch) + m.enqueueControlLocked(frame{ + op: OpClose, + channel: id, + }) + } + m.mu.Unlock() + return nil, ctx.Err() + } +} + +// Accept waits on the host side for the next incoming channel open request. +// The caller must then call ch.Accept() or ch.Refuse(reason). +func (m *Mux) Accept(ctx context.Context) (*Channel, OpenRequest, error) { + if m.role != Host { + return nil, OpenRequest{}, ErrInvalidRole + } + select { + case item := <-m.acceptCh: + return item.ch, item.req, nil + case <-m.done: + return nil, OpenRequest{}, ErrLinkClosed + case <-ctx.Done(): + return nil, OpenRequest{}, ctx.Err() + } +} + +// SendPing sends an OpPing frame on channel 0 with seq. +func (m *Mux) SendPing(seq uint32) error { + m.mu.Lock() + defer m.mu.Unlock() + if m.closed { + return ErrLinkClosed + } + m.enqueueControlLocked(frame{ + op: OpPing, + channel: 0, + payload: encodeUint32(seq), + }) + return nil +} + +// SendSignal sends one signalling payload as an OpSignal frame on channel 0. It +// refuses a payload over SignalMax and refuses to send more than SignalRate +// frames in a minute, because the far end closes a link that does either. +func (m *Mux) SendSignal(payload []byte) error { + if len(payload) > SignalMax { + return ErrSignalTooLarge + } + m.mu.Lock() + defer m.mu.Unlock() + if m.closed { + return ErrLinkClosed + } + if !m.noteSignalLocked(&m.signalsOut) { + return ErrTooManySignals + } + m.enqueueControlLocked(frame{ + op: OpSignal, + channel: 0, + payload: append([]byte(nil), payload...), + }) + return nil +} + +// noteSignalLocked records one signalling frame against the per-minute rate and +// reports whether it is within it. +func (m *Mux) noteSignalLocked(window *[]time.Time) bool { + now := m.clock.Now() + kept := (*window)[:0] + for _, at := range *window { + if now.Sub(at) < time.Minute { + kept = append(kept, at) + } + } + *window = kept + if len(*window) >= SignalRate { + return false + } + *window = append(*window, now) + return true +} + +// SendHelloAck sends an OpHelloAck frame on channel 0 from the host. +func (m *Mux) SendHelloAck(ack HelloAck) error { + if m.role != Host { + return ErrInvalidRole + } + if ack.V == 0 { + ack.V = 1 + } + payload, err := json.Marshal(ack) + if err != nil { + return err + } + m.mu.Lock() + defer m.mu.Unlock() + if m.closed { + return ErrLinkClosed + } + m.enqueueControlLocked(frame{ + op: OpHelloAck, + channel: 0, + payload: payload, + }) + return nil +} + +// HelloAck returns the received HelloAck if one has arrived on the link. +func (m *Mux) HelloAck() (HelloAck, bool) { + m.mu.Lock() + defer m.mu.Unlock() + return m.helloAck, m.hasHelloAck +} + +// WaitHelloAck waits until an OpHelloAck frame arrives, the context is cancelled, +// or the link closes. +func (m *Mux) WaitHelloAck(ctx context.Context) (HelloAck, error) { + select { + case <-m.helloAckCh: + m.mu.Lock() + ack := m.helloAck + m.mu.Unlock() + return ack, nil + case <-m.done: + m.mu.Lock() + ack, ok := m.helloAck, m.hasHelloAck + m.mu.Unlock() + if ok { + return ack, nil + } + return HelloAck{}, ErrLinkClosed + case <-ctx.Done(): + return HelloAck{}, ctx.Err() + } +} + +func (m *Mux) readerLoop() { + for { + f, err := readFrame(m.rwc, m.limits.ChunkBytes, m.cfg.OnFrameRead) + if err != nil { + m.fail(err) + return + } + if err := m.handleFrame(f); err != nil { + m.fail(err) + return + } + } +} + +func (m *Mux) handleFrame(f frame) error { + switch f.op { + case OpOpen: + if m.role != Host || f.channel == 0 || f.channel%2 == 0 { + return ErrProtocol + } + var req OpenRequest + if err := json.Unmarshal(f.payload, &req); err != nil { + return ErrProtocol + } + m.mu.Lock() + if m.closed { + m.mu.Unlock() + return nil + } + if _, exists := m.channels[f.channel]; exists { + m.mu.Unlock() + return ErrProtocol + } + if len(m.channels) >= m.limits.MaxChannelsPerLink { + m.enqueueControlLocked(frame{ + op: OpRefused, + channel: f.channel, + payload: []byte(ReasonTooMany), + }) + m.mu.Unlock() + return nil + } + ch := newChannel(m, f.channel) + ch.pendingAccept = true + m.channels[f.channel] = ch + m.channelOrder = append(m.channelOrder, f.channel) + m.mu.Unlock() + + select { + case m.acceptCh <- acceptItem{ch: ch, req: req}: + case <-m.done: + } + return nil + + case OpOpened: + if m.role != Viewer || f.channel == 0 { + return ErrProtocol + } + m.mu.Lock() + ch, ok := m.channels[f.channel] + if !ok || ch.opened { + m.mu.Unlock() + return ErrProtocol + } + ch.opened = true + ch.signalOpened() + m.mu.Unlock() + return nil + + case OpRefused: + if m.role != Viewer || f.channel == 0 { + return ErrProtocol + } + reason := string(f.payload) + m.mu.Lock() + ch, ok := m.channels[f.channel] + if !ok || ch.opened { + m.mu.Unlock() + return ErrProtocol + } + ch.refused = true + ch.ended = true + ch.reason = reason + ch.closeDone() + m.removeChannelLocked(ch) + ch.signalOpened() + m.mu.Unlock() + return nil + + case OpData: + if f.channel == 0 { + return ErrProtocol + } + n := len(f.payload) + m.mu.Lock() + if n > m.linkRecvAllowance { + m.mu.Unlock() + return fmt.Errorf("%w: link credit overrun (%d > %d)", ErrProtocol, n, m.linkRecvAllowance) + } + ch, ok := m.channels[f.channel] + if !ok { + // If the channel ID was never valid or never opened, fail the link; + // if it was recently closed locally while data was in flight, return + // the link credit so the remaining channels do not lose link window. + if f.channel%2 == 0 || (m.role == Viewer && f.channel > m.nextChanID) { + m.mu.Unlock() + return ErrProtocol + } + m.linkRecvAllowance -= n + m.linkUnreturnedBytes += n + m.maybeSendLinkCreditLocked() + m.mu.Unlock() + return nil + } + if n > ch.recvAllowance { + m.mu.Unlock() + return fmt.Errorf("%w: channel %d credit overrun (%d > %d)", ErrProtocol, f.channel, n, ch.recvAllowance) + } + ch.recvAllowance -= n + m.linkRecvAllowance -= n + if ch.ended { + m.linkUnreturnedBytes += n + m.maybeSendLinkCreditLocked() + m.mu.Unlock() + return nil + } + ch.readBuf = append(ch.readBuf, f.payload...) + m.totalBufferedBytes += n + m.cond.Broadcast() + m.mu.Unlock() + return nil + + case OpCredit: + inc, ok := decodeUint32(f.payload) + if !ok { + return ErrProtocol + } + m.mu.Lock() + if f.channel == 0 { + m.linkSendCredit += int(inc) + } else { + if ch, exists := m.channels[f.channel]; exists { + ch.sendCredit += int(inc) + } + } + m.cond.Broadcast() + m.mu.Unlock() + return nil + + case OpClose: + if f.channel == 0 { + return ErrProtocol + } + reason := string(f.payload) + m.mu.Lock() + if ch, ok := m.channels[f.channel]; ok { + if !ch.ended { + ch.ended = true + ch.reason = reason + } + ch.remoteClosed = true + ch.closeDone() + // Free any pending outbound chunks, and remove the channel once its + // read buffer has been drained. + for _, chunk := range ch.outQueue { + m.linkSendCredit += len(chunk.data) + if chunk.done != nil { + chunk.done <- ch.writeErrLocked() + close(chunk.done) + } + } + ch.outQueue = nil + if len(ch.readBuf) == 0 { + m.removeChannelLocked(ch) + } + m.cond.Broadcast() + } + m.mu.Unlock() + return nil + + case OpReset: + if f.channel == 0 { + return ErrProtocol + } + reason := string(f.payload) + m.mu.Lock() + if ch, ok := m.channels[f.channel]; ok { + ch.ended = true + ch.remoteReset = true + ch.reason = reason + ch.closeDone() + m.removeChannelLocked(ch) + m.cond.Broadcast() + } + m.mu.Unlock() + return nil + + case OpPing: + seq, ok := decodeUint32(f.payload) + if !ok || f.channel != 0 { + return ErrProtocol + } + m.mu.Lock() + m.enqueueControlLocked(frame{ + op: OpPong, + channel: 0, + payload: encodeUint32(seq), + }) + m.mu.Unlock() + return nil + + case OpPong: + seq, ok := decodeUint32(f.payload) + if !ok || f.channel != 0 { + return ErrProtocol + } + if m.cfg.OnPong != nil { + m.cfg.OnPong(seq) + } + return nil + + case OpSignal: + if f.channel != 0 || len(f.payload) > SignalMax { + return ErrProtocol + } + m.mu.Lock() + within := m.noteSignalLocked(&m.signalsIn) + m.mu.Unlock() + if !within { + return ErrTooManySignals + } + if m.cfg.OnSignal != nil { + m.cfg.OnSignal(f.payload) + } + return nil + + case OpHelloAck: + if f.channel != 0 { + return ErrProtocol + } + var ack HelloAck + if err := json.Unmarshal(f.payload, &ack); err != nil { + return ErrProtocol + } + m.mu.Lock() + m.helloAck = ack + m.hasHelloAck = true + m.mu.Unlock() + m.helloAckOnce.Do(func() { + close(m.helloAckCh) + }) + return nil + } + return nil +} + +func (m *Mux) refillTokensLocked() { + now := m.clock.Now() + elapsed := now.Sub(m.lastRefill) + if elapsed > 0 { + m.tokens += elapsed.Seconds() * float64(m.limits.Rate) + if m.tokens > float64(m.limits.RateBurst) { + m.tokens = float64(m.limits.RateBurst) + } + m.lastRefill = now + } +} + +func (m *Mux) peekNextDataBytesLocked() int { + n := len(m.channelOrder) + if n == 0 { + return 0 + } + if m.rrIndex >= n || m.rrIndex < 0 { + m.rrIndex = 0 + } + for i := 0; i < n; i++ { + idx := (m.rrIndex + i) % n + id := m.channelOrder[idx] + ch := m.channels[id] + if ch != nil && len(ch.outQueue) > 0 { + return len(ch.outQueue[0].data) + } + } + return 0 +} + +func (m *Mux) popNextDataChunkLocked() (uint32, *outChunk, bool) { + n := len(m.channelOrder) + if n == 0 { + return 0, nil, false + } + if m.rrIndex >= n || m.rrIndex < 0 { + m.rrIndex = 0 + } + for i := 0; i < n; i++ { + idx := (m.rrIndex + i) % n + id := m.channelOrder[idx] + ch := m.channels[id] + if ch != nil && len(ch.outQueue) > 0 { + chunk := ch.outQueue[0] + ch.outQueue = ch.outQueue[1:] + m.rrIndex = (idx + 1) % n + return id, chunk, true + } + } + return 0, nil, false +} + +func (m *Mux) writerLoop() { + var paceTimer Timer + stopPaceTimer := func() { + if paceTimer != nil { + paceTimer.Stop() + paceTimer = nil + } + } + defer stopPaceTimer() + + for { + m.mu.Lock() + if m.closed { + m.mu.Unlock() + return + } + + // Control frames always jump ahead of queued data frames and are never + // delayed by the data token bucket. + if len(m.ctrlQueue) > 0 { + f := m.ctrlQueue[0] + m.ctrlQueue = m.ctrlQueue[1:] + m.mu.Unlock() + + n, err := writeFrame(m.rwc, f, m.limits.ChunkBytes) + if err != nil { + m.fail(err) + return + } + if m.cfg.OnFrameWritten != nil { + m.cfg.OnFrameWritten(n) + } + continue + } + + need := m.peekNextDataBytesLocked() + if need > 0 { + m.refillTokensLocked() + if m.tokens >= float64(need) { + stopPaceTimer() + chID, chunk, ok := m.popNextDataChunkLocked() + if ok { + m.tokens -= float64(len(chunk.data)) + m.mu.Unlock() + + n, err := writeFrame(m.rwc, frame{ + op: OpData, + channel: chID, + payload: chunk.data, + }, m.limits.ChunkBytes) + if chunk.done != nil { + chunk.done <- err + close(chunk.done) + } + if err != nil { + m.fail(err) + return + } + if m.cfg.OnFrameWritten != nil { + m.cfg.OnFrameWritten(n) + } + continue + } + } + + // Not enough tokens for the next queued data chunk; start a pacing + // timer on Clock if one is not already running. + if paceTimer == nil { + deficit := float64(need) - m.tokens + wait := time.Duration(math.Ceil(deficit / float64(m.limits.Rate) * float64(time.Second))) + if wait < time.Nanosecond { + wait = time.Nanosecond + } + paceTimer = m.clock.NewTimer(wait) + } + timerC := paceTimer.C() + m.mu.Unlock() + + select { + case <-timerC: + stopPaceTimer() + case <-m.writeWake: + case <-m.done: + return + } + continue + } + + stopPaceTimer() + m.mu.Unlock() + + select { + case <-m.writeWake: + case <-m.done: + return + } + } +} + +// Channel is a single flow-controlled stream multiplexed over a Mux. +type Channel struct { + mux *Mux + id uint32 + + opened bool + refused bool + pendingAccept bool + openedOnce sync.Once + openedCh chan struct{} + + sendCredit int + recvAllowance int + unreturnedBytes int + readBuf []byte + outQueue []*outChunk + + ended bool + remoteClosed bool + remoteReset bool + failErr error + reason string + + doneOnce sync.Once + done chan struct{} +} + +func newChannel(m *Mux, id uint32) *Channel { + return &Channel{ + mux: m, + id: id, + openedCh: make(chan struct{}), + sendCredit: m.limits.ChannelWindow, + recvAllowance: m.limits.ChannelWindow, + done: make(chan struct{}), + } +} + +func (c *Channel) signalOpened() { + c.openedOnce.Do(func() { + close(c.openedCh) + }) +} + +func (c *Channel) closeDone() { + c.doneOnce.Do(func() { + close(c.done) + }) +} + +func (c *Channel) failLocked(err error) { + if !c.ended { + c.ended = true + } + if c.failErr == nil { + c.failErr = err + } + for _, chunk := range c.outQueue { + if chunk.done != nil { + chunk.done <- err + close(chunk.done) + } + } + c.outQueue = nil + c.closeDone() + c.signalOpened() +} + +// ID returns the channel's odd wire identifier. +func (c *Channel) ID() uint32 { + return c.id +} + +// Done returns a channel that closes when the channel ends for any reason. +func (c *Channel) Done() <-chan struct{} { + return c.done +} + +// Reason returns the closed-enum reason string that ended the channel, or "" +// for a clean local Close. +func (c *Channel) Reason() string { + c.mux.mu.Lock() + defer c.mux.mu.Unlock() + return c.reason +} + +// Accept confirms a pending host channel returned by Mux.Accept and sends +// OpOpened to the viewer. +func (c *Channel) Accept() error { + m := c.mux + m.mu.Lock() + defer m.mu.Unlock() + if m.closed { + return ErrLinkClosed + } + if !c.pendingAccept { + return ErrProtocol + } + c.pendingAccept = false + c.opened = true + m.enqueueControlLocked(frame{ + op: OpOpened, + channel: c.id, + }) + return nil +} + +// Refuse rejects a pending host channel returned by Mux.Accept and sends +// OpRefused with reason to the viewer. +func (c *Channel) Refuse(reason string) error { + m := c.mux + m.mu.Lock() + defer m.mu.Unlock() + if m.closed { + return ErrLinkClosed + } + if !c.pendingAccept { + return ErrProtocol + } + c.pendingAccept = false + c.ended = true + c.reason = reason + c.closeDone() + m.removeChannelLocked(c) + m.enqueueControlLocked(frame{ + op: OpRefused, + channel: c.id, + payload: []byte(reason), + }) + return nil +} + +// Read reads buffered data from the channel and grants channel and link credit +// back to the peer when unreturned consumed bytes reach a quarter window or the +// read buffer drains empty. +func (c *Channel) Read(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + m := c.mux + m.mu.Lock() + for len(c.readBuf) == 0 { + if c.remoteReset { + reason := c.reason + m.mu.Unlock() + return 0, &ChannelError{Op: "reset", Why: reason} + } + if c.remoteClosed { + reason := c.reason + m.removeChannelLocked(c) + m.mu.Unlock() + if reason != "" { + return 0, &ChannelError{Op: "close", Why: reason, Err: io.EOF} + } + return 0, io.EOF + } + if m.closed || c.failErr != nil { + m.mu.Unlock() + return 0, ErrLinkClosed + } + if c.ended { + reason := c.reason + m.mu.Unlock() + if reason != "" { + return 0, &ChannelError{Op: "close", Why: reason, Err: io.EOF} + } + return 0, io.EOF + } + m.cond.Wait() + } + + if c.remoteReset { + reason := c.reason + m.mu.Unlock() + return 0, &ChannelError{Op: "reset", Why: reason} + } + + n := copy(p, c.readBuf) + c.readBuf = c.readBuf[n:] + if len(c.readBuf) == 0 { + c.readBuf = nil + } + m.totalBufferedBytes -= n + if m.totalBufferedBytes < 0 { + m.totalBufferedBytes = 0 + } + + if !m.closed && !c.ended { + c.unreturnedBytes += n + if c.unreturnedBytes >= m.limits.ChannelWindow/4 || len(c.readBuf) == 0 { + grant := c.unreturnedBytes + c.unreturnedBytes = 0 + c.recvAllowance += grant + m.enqueueControlLocked(frame{ + op: OpCredit, + channel: c.id, + payload: encodeUint32(uint32(grant)), + }) + } + } + if !m.closed { + m.linkUnreturnedBytes += n + m.maybeSendLinkCreditLocked() + } + if len(c.readBuf) == 0 && c.remoteClosed { + m.removeChannelLocked(c) + } + m.mu.Unlock() + return n, nil +} + +func (c *Channel) writeErrLocked() error { + if c.remoteReset { + return &ChannelError{Op: "reset", Why: c.reason} + } + if c.mux.closed || c.failErr != nil { + return ErrLinkClosed + } + if c.reason != "" { + return &ChannelError{Op: "close", Why: c.reason, Err: io.ErrClosedPipe} + } + return io.ErrClosedPipe +} + +// Write cuts p into ChunkBytes slices, blocks while out of channel or link +// credit, and queues data frames for the round-robin writer goroutine. +func (c *Channel) Write(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + m := c.mux + total := 0 + remaining := p + var waiters []chan error + + for len(remaining) > 0 { + m.mu.Lock() + for (c.sendCredit <= 0 || m.linkSendCredit <= 0) && !c.ended && !m.closed { + m.cond.Wait() + } + if c.ended || m.closed { + err := c.writeErrLocked() + m.mu.Unlock() + for _, w := range waiters { + if wErr := <-w; wErr != nil { + return total, wErr + } + } + return total, err + } + + for len(remaining) > 0 && c.sendCredit > 0 && m.linkSendCredit > 0 { + take := len(remaining) + if take > m.limits.ChunkBytes { + take = m.limits.ChunkBytes + } + if take > c.sendCredit { + take = c.sendCredit + } + if take > m.linkSendCredit { + take = m.linkSendCredit + } + c.sendCredit -= take + m.linkSendCredit -= take + + buf := make([]byte, take) + copy(buf, remaining[:take]) + remaining = remaining[take:] + total += take + + var doneCh chan error + if len(remaining) == 0 { + doneCh = make(chan error, 1) + waiters = append(waiters, doneCh) + } + c.outQueue = append(c.outQueue, &outChunk{ + data: buf, + done: doneCh, + }) + } + m.wakeWriter() + m.mu.Unlock() + } + + for _, w := range waiters { + if err := <-w; err != nil { + return total, err + } + } + return total, nil +} + +// Close closes the channel cleanly with an empty reason. +func (c *Channel) Close() error { + return c.CloseWithReason("") +} + +// CloseWithReason closes the channel, sends OpClose with reason, and releases +// its credit state. +func (c *Channel) CloseWithReason(reason string) error { + m := c.mux + m.mu.Lock() + defer m.mu.Unlock() + if c.ended { + return nil + } + c.ended = true + c.reason = reason + c.closeDone() + m.removeChannelLocked(c) + m.enqueueControlLocked(frame{ + op: OpClose, + channel: c.id, + payload: []byte(reason), + }) + return nil +} + +// Reset aborts the channel, sends OpReset with reason, and wakes any blocked +// reader or writer immediately. +func (c *Channel) Reset(reason string) error { + m := c.mux + m.mu.Lock() + defer m.mu.Unlock() + if c.ended { + return nil + } + c.ended = true + c.remoteReset = true + c.reason = reason + c.closeDone() + m.removeChannelLocked(c) + m.enqueueControlLocked(frame{ + op: OpReset, + channel: c.id, + payload: []byte(reason), + }) + return nil +} diff --git a/internal/livedoor/mux_frame.go b/internal/livedoor/mux_frame.go new file mode 100644 index 0000000000..aaec35f5d5 --- /dev/null +++ b/internal/livedoor/mux_frame.go @@ -0,0 +1,155 @@ +package livedoor + +import ( + "encoding/binary" + "errors" + "fmt" + "io" +) + +// Wire opcodes for the live door multiplexer frame header. +const ( + OpOpen uint8 = 1 + OpOpened uint8 = 2 + OpRefused uint8 = 3 + OpData uint8 = 4 + OpCredit uint8 = 5 + OpClose uint8 = 6 + OpReset uint8 = 7 + OpPing uint8 = 8 + OpPong uint8 = 9 + OpHelloAck uint8 = 10 + + // OpSignal carries one signalling payload of the direct road on channel 0 of + // a tunnel that is already open: an offer, an answer, a candidate or a + // refusal. It is ADDITIVE BY CONSTRUCTION. A build that does not know it + // reads the frame like any unknown op, consumes its bounded payload and + // carries on, so an older host or viewer simply never takes part and the + // view stays on the relay. + OpSignal uint8 = 11 +) + +// Closed reason vocabulary carried by OpRefused, OpClose, and OpReset frames. +const ( + ReasonNotRunning = "not-running" + ReasonNotAllowed = "not-allowed" + ReasonHolderGone = "holder-gone" + ReasonHolderOld = "holder-old" + ReasonRemoved = "removed" + ReasonPermitChanged = "permit-changed" + ReasonLagging = "lagging" + ReasonFrameTooLarge = "frame-too-large" + ReasonBudget = "budget" + ReasonIdle = "idle" + ReasonHostClosing = "host-closing" + ReasonTooMany = "too-many" + + // ReasonRemoteControlOff is what a host says to every live view it closes + // because the person turned remote control off on it. It is ADDITIVE ON THE + // WIRE: reasons are opaque strings to the mux, so a build that does not know + // this one reads an ordinary channel end it has no sentence for, says a plain + // loss of connection and redials as it always did. A build that knows it ends + // the view for good, because the computer is up and answered, and redialling + // cannot change what it said. + ReasonRemoteControlOff = "remote-control-off" + + // ReasonRoadChange is the reason a viewer's own link gives a channel it ends + // on purpose so the channel's chat can be redialled over the other road. IT + // IS VIEWER-LOCAL: it is never written on a wire frame and never spoken to a + // person, so chatlist has no sentence for it and the words law lists it as + // exempt. + ReasonRoadChange = "road-change" +) + +const frameHeaderBytes = 9 + +// ErrFrameTooLarge reports that a frame payload length exceeded ChunkBytes. +var ErrFrameTooLarge = errors.New("livedoor: frame payload exceeds ChunkBytes") + +// frame is the decoded representation of one wire frame: +// op u8 | chan u32 BE | n u32 BE | payload[n]. +type frame struct { + op uint8 + channel uint32 + payload []byte +} + +func isKnownOp(op uint8) bool { + return op >= OpOpen && op <= OpSignal +} + +// writeFrame encodes f onto w in a single write and returns the total wire +// byte count written. +func writeFrame(w io.Writer, f frame, maxChunk int) (int, error) { + if maxChunk <= 0 { + maxChunk = ChunkBytes + } + if len(f.payload) > maxChunk { + return 0, fmt.Errorf("%w: %d > %d", ErrFrameTooLarge, len(f.payload), maxChunk) + } + buf := make([]byte, frameHeaderBytes+len(f.payload)) + buf[0] = f.op + binary.BigEndian.PutUint32(buf[1:5], f.channel) + binary.BigEndian.PutUint32(buf[5:9], uint32(len(f.payload))) + copy(buf[frameHeaderBytes:], f.payload) + n, err := w.Write(buf) + if err != nil { + return n, err + } + if n != len(buf) { + return n, io.ErrShortWrite + } + return n, nil +} + +// readFrame reads the next known frame from r, skipping any unknown opcode after +// consuming its bounded payload so future additive ops do not break older peers. +// If any incoming frame declares n > maxChunk, readFrame returns ErrFrameTooLarge. +func readFrame(r io.Reader, maxChunk int, onFrameRead func(n int)) (frame, error) { + if maxChunk <= 0 { + maxChunk = ChunkBytes + } + var hdr [frameHeaderBytes]byte + for { + if _, err := io.ReadFull(r, hdr[:]); err != nil { + return frame{}, err + } + op := hdr[0] + ch := binary.BigEndian.Uint32(hdr[1:5]) + n := binary.BigEndian.Uint32(hdr[5:9]) + if uint64(n) > uint64(maxChunk) { + return frame{}, fmt.Errorf("%w: %d > %d", ErrFrameTooLarge, n, maxChunk) + } + var payload []byte + if n > 0 { + payload = make([]byte, int(n)) + if _, err := io.ReadFull(r, payload); err != nil { + return frame{}, err + } + } + if onFrameRead != nil { + onFrameRead(frameHeaderBytes + int(n)) + } + if !isKnownOp(op) { + continue + } + return frame{ + op: op, + channel: ch, + payload: payload, + }, nil + } +} + +func encodeUint32(v uint32) []byte { + var b [4]byte + binary.BigEndian.PutUint32(b[:], v) + return b[:] +} + +func decodeUint32(b []byte) (uint32, bool) { + if len(b) != 4 { + return 0, false + } + return binary.BigEndian.Uint32(b), true +} diff --git a/internal/livedoor/mux_signal_test.go b/internal/livedoor/mux_signal_test.go new file mode 100644 index 0000000000..baa019eca7 --- /dev/null +++ b/internal/livedoor/mux_signal_test.go @@ -0,0 +1,193 @@ +package livedoor + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "net" + "testing" + "time" +) + +// signalInbox collects, in order, every signalling payload a mux hands to its +// OnSignal callback. +type signalInbox struct { + got chan []byte +} + +func newSignalInbox() *signalInbox { return &signalInbox{got: make(chan []byte, 256)} } + +func (s *signalInbox) take(t *testing.T) []byte { + t.Helper() + select { + case p := <-s.got: + return p + case <-time.After(5 * time.Second): + t.Fatal("no signalling payload arrived") + return nil + } +} + +func (s *signalInbox) onSignal(p []byte) { s.got <- append([]byte(nil), p...) } + +// V37: OpSignal rides channel 0 of an open link, a mux that does not know an op +// still skips it (so an older build ignores signalling), and a signal on any +// other channel is a protocol error that ends the link. +func TestAnUnknownOpIsStillSkippedAndSignalRidesChannelZero(t *testing.T) { + t.Run("the codec round-trips a signal and OpSignal is the only new known op", func(t *testing.T) { + var buf bytes.Buffer + want := frame{op: OpSignal, channel: 0, payload: []byte(`{"v":1,"t":"offer","id":"abc"}`)} + if _, err := writeFrame(&buf, want, ChunkBytes); err != nil { + t.Fatal(err) + } + got, err := readFrame(&buf, ChunkBytes, nil) + if err != nil || got.op != OpSignal || got.channel != 0 || !bytes.Equal(got.payload, want.payload) { + t.Fatalf("round trip = %+v, %v; want %+v", got, err, want) + } + if !isKnownOp(OpSignal) || isKnownOp(OpSignal+1) || isKnownOp(0) { + t.Fatal("isKnownOp does not stop exactly at OpSignal") + } + if OpSignal != 11 { + t.Fatalf("OpSignal = %d; the wire number is 11", OpSignal) + } + }) + + t.Run("an op the reader does not know is consumed and the next frame decodes", func(t *testing.T) { + var buf bytes.Buffer + payload := []byte("a future extension") + var hdr [frameHeaderBytes]byte + hdr[0] = OpSignal + 1 + binary.BigEndian.PutUint32(hdr[5:9], uint32(len(payload))) + buf.Write(hdr[:]) + buf.Write(payload) + next := frame{op: OpPing, channel: 0, payload: encodeUint32(7)} + if _, err := writeFrame(&buf, next, ChunkBytes); err != nil { + t.Fatal(err) + } + got, err := readFrame(&buf, ChunkBytes, nil) + if err != nil || got.op != OpPing { + t.Fatalf("the frame after an unknown op = %+v, %v; want the ping", got, err) + } + }) + + t.Run("signals arrive in order in both directions", func(t *testing.T) { + viewerInbox, hostInbox := newSignalInbox(), newSignalInbox() + v, h := newMuxPair(t, MuxConfig{OnSignal: viewerInbox.onSignal}, MuxConfig{OnSignal: hostInbox.onSignal}) + for i := 0; i < 5; i++ { + if err := v.SendSignal([]byte(fmt.Sprintf("to-host-%d", i))); err != nil { + t.Fatal(err) + } + if err := h.SendSignal([]byte(fmt.Sprintf("to-viewer-%d", i))); err != nil { + t.Fatal(err) + } + } + for i := 0; i < 5; i++ { + if got := hostInbox.take(t); string(got) != fmt.Sprintf("to-host-%d", i) { + t.Fatalf("host's signal %d = %q", i, got) + } + if got := viewerInbox.take(t); string(got) != fmt.Sprintf("to-viewer-%d", i) { + t.Fatalf("viewer's signal %d = %q", i, got) + } + } + }) + + t.Run("a signal on a channel other than zero ends the link", func(t *testing.T) { + near, far := net.Pipe() + t.Cleanup(func() { _ = near.Close(); _ = far.Close() }) + host := NewMux(far, Host, MuxConfig{}) + t.Cleanup(func() { _ = host.Close() }) + go func() { + _, _ = writeFrame(near, frame{op: OpSignal, channel: 3, payload: []byte("{}")}, ChunkBytes) + }() + select { + case <-host.Done(): + case <-time.After(5 * time.Second): + t.Fatal("a signal on channel 3 did not end the link") + } + }) +} + +// V37: a signalling payload over SignalMax is refused by the sender and ends the +// link at the receiver, and more than SignalRate frames in a minute is refused by +// the sender and ends the link at the receiver (`too-many`). +func TestASignalFrameOverTheLimitIsRefused(t *testing.T) { + t.Run("the sender refuses a payload over the limit and sends nothing", func(t *testing.T) { + inbox := newSignalInbox() + v, _ := newMuxPair(t, MuxConfig{}, MuxConfig{OnSignal: inbox.onSignal}) + if err := v.SendSignal(make([]byte, SignalMax+1)); !errors.Is(err, ErrSignalTooLarge) { + t.Fatalf("SendSignal(SignalMax+1) = %v, want ErrSignalTooLarge", err) + } + if err := v.SendSignal(make([]byte, SignalMax)); err != nil { + t.Fatalf("SendSignal(SignalMax) = %v, want it sent", err) + } + if got := inbox.take(t); len(got) != SignalMax { + t.Fatalf("the host got %d bytes, want exactly the one payload at the limit", len(got)) + } + select { + case extra := <-inbox.got: + t.Fatalf("a refused payload still reached the host (%d bytes)", len(extra)) + default: + } + }) + + t.Run("a receiver ends the link on a payload over the limit", func(t *testing.T) { + near, far := net.Pipe() + t.Cleanup(func() { _ = near.Close(); _ = far.Close() }) + host := NewMux(far, Host, MuxConfig{}) + t.Cleanup(func() { _ = host.Close() }) + // ChunkBytes is larger than SignalMax, so the frame itself is well formed. + go func() { + _, _ = writeFrame(near, frame{op: OpSignal, channel: 0, payload: make([]byte, SignalMax+1)}, ChunkBytes) + }() + select { + case <-host.Done(): + case <-time.After(5 * time.Second): + t.Fatal("an oversize signal did not end the link") + } + }) + + t.Run("the sender stops at SignalRate frames a minute and starts again after it", func(t *testing.T) { + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + inbox := newSignalInbox() + v, _ := newMuxPair(t, MuxConfig{Clock: fc}, MuxConfig{Clock: fc, OnSignal: inbox.onSignal}) + for i := 0; i < SignalRate; i++ { + if err := v.SendSignal([]byte("x")); err != nil { + t.Fatalf("frame %d of %d was refused: %v", i+1, SignalRate, err) + } + inbox.take(t) + } + if err := v.SendSignal([]byte("x")); !errors.Is(err, ErrTooManySignals) { + t.Fatalf("frame %d in a minute = %v, want ErrTooManySignals", SignalRate+1, err) + } + fc.Advance(time.Minute + time.Second) + if err := v.SendSignal([]byte("x")); err != nil { + t.Fatalf("a frame a minute later was refused: %v", err) + } + inbox.take(t) + }) + + t.Run("a receiver ends the link on more than SignalRate frames in a minute", func(t *testing.T) { + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + near, far := net.Pipe() + t.Cleanup(func() { _ = near.Close(); _ = far.Close() }) + inbox := newSignalInbox() + host := NewMux(far, Host, MuxConfig{Clock: fc, OnSignal: inbox.onSignal}) + t.Cleanup(func() { _ = host.Close() }) + go func() { + for i := 0; i <= SignalRate; i++ { + if _, err := writeFrame(near, frame{op: OpSignal, channel: 0, payload: []byte("x")}, ChunkBytes); err != nil { + return + } + } + }() + select { + case <-host.Done(): + case <-time.After(5 * time.Second): + t.Fatal("a flood of signals did not end the link") + } + if n := len(inbox.got); n != SignalRate { + t.Fatalf("the host handed %d signals to its handler, want exactly %d before ending the link", n, SignalRate) + } + }) +} diff --git a/internal/livedoor/mux_test.go b/internal/livedoor/mux_test.go new file mode 100644 index 0000000000..c09afd6730 --- /dev/null +++ b/internal/livedoor/mux_test.go @@ -0,0 +1,674 @@ +package livedoor + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "io" + "net" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" +) + +func newMuxPair(t *testing.T, viewerCfg, hostCfg MuxConfig) (*Mux, *Mux) { + t.Helper() + c1, c2 := net.Pipe() + v := NewMux(c1, Viewer, viewerCfg) + h := NewMux(c2, Host, hostCfg) + t.Cleanup(func() { + _ = v.Close() + _ = h.Close() + }) + return v, h +} + +func openAcceptedPair(t *testing.T, v, h *Mux, chat string) (*Channel, *Channel) { + t.Helper() + ctx := context.Background() + type acceptRes struct { + ch *Channel + req OpenRequest + err error + } + accCh := make(chan acceptRes, 1) + guard.Go("livedoor.test.accept", func() { + ch, req, err := h.Accept(ctx) + if err == nil { + err = ch.Accept() + } + accCh <- acceptRes{ch: ch, req: req, err: err} + }) + + vCh, err := v.Open(ctx, chat) + if err != nil { + t.Fatalf("Open(%q) failed: %v", chat, err) + } + res := <-accCh + if res.err != nil { + t.Fatalf("Accept(%q) failed: %v", chat, res.err) + } + if res.req.Chat != chat || res.req.V != 1 { + t.Fatalf("OpenRequest = %+v, want chat=%q v=1", res.req, chat) + } + return vCh, res.ch +} + +// TestEveryFrameOpRoundTripsOversizeFailsAndUnknownOpsAreSkipped verifies +// contract (mux): a frame round-trips through the codec for every op, an n +// above ChunkBytes is a protocol error, and an unknown op with a payload is +// skipped so the next frame still decodes. +func TestEveryFrameOpRoundTripsOversizeFailsAndUnknownOpsAreSkipped(t *testing.T) { + ops := []uint8{ + OpOpen, + OpOpened, + OpRefused, + OpData, + OpCredit, + OpClose, + OpReset, + OpPing, + OpPong, + OpHelloAck, + } + var buf bytes.Buffer + for i, op := range ops { + want := frame{ + op: op, + channel: uint32(i*2 + 1), + payload: []byte{byte(i), 'o', 'k'}, + } + if _, err := writeFrame(&buf, want, ChunkBytes); err != nil { + t.Fatalf("writeFrame(op=%d) failed: %v", op, err) + } + got, err := readFrame(&buf, ChunkBytes, nil) + if err != nil { + t.Fatalf("readFrame(op=%d) failed: %v", op, err) + } + if got.op != want.op || got.channel != want.channel || !bytes.Equal(got.payload, want.payload) { + t.Fatalf("round-trip op=%d got %+v, want %+v", op, got, want) + } + } + + // An unknown opcode with a payload is skipped and the following frame decodes. + buf.Reset() + unknownPayload := []byte("future-extension-payload") + var hdr [frameHeaderBytes]byte + hdr[0] = 99 + binary.BigEndian.PutUint32(hdr[1:5], 7) + binary.BigEndian.PutUint32(hdr[5:9], uint32(len(unknownPayload))) + buf.Write(hdr[:]) + buf.Write(unknownPayload) + + nextWant := frame{op: OpData, channel: 3, payload: []byte("after-unknown")} + if _, err := writeFrame(&buf, nextWant, ChunkBytes); err != nil { + t.Fatalf("writeFrame after unknown failed: %v", err) + } + var readBytes int + got, err := readFrame(&buf, ChunkBytes, func(n int) { readBytes += n }) + if err != nil { + t.Fatalf("readFrame after unknown failed: %v", err) + } + if got.op != nextWant.op || got.channel != nextWant.channel || !bytes.Equal(got.payload, nextWant.payload) { + t.Fatalf("decoded frame after unknown = %+v, want %+v", got, nextWant) + } + if wantBytes := frameHeaderBytes + len(unknownPayload) + frameHeaderBytes + len(nextWant.payload); readBytes != wantBytes { + t.Fatalf("onFrameRead counted %d bytes, want %d", readBytes, wantBytes) + } + + // An incoming frame declaring n > ChunkBytes is a protocol error. + buf.Reset() + hdr[0] = OpData + binary.BigEndian.PutUint32(hdr[1:5], 1) + binary.BigEndian.PutUint32(hdr[5:9], uint32(ChunkBytes+1)) + buf.Write(hdr[:]) + if _, err := readFrame(&buf, ChunkBytes, nil); !errors.Is(err, ErrFrameTooLarge) { + t.Fatalf("readFrame with n > ChunkBytes returned %v, want ErrFrameTooLarge", err) + } +} + +// TestTwoChannelsInterleaveOnOneLinkWithoutStarvingTheSmallerOne verifies +// contract (mux): two channels interleave on one link, both deliver their +// bytes in order, and neither is starved while the other has a large backlog +// (writing 1 MiB on A while B sends a small message delivers B before A finishes). +func TestTwoChannelsInterleaveOnOneLinkWithoutStarvingTheSmallerOne(t *testing.T) { + lim := DefaultLimits() + lim.Rate = 64 << 20 + lim.RateBurst = 64 << 20 + v, h := newMuxPair(t, MuxConfig{Limits: lim}, MuxConfig{Limits: lim}) + + vA, hA := openAcceptedPair(t, v, h, "chat-a") + vB, hB := openAcceptedPair(t, v, h, "chat-b") + + const totalA = 1 << 20 + wantA := make([]byte, totalA) + for i := range wantA { + wantA[i] = byte(i % 251) + } + wantB := []byte("urgent-small-message-on-b") + + aDone := make(chan error, 1) + guard.Go("livedoor.test.writeA", func() { + _, err := vA.Write(wantA) + _ = vA.Close() + aDone <- err + }) + + // Read the first chunk of A so A is actively mid-transfer with its remaining + // window queued in A's outbound queue before B writes its small message. + gotA := make([]byte, 0, totalA) + firstChunk := make([]byte, ChunkBytes) + if _, err := io.ReadFull(hA, firstChunk); err != nil { + t.Fatalf("reading first chunk of A failed: %v", err) + } + gotA = append(gotA, firstChunk...) + + bWriteDone := make(chan error, 1) + guard.Go("livedoor.test.writeB", func() { + _, err := vB.Write(wantB) + _ = vB.Close() + bWriteDone <- err + }) + + gotB, err := io.ReadAll(hB) + if err != nil { + t.Fatalf("reading B failed: %v", err) + } + if !bytes.Equal(gotB, wantB) { + t.Fatalf("B payload = %q, want %q", gotB, wantB) + } + + // B must arrive while A still has the bulk of its 1 MiB transfer pending. + select { + case err := <-aDone: + t.Fatalf("A finished its 1 MiB write before B was read (err=%v)", err) + default: + } + + restA, err := io.ReadAll(hA) + if err != nil { + t.Fatalf("reading remainder of A failed: %v", err) + } + gotA = append(gotA, restA...) + if err := <-aDone; err != nil { + t.Fatalf("vA.Write failed: %v", err) + } + if err := <-bWriteDone; err != nil { + t.Fatalf("vB.Write failed: %v", err) + } + if !bytes.Equal(gotA, wantA) { + t.Fatalf("A delivered %d bytes, want exact 1 MiB in order", len(gotA)) + } +} + +// TestAChannelThatIsNotReadStopsTheSenderAtItsWindowAndOtherChannelsStillFlow +// verifies contract V17 (mux half): a reader that never reads one channel caps +// the sender at ChannelWindow bytes in flight, a second channel on the same +// link keeps flowing, and the stuck sender wakes when the reader finally reads. +func TestAChannelThatIsNotReadStopsTheSenderAtItsWindowAndOtherChannelsStillFlow(t *testing.T) { + lim := DefaultLimits() + lim.Rate = 64 << 20 + lim.RateBurst = 64 << 20 + v, h := newMuxPair(t, MuxConfig{Limits: lim}, MuxConfig{Limits: lim}) + + vA, hA := openAcceptedPair(t, v, h, "unread-a") + vB, hB := openAcceptedPair(t, v, h, "flowing-b") + + var aSent atomic.Int64 + aReachedWindow := make(chan struct{}) + aFinished := make(chan error, 1) + chunk := bytes.Repeat([]byte{'a'}, ChunkBytes) + const totalChunksA = (ChannelWindow / ChunkBytes) + 4 + + guard.Go("livedoor.test.v17.writeA", func() { + for i := 0; i < totalChunksA; i++ { + n, err := vA.Write(chunk) + if err != nil { + aFinished <- err + return + } + if aSent.Add(int64(n)) == int64(ChannelWindow) { + close(aReachedWindow) + } + } + aFinished <- nil + }) + + <-aReachedWindow + + // Push 512 KiB (two full ChannelWindows) across channel B while channel A + // remains unread and pinned at ChannelWindow. + const totalB = 2 * ChannelWindow + wantB := bytes.Repeat([]byte{'b'}, totalB) + bReadDone := make(chan []byte, 1) + guard.Go("livedoor.test.v17.readB", func() { + data, _ := io.ReadAll(hB) + bReadDone <- data + }) + if _, err := vB.Write(wantB); err != nil { + t.Fatalf("vB.Write failed while A was capped: %v", err) + } + _ = vB.Close() + if gotB := <-bReadDone; !bytes.Equal(gotB, wantB) { + t.Fatalf("channel B read %d bytes, want %d", len(gotB), len(wantB)) + } + + if got := aSent.Load(); got != int64(ChannelWindow) { + t.Fatalf("unread channel A sent %d bytes, want capped at ChannelWindow (%d)", got, ChannelWindow) + } + + // Now drain channel A on the host and verify the stuck sender wakes and completes. + wantTotalA := totalChunksA * ChunkBytes + gotA := make([]byte, wantTotalA) + if _, err := io.ReadFull(hA, gotA); err != nil { + t.Fatalf("draining channel A failed: %v", err) + } + if err := <-aFinished; err != nil { + t.Fatalf("vA.Write after drain returned error: %v", err) + } + if got := aSent.Load(); got != int64(wantTotalA) { + t.Fatalf("channel A total sent = %d, want %d", got, wantTotalA) + } +} + +// TestACreditIsReturnedWhenTheQueueDrainsAndNeverFromATimer verifies contract +// V15 (mux half) / (mux): with a fake clock never advanced, the sender still +// gets credit back after the reader consumes, and no frame is written while +// idle for a virtual 10 minutes (OnFrameWritten never fires). +func TestACreditIsReturnedWhenTheQueueDrainsAndNeverFromATimer(t *testing.T) { + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + // FRAMES ARE COUNTED AT THE TRANSPORT, BEFORE THEY ARE DELIVERED. The mux's + // OnFrameWritten runs after a write returns, and over a synchronous pipe the + // receiver can have read the frame, returned the credit and woken this test + // before that callback runs, so a count taken from it can still be rising + // when the idle measurement starts. A count made before delivery cannot. + var framesWritten atomic.Int64 + c1, c2 := net.Pipe() + cfg := MuxConfig{Clock: fc} + v := NewMux(&countBeforeRWC{ReadWriteCloser: c1, n: &framesWritten}, Viewer, cfg) + h := NewMux(&countBeforeRWC{ReadWriteCloser: c2, n: &framesWritten}, Host, cfg) + t.Cleanup(func() { + _ = v.Close() + _ = h.Close() + }) + vCh, hCh := openAcceptedPair(t, v, h, "data-driven-credit") + + // Transfer 2 * ChannelWindow (512 KiB <= RateBurst 1 MiB) without ever + // advancing the fake clock; credit must return purely from reader consumption. + const transferBytes = 2 * ChannelWindow + payload := bytes.Repeat([]byte{'d'}, transferBytes) + readErrCh := make(chan error, 1) + guard.Go("livedoor.test.v15.reader", func() { + buf := make([]byte, transferBytes) + _, err := io.ReadFull(hCh, buf) + readErrCh <- err + }) + + if _, err := vCh.Write(payload); err != nil { + t.Fatalf("Write across two windows without advancing clock failed: %v", err) + } + if err := <-readErrCh; err != nil { + t.Fatalf("ReadFull across two windows failed: %v", err) + } + + // Wait for the trailing channel and link credit frames from the last Read to + // flush before measuring the 10-minute idle period. + v.mu.Lock() + for vCh.sendCredit < ChannelWindow || v.linkSendCredit < LinkWindow { + v.cond.Wait() + } + v.mu.Unlock() + + framesWritten.Store(0) + fc.Advance(10 * time.Minute) + if got := framesWritten.Load(); got != 0 { + t.Fatalf("%d frames were written during 10 virtual minutes of idle, want 0", got) + } +} + +// TestPeerOverrunningCreditFailsTheLinkCloseWakesBlockedCallersAndTooManyChannelsIsRefused +// verifies contract (mux): a peer that sends data beyond its credit fails the +// link, Close wakes every blocked Read/Write/Open/Accept exactly once, and +// opening past MaxChannelsPerLink is refused with too-many. +func TestPeerOverrunningCreditFailsTheLinkCloseWakesBlockedCallersAndTooManyChannelsIsRefused(t *testing.T) { + // 1. Opening past MaxChannelsPerLink is refused with ReasonTooMany. + v, h := newMuxPair(t, MuxConfig{}, MuxConfig{}) + for i := 0; i < MaxChannelsPerLink; i++ { + openAcceptedPair(t, v, h, "slot") + } + _, err := v.Open(context.Background(), "one-too-many") + var refErr *RefusedError + if !errors.As(err, &refErr) || refErr.Reason != ReasonTooMany { + t.Fatalf("33rd Open returned %v, want *RefusedError{Reason:%q}", err, ReasonTooMany) + } + + // 2. A peer that sends DATA beyond its ChannelWindow credit fails the link. + rawPeer, hostSide := net.Pipe() + hostMux := NewMux(hostSide, Host, MuxConfig{}) + t.Cleanup(func() { + _ = rawPeer.Close() + _ = hostMux.Close() + }) + accepted := make(chan *Channel, 1) + guard.Go("livedoor.test.overrun.accept", func() { + ch, _, err := hostMux.Accept(context.Background()) + if err == nil { + _ = ch.Accept() + accepted <- ch + } + }) + if _, err := writeFrame(rawPeer, frame{op: OpOpen, channel: 1, payload: []byte(`{"chat":"c","v":1}`)}, ChunkBytes); err != nil { + t.Fatalf("raw OpOpen failed: %v", err) + } + if _, err := readFrame(rawPeer, ChunkBytes, nil); err != nil { + t.Fatalf("reading OpOpened failed: %v", err) + } + hostCh := <-accepted + + chunk := make([]byte, ChunkBytes) + chunksInWindow := ChannelWindow / ChunkBytes + for i := 0; i < chunksInWindow; i++ { + if _, err := writeFrame(rawPeer, frame{op: OpData, channel: 1, payload: chunk}, ChunkBytes); err != nil { + t.Fatalf("writing within window failed at chunk %d: %v", i, err) + } + } + // One extra byte beyond ChannelWindow without any consumed read must fail the link. + _, _ = writeFrame(rawPeer, frame{op: OpData, channel: 1, payload: []byte{'!'}}, ChunkBytes) + <-hostMux.Done() + if _, err := hostCh.Write([]byte("x")); !errors.Is(err, ErrLinkClosed) { + t.Fatalf("hostCh.Write after credit overrun returned %v, want ErrLinkClosed", err) + } + + // 3. Close wakes every blocked Read, Write, Open, and Accept exactly once. + v2, h2 := newMuxPair(t, MuxConfig{}, MuxConfig{}) + vCh2, hCh2 := openAcceptedPair(t, v2, h2, "wake-test") + + // Exhaust vCh2's channel send credit so the next Write blocks. + if _, err := vCh2.Write(make([]byte, ChannelWindow)); err != nil { + t.Fatalf("filling channel window failed: %v", err) + } + + readWake := make(chan error, 1) + writeWake := make(chan error, 1) + openWake := make(chan error, 1) + acceptWake := make(chan error, 1) + + // Drain hCh2 first so a subsequent Read blocks on an empty buffer. + drained := make([]byte, ChannelWindow) + if _, err := io.ReadFull(hCh2, drained); err != nil { + t.Fatalf("draining hCh2 failed: %v", err) + } + // Refill window on a second channel where h2 never reads so Write blocks while hCh2 Read blocks. + vCh3, _ := openAcceptedPair(t, v2, h2, "write-block") + if _, err := vCh3.Write(make([]byte, ChannelWindow)); err != nil { + t.Fatalf("filling vCh3 window failed: %v", err) + } + + guard.Go("livedoor.test.wake.read", func() { + var b [8]byte + _, err := hCh2.Read(b[:]) + readWake <- err + }) + guard.Go("livedoor.test.wake.write", func() { + _, err := vCh3.Write([]byte("blocked-on-credit")) + writeWake <- err + }) + guard.Go("livedoor.test.wake.accept", func() { + _, _, err := h2.Accept(context.Background()) + acceptWake <- err + }) + + // Use a raw peer so Open blocks waiting for OpOpened that never arrives. + cOpen1, cOpen2 := net.Pipe() + vOpen := NewMux(cOpen1, Viewer, MuxConfig{}) + t.Cleanup(func() { + _ = cOpen2.Close() + _ = vOpen.Close() + }) + guard.Go("livedoor.test.wake.drainOpen", func() { + _, _ = readFrame(cOpen2, ChunkBytes, nil) + }) + guard.Go("livedoor.test.wake.open", func() { + _, err := vOpen.Open(context.Background(), "never-answered") + openWake <- err + }) + + _ = v2.Close() + _ = v2.Close() + _ = h2.Close() + _ = vOpen.Close() + + if err := <-readWake; err == nil { + t.Fatal("blocked Read woke with nil error on Close") + } + if err := <-writeWake; !errors.Is(err, ErrLinkClosed) { + t.Fatalf("blocked Write woke with %v, want ErrLinkClosed", err) + } + if err := <-acceptWake; !errors.Is(err, ErrLinkClosed) { + t.Fatalf("blocked Accept woke with %v, want ErrLinkClosed", err) + } + if err := <-openWake; !errors.Is(err, ErrLinkClosed) { + t.Fatalf("blocked Open woke with %v, want ErrLinkClosed", err) + } +} + +// TestPingIsAnsweredWithMatchingPongAndAnIdleMuxWritesNothingOverAnHour +// verifies contract (mux): OpPing is answered with OpPong carrying the same seq, +// and a mux with no pings and no traffic writes zero frames over a virtual hour. +func TestPingIsAnsweredWithMatchingPongAndAnIdleMuxWritesNothingOverAnHour(t *testing.T) { + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + pongs := make(chan uint32, 1) + var written atomic.Int64 + + v, _ := newMuxPair(t, + MuxConfig{ + Clock: fc, + OnPong: func(seq uint32) { pongs <- seq }, + OnFrameWritten: func(int) { written.Add(1) }, + }, + MuxConfig{ + Clock: fc, + OnFrameWritten: func(int) { written.Add(1) }, + }, + ) + + if err := v.SendPing(0xCAFEBABE); err != nil { + t.Fatalf("SendPing failed: %v", err) + } + if got := <-pongs; got != 0xCAFEBABE { + t.Fatalf("OnPong got seq %#x, want 0xCAFEBABE", got) + } + eventually(t, "both ping and pong frame write callbacks to complete", func() bool { + return written.Load() == 2 + }) + + written.Store(0) + fc.Advance(time.Hour) + if got := written.Load(); got != 0 { + t.Fatalf("idle mux wrote %d frames over a virtual hour, want 0", got) + } +} + +// TestOneLinkIsPacedToItsRate verifies contract V18 (pacing half): with the +// fake clock, writing 3 MiB through a link with Rate = 1 MiB/s and burst 1 MiB +// delivers the first MiB at once and the rest only as the clock advances +// (asserting byte totals at virtual 0 s, 1 s, and 2 s). +func TestOneLinkIsPacedToItsRate(t *testing.T) { + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + lim := DefaultLimits() + lim.Rate = 1 << 20 + lim.RateBurst = 1 << 20 + + v, h := newMuxPair(t, MuxConfig{Clock: fc, Limits: lim}, MuxConfig{Clock: fc, Limits: lim}) + vCh, hCh := openAcceptedPair(t, v, h, "paced-chat") + + const ( + oneMiB = 1 << 20 + threeMiB = 3 << 20 + ) + var delivered atomic.Int64 + at1MiB := make(chan struct{}) + at2MiB := make(chan struct{}) + at3MiB := make(chan struct{}) + + guard.Go("livedoor.test.v18.reader", func() { + buf := make([]byte, ChunkBytes) + for { + n, err := hCh.Read(buf) + if n > 0 { + tot := delivered.Add(int64(n)) + if tot == oneMiB { + close(at1MiB) + } else if tot == 2*oneMiB { + close(at2MiB) + } else if tot == threeMiB { + close(at3MiB) + } + } + if err != nil { + return + } + } + }) + + writeDone := make(chan error, 1) + guard.Go("livedoor.test.v18.writer", func() { + _, err := vCh.Write(make([]byte, threeMiB)) + writeDone <- err + }) + + // Virtual 0 s: the 1 MiB burst arrives immediately and the writer parks on + // the fake clock waiting for tokens for the second megabyte. + <-at1MiB + fc.WaitForTimers(1) + if got := delivered.Load(); got != oneMiB { + t.Fatalf("delivered at virtual 0 s = %d, want %d (1 MiB)", got, oneMiB) + } + + // Virtual 1 s: advancing by 1 s refills 1 MiB and delivers the second megabyte. + fc.Advance(time.Second) + <-at2MiB + fc.WaitForTimers(1) + if got := delivered.Load(); got != 2*oneMiB { + t.Fatalf("delivered at virtual 1 s = %d, want %d (2 MiB)", got, 2*oneMiB) + } + + // Virtual 2 s: advancing by another 1 s refills 1 MiB and delivers the third megabyte. + fc.Advance(time.Second) + <-at3MiB + if err := <-writeDone; err != nil { + t.Fatalf("3 MiB write returned error: %v", err) + } + if got := delivered.Load(); got != threeMiB { + t.Fatalf("delivered at virtual 2 s = %d, want %d (3 MiB)", got, threeMiB) + } +} + +// TestRefuseReachesOpenAsRefusedErrorAndResetCarriesItsReasonToRead verifies +// contract (mux): Refuse("not-running") reaches the viewer's Open as +// *RefusedError{Reason:"not-running"}, and Reset("lagging") on the host side +// makes the viewer's channel Read return an error whose Reason() is lagging. +func TestRefuseReachesOpenAsRefusedErrorAndResetCarriesItsReasonToRead(t *testing.T) { + v, h := newMuxPair(t, MuxConfig{}, MuxConfig{}) + + // 1. Refuse("not-running") reaches Open as *RefusedError{Reason:"not-running"}. + guard.Go("livedoor.test.refuse", func() { + ch, _, err := h.Accept(context.Background()) + if err == nil { + _ = ch.Refuse(ReasonNotRunning) + } + }) + _, err := v.Open(context.Background(), "stopped-chat") + var refErr *RefusedError + if !errors.As(err, &refErr) || refErr.Reason != ReasonNotRunning { + t.Fatalf("Open after Refuse(%q) returned %v, want *RefusedError{Reason:%q}", ReasonNotRunning, err, ReasonNotRunning) + } + + // 2. Reset("lagging") on the host makes the viewer's channel Read return an + // error whose Reason() is "lagging". + vCh, hCh := openAcceptedPair(t, v, h, "lagging-chat") + if err := hCh.Reset(ReasonLagging); err != nil { + t.Fatalf("hCh.Reset(%q) failed: %v", ReasonLagging, err) + } + var buf [32]byte + _, readErr := vCh.Read(buf[:]) + if readErr == nil { + t.Fatal("vCh.Read after host Reset succeeded, want error") + } + var reasoner interface{ Reason() string } + if !errors.As(readErr, &reasoner) || reasoner.Reason() != ReasonLagging { + t.Fatalf("vCh.Read error = %T (%v), want Reason() == %q", readErr, readErr, ReasonLagging) + } + if got := vCh.Reason(); got != ReasonLagging { + t.Fatalf("vCh.Reason() = %q, want %q", got, ReasonLagging) + } + + // 3. OpHelloAck round-trips from host to viewer on channel 0. + wantAck := HelloAck{ + V: 1, + Watch: true, + Drive: false, + Road: "relay", + Limits: DefaultLimits(), + } + if err := h.SendHelloAck(wantAck); err != nil { + t.Fatalf("SendHelloAck failed: %v", err) + } + gotAck, err := v.WaitHelloAck(context.Background()) + if err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + if gotAck.Watch != wantAck.Watch || gotAck.Drive != wantAck.Drive || gotAck.Road != wantAck.Road || gotAck.Limits.ChannelWindow != wantAck.Limits.ChannelWindow { + t.Fatalf("WaitHelloAck got %+v, want %+v", gotAck, wantAck) + } +} + +// TestUnixTransportEnforcesSunPathLimitAndDialsShortSocket verifies contract +// (mux): UnixTransport rejects socket paths over 103 bytes and listens/dials +// short socket paths under /tmp/ld-*. +func TestUnixTransportEnforcesSunPathLimitAndDialsShortSocket(t *testing.T) { + tr := UnixTransport() + longAddr := "/tmp/" + strings.Repeat("a", 100) + if _, err := tr.Listen(longAddr); err == nil { + t.Fatalf("Listen(%d-byte path) succeeded, want sun_path limit error", len(longAddr)) + } + if _, err := tr.Dial(context.Background(), longAddr); err == nil { + t.Fatalf("Dial(%d-byte path) succeeded, want sun_path limit error", len(longAddr)) + } + + dir, err := os.MkdirTemp("/tmp", "ld-") + if err != nil { + t.Fatalf("MkdirTemp failed: %v", err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + + addr := filepath.Join(dir, "s.sock") + ln, err := tr.Listen(addr) + if err != nil { + t.Fatalf("Listen(%q) failed: %v", addr, err) + } + t.Cleanup(func() { _ = ln.Close() }) + + accepted := make(chan net.Conn, 1) + guard.Go("livedoor.test.unix.accept", func() { + c, err := ln.Accept() + if err == nil { + accepted <- c + } + }) + + client, err := tr.Dial(context.Background(), addr) + if err != nil { + t.Fatalf("Dial(%q) failed: %v", addr, err) + } + t.Cleanup(func() { _ = client.Close() }) + + server := <-accepted + t.Cleanup(func() { _ = server.Close() }) +} diff --git a/internal/livedoor/registry.go b/internal/livedoor/registry.go new file mode 100644 index 0000000000..6c58632ad9 --- /dev/null +++ b/internal/livedoor/registry.go @@ -0,0 +1,288 @@ +package livedoor + +import ( + "path/filepath" + "strings" + "sync" + + "github.com/Agent-Field/codeaf/internal/home" +) + +// Closer is the lifecycle handle a live tunnel registers with a Registry so +// device removal and permit edits reach open views immediately. +type Closer interface { + CloseWithReason(reason string) + PermitsChanged() +} + +type channelResetter interface { + resetAllChannels(reason string) +} + +type maxTunnelsProvider interface { + maxTunnelsPerDevice() int +} + +// roadProvider is implemented by a Closer that knows which road it arrived on. +// A Closer that does not is a relay tunnel, which is every tunnel that existed +// before the direct road did. +type roadProvider interface { + roadName() string +} + +type regEntry struct { + id uint64 + device string + road string + closer Closer +} + +func roadOf(c Closer) string { + if p, ok := c.(roadProvider); ok { + if road := p.roadName(); road != "" { + return road + } + } + return RoadRelay +} + +// Registry tracks active live-door tunnels by authenticated viewer device ID so +// device revocation, permit changes, per-device tunnel limits, and daily budget +// exhaustion reach every open tunnel without holding a lock across network writes. +type Registry struct { + mu sync.Mutex + nextID uint64 + byDevice map[string][]*regEntry +} + +// NewRegistry returns an empty tunnel registry. +func NewRegistry() *Registry { + return &Registry{ + byDevice: make(map[string][]*regEntry), + } +} + +// Add registers c under device and returns an idempotent removal callback. When +// device already holds MaxTunnelsPerDevice active tunnels ON THE SAME ROAD, the +// oldest of that road is closed with ReasonHostClosing outside the registry lock +// before Add returns. +// +// THE CAP IS PER ROAD, because a reconnecting relay link briefly overlaps its +// dying predecessor and must be allowed to, and a cap shared with the direct road +// would let that reconnect evict a healthy direct tunnel (or the other way +// round). Each road evicts only its own. +func (r *Registry) Add(device string, c Closer) (remove func()) { + if r == nil || c == nil { + return func() {} + } + maxTunnels := MaxTunnelsPerDevice + if p, ok := c.(maxTunnelsProvider); ok { + if m := p.maxTunnelsPerDevice(); m > 0 { + maxTunnels = m + } + } + road := roadOf(c) + + var evicted []Closer + r.mu.Lock() + r.nextID++ + id := r.nextID + list := r.byDevice[device] + for sameRoad(list, road) >= maxTunnels { + for i, entry := range list { + if entry.road == road { + evicted = append(evicted, entry.closer) + list = append(append([]*regEntry(nil), list[:i]...), list[i+1:]...) + break + } + } + } + list = append(list, ®Entry{ + id: id, + device: device, + road: road, + closer: c, + }) + r.byDevice[device] = list + r.mu.Unlock() + + for _, old := range evicted { + old.CloseWithReason(ReasonHostClosing) + } + + var once sync.Once + return func() { + once.Do(func() { + r.mu.Lock() + cur := r.byDevice[device] + for i, entry := range cur { + if entry.id == id { + cur = append(cur[:i], cur[i+1:]...) + break + } + } + if len(cur) == 0 { + delete(r.byDevice, device) + } else { + r.byDevice[device] = cur + } + r.mu.Unlock() + }) + } +} + +// sameRoad counts the entries in list that arrived on road. +func sameRoad(list []*regEntry, road string) int { + n := 0 + for _, entry := range list { + if entry.road == road { + n++ + } + } + return n +} + +// Revoke removes and closes every registered tunnel belonging to any of devices +// with ReasonRemoved. +func (r *Registry) Revoke(devices ...string) { + if r == nil || len(devices) == 0 { + return + } + var targets []Closer + r.mu.Lock() + for _, dev := range devices { + if dev == "" { + continue + } + for _, entry := range r.byDevice[dev] { + targets = append(targets, entry.closer) + } + delete(r.byDevice, dev) + } + r.mu.Unlock() + + for _, c := range targets { + c.CloseWithReason(ReasonRemoved) + } +} + +// PermitsChanged notifies every registered tunnel for device that its host +// permit may have changed. When device is empty, all registered tunnels across +// all devices are notified. +func (r *Registry) PermitsChanged(device string) { + if r == nil { + return + } + var targets []Closer + r.mu.Lock() + if device == "" { + for _, list := range r.byDevice { + for _, entry := range list { + targets = append(targets, entry.closer) + } + } + } else { + for _, entry := range r.byDevice[device] { + targets = append(targets, entry.closer) + } + } + r.mu.Unlock() + + for _, c := range targets { + c.PermitsChanged() + } +} + +// Count reports how many active tunnels are currently registered for device. +func (r *Registry) Count(device string) int { + if r == nil { + return 0 + } + r.mu.Lock() + defer r.mu.Unlock() + return len(r.byDevice[device]) +} + +// HasRoad reports whether device has at least one tunnel registered on road. The +// host uses it to excuse a silent relay standby while a direct tunnel of the same +// device is open. +func (r *Registry) HasRoad(device, road string) bool { + if r == nil { + return false + } + r.mu.Lock() + defer r.mu.Unlock() + return sameRoad(r.byDevice[device], road) > 0 +} + +// countRoad reports how many tunnels are registered on road across every +// device: what the host's own direct-tunnel cap is measured against. +func (r *Registry) countRoad(road string) int { + if r == nil { + return 0 + } + r.mu.Lock() + defer r.mu.Unlock() + n := 0 + for _, list := range r.byDevice { + n += sameRoad(list, road) + } + return n +} + +// onBudgetExhausted resets the channels of every RELAY tunnel. A direct tunnel +// is not counted by the daily budget and a spent budget never touches it: the +// budget exists for the relay's cost. +func (r *Registry) onBudgetExhausted() { + if r == nil { + return + } + var targets []channelResetter + r.mu.Lock() + for _, list := range r.byDevice { + for _, entry := range list { + if entry.road == RoadDirect { + continue + } + if cr, ok := entry.closer.(channelResetter); ok { + targets = append(targets, cr) + } + } + } + r.mu.Unlock() + + for _, cr := range targets { + cr.resetAllChannels(ReasonBudget) + } +} + +var ( + defaultRegistriesMu sync.Mutex + defaultRegistries = make(map[string]*Registry) +) + +// DefaultRegistry returns the process-wide Registry for homeDir, creating it on +// first use so in-process revocation callers and the live door share one table. +func DefaultRegistry(homeDir string) *Registry { + homeDir = strings.TrimSpace(homeDir) + if homeDir == "" { + homeDir = home.Dir() + } + key := filepath.Clean(homeDir) + defaultRegistriesMu.Lock() + defer defaultRegistriesMu.Unlock() + reg, ok := defaultRegistries[key] + if !ok { + reg = NewRegistry() + defaultRegistries[key] = reg + } + return reg +} + +// NotifyRemoved closes any live tunnel for device under homeDir immediately. +func NotifyRemoved(homeDir, device string) { + if strings.TrimSpace(device) == "" { + return + } + DefaultRegistry(homeDir).Revoke(device) +} diff --git a/internal/livedoor/remote_control_off_test.go b/internal/livedoor/remote_control_off_test.go new file mode 100644 index 0000000000..3ff9dc9937 --- /dev/null +++ b/internal/livedoor/remote_control_off_test.go @@ -0,0 +1,376 @@ +package livedoor + +import ( + "context" + "errors" + "io" + "net" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/pair" +) + +// These tests are written from the contract for the person turning remote +// control off on the computer being watched, not from the code that implements +// it: +// +// C1 A viewer that has a chat open on a host whose remote control goes off has +// that view ended with ONE reason that says so. The link does not redial: no +// timer is armed and no tunnel is dialled again by itself. +// C2 A host that goes away without saying anything is still a host that went +// away: the link redials as it always did. +// C3 A host that changes the permit (watching taken away while remote control +// stays on) still ends the view with the permit's reason, as it always did. +// C4 A build that does not know the new reason ends the view cleanly: the reason +// is an opaque string on the wire, the viewer says a plain loss of +// connection, and it redials as it did before the reason existed. +// C5 Turning remote control back on is enough for the next view a person opens +// to work, without restarting the viewer. + +// switchableHost serves one viewer tunnel per dial with a permit and a switch the +// test turns, the way syncsetup's door reads the setting on every question. +type switchableHost struct { + watch atomic.Bool + off atomic.Bool + reg *Registry + peer Peer + dials atomic.Int32 +} + +func newSwitchableHost(t *testing.T, ctx context.Context, fc *FakeClock) (*switchableHost, *Link) { + t.Helper() + h := &switchableHost{ + reg: NewRegistry(), + peer: Peer{Device: "dev-viewer", Label: "laptop", Permit: pair.Permit{Watch: true, Drive: true}}, + } + h.watch.Store(true) + resolver := startStubHostResolver(t) + link := NewLink(LinkConfig{ + Clock: fc, + HostName: "Desktop", + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + h.dials.Add(1) + vSide, hSide := net.Pipe() + t.Cleanup(func() { + _ = vSide.Close() + _ = hSide.Close() + }) + guard.Go("livedoor.test.rcoff.serve", func() { + _ = Serve(ctx, hSide, h.peer, ServeConfig{ + Resolver: resolver, + Registry: h.reg, + Host: "Desktop", + Road: "relay", + Permit: func(string) pair.Permit { + if !h.watch.Load() { + return pair.Permit{} + } + return pair.Permit{Watch: true, Drive: true} + }, + Off: func() bool { return h.off.Load() }, + }) + }) + return vSide, nil + }, + }) + t.Cleanup(link.Close) + return h, link +} + +// readEnd reads a channel until it ends and answers the error it ended with. +func readEnd(t *testing.T, ch io.Reader) error { + t.Helper() + done := make(chan error, 1) + guard.Go("livedoor.test.rcoff.read", func() { + var buf [32]byte + _, err := ch.Read(buf[:]) + done <- err + }) + select { + case err := <-done: + return err + case <-time.After(5 * time.Second): + t.Fatal("the view did not end") + return nil + } +} + +// C1. +func TestRemoteControlOffEndsAnOpenViewWithItsOwnReasonAndTheLinkDoesNotRedial(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + host, link := newSwitchableHost(t, ctx, fc) + + ch, err := link.OpenerContext("chat-off")(ctx) + if err != nil { + t.Fatalf("opening the view: %v", err) + } + ended := make(chan string, 1) + link.OnChannelEnd(func(_, reason string) { ended <- reason }) + + host.watch.Store(false) + host.off.Store(true) + host.reg.PermitsChanged("") + + readErr := readEnd(t, ch) + if reason, ok := ReasonOf(readErr); !ok || reason != ReasonRemoteControlOff { + t.Fatalf("the view ended with %v (reason %q), want the reason %q", readErr, reason, ReasonRemoteControlOff) + } + if got := <-ended; got != ReasonRemoteControlOff { + t.Fatalf("OnChannelEnd said %q, want %q", got, ReasonRemoteControlOff) + } + + eventually(t, "the link to rest with the host's reason and no timer armed", func() bool { + st := link.State() + return st.Kind == Revoked && st.Reason == ReasonRemoteControlOff && fc.BlockedTimers() == 0 + }) + if said := chatlist.LiveSaid(link.State().Reason, "Desktop"); said != "Desktop turned remote control off." { + t.Fatalf("the one sentence reads %q", said) + } + fc.Advance(time.Hour) + if got := host.dials.Load(); got != 1 { + t.Fatalf("the link dialled again by itself: %d dials, want 1", got) + } + if st := link.State(); st.Kind == Reconnecting || st.Kind == WentOffline { + t.Fatalf("the link claims %v although the host is up and said no", st.Kind) + } +} + +// C5: and turning it back on is taken by the next open. +func TestTheFirstOpeningAfterRemoteControlIsBackOnDialsAgain(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + host, link := newSwitchableHost(t, ctx, fc) + + ch, err := link.OpenerContext("chat-off")(ctx) + if err != nil { + t.Fatalf("opening the view: %v", err) + } + host.watch.Store(false) + host.off.Store(true) + host.reg.PermitsChanged("") + _ = readEnd(t, ch) + eventually(t, "the link to rest", func() bool { return link.State().Kind == Revoked }) + + host.watch.Store(true) + host.off.Store(false) + again, err := link.OpenerContext("chat-off")(ctx) + if err != nil { + t.Fatalf("opening again with remote control back on: %v", err) + } + defer again.Close() + if got := host.dials.Load(); got != 2 { + t.Fatalf("%d dials, want 2: the open after remote control came back did not dial", got) + } + eventually(t, "the link to be live again", func() bool { return link.State().Kind == Live }) +} + +// A person who asks again while the host is still off is refused in the same +// words (the host's answer to the dial carries them), and the view they open +// the next time, after the host is back on, works: the refusal is not remembered +// as this computer's permit being empty. +func TestAnOpenWhileRemoteControlIsStillOffIsRefusedAsOffAndLiftedWhenItIsBackOn(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + host, link := newSwitchableHost(t, ctx, fc) + + ch, err := link.OpenerContext("chat-off")(ctx) + if err != nil { + t.Fatalf("opening the view: %v", err) + } + host.watch.Store(false) + host.off.Store(true) + host.reg.PermitsChanged("") + _ = readEnd(t, ch) + eventually(t, "the link to rest", func() bool { return link.State().Kind == Revoked }) + + _, err = link.OpenerContext("chat-off")(ctx) + if reason, ok := ReasonOf(err); !ok || reason != ReasonRemoteControlOff { + t.Fatalf("an open on a host that is off was refused with %v (reason %q), want %q", err, reason, ReasonRemoteControlOff) + } + if st := link.State(); st.Kind != Revoked || st.Reason != ReasonRemoteControlOff || fc.BlockedTimers() != 0 { + t.Fatalf("after the refused open the link is %+v with %d timers, want it resting with the host's reason", st, fc.BlockedTimers()) + } + + host.watch.Store(true) + host.off.Store(false) + again, err := link.OpenerContext("chat-off")(ctx) + if err != nil { + t.Fatalf("opening with remote control back on, after a refused open: %v", err) + } + defer again.Close() +} + +// C3: a real permit change keeps its own reason and its own sentence. +func TestAPermitThatTakesWatchingAwayKeepsItsReasonWhileRemoteControlIsOn(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + host, link := newSwitchableHost(t, ctx, fc) + + ch, err := link.OpenerContext("chat-permit")(ctx) + if err != nil { + t.Fatalf("opening the view: %v", err) + } + host.watch.Store(false) // remote control stays on: host.off is false + host.reg.PermitsChanged("") + + readErr := readEnd(t, ch) + if reason, ok := ReasonOf(readErr); !ok || reason != ReasonPermitChanged { + t.Fatalf("the view ended with %v (reason %q), want the permit's %q", readErr, reason, ReasonPermitChanged) + } + var ce *ChannelError + if errors.As(readErr, &ce) && ce.EndsView() { + t.Fatal("a changed permit ends the view for good; it must keep redialling to learn the new permit") + } + if got := chatlist.LiveSaid(ReasonPermitChanged, "Desktop"); got != "Desktop changed what this computer may do in its chats." { + t.Fatalf("the permit sentence reads %q", got) + } + // It redials, learns it may not watch at all, and says that, as before. The + // clock is advanced inside the wait because the link arms its redial timer + // just after the channel's end is read. + eventually(t, "the redial to be told watching is off", func() bool { + fc.Advance(time.Second) + st := link.State() + return st.Kind == Revoked && st.Reason == ReasonNotAllowed + }) +} + +// C2: a host that simply goes away is a host that went away. +func TestAHostThatGoesAwayWithoutSayingAnythingIsStillRedialled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + + var ( + dials atomic.Int32 + sides = make(chan net.Conn, 4) + ) + link := NewLink(LinkConfig{ + Clock: fc, + HostName: "Desktop", + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + dials.Add(1) + vSide, hSide := net.Pipe() + t.Cleanup(func() { _ = vSide.Close(); _ = hSide.Close() }) + hMux := NewMux(hSide, Host, MuxConfig{}) + t.Cleanup(func() { _ = hMux.Close() }) + _ = hMux.SendHelloAck(HelloAck{V: 1, Watch: true, Drive: true, Road: "relay", Limits: DefaultLimits()}) + guard.Go("livedoor.test.vanish.accept", func() { + for { + ch, _, err := hMux.Accept(ctx) + if err != nil { + return + } + _ = ch.Accept() + } + }) + sides <- hSide + return vSide, nil + }, + }) + t.Cleanup(link.Close) + + ch, err := link.OpenerContext("chat-vanish")(ctx) + if err != nil { + t.Fatalf("opening the view: %v", err) + } + _ = (<-sides).Close() // the host's process is killed: nothing is said + + readErr := readEnd(t, ch) + var ce *ChannelError + if errors.As(readErr, &ce) && ce.EndsView() { + t.Fatalf("a connection that dropped without a word ended the view for good: %v", readErr) + } + eventually(t, "the link to redial", func() bool { + st := link.State() + return (st.Kind == Reconnecting || st.Kind == WentOffline) && fc.BlockedTimers() > 0 + }) + fc.Advance(time.Minute) + eventually(t, "the second dial", func() bool { return dials.Load() >= 2 }) +} + +// C4: a viewer built before the reason existed meets a string it has no case +// for. This drives the current link with exactly that: a reason it does not know. +func TestAReasonTheViewerHasNoSentenceForEndsTheViewCleanlyAndIsRedialled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + + var ( + dials atomic.Int32 + hostCh = make(chan *Channel, 1) + ) + link := NewLink(LinkConfig{ + Clock: fc, + HostName: "Desktop", + Dial: func(_ context.Context) (io.ReadWriteCloser, error) { + dials.Add(1) + vSide, hSide := net.Pipe() + t.Cleanup(func() { _ = vSide.Close(); _ = hSide.Close() }) + hMux := NewMux(hSide, Host, MuxConfig{}) + t.Cleanup(func() { _ = hMux.Close() }) + _ = hMux.SendHelloAck(HelloAck{V: 1, Watch: true, Drive: true, Road: "relay", Limits: DefaultLimits()}) + guard.Go("livedoor.test.unknown.accept", func() { + for { + ch, _, err := hMux.Accept(ctx) + if err != nil { + return + } + _ = ch.Accept() + select { + case hostCh <- ch: + default: + } + } + }) + return vSide, nil + }, + }) + t.Cleanup(link.Close) + + ch, err := link.OpenerContext("chat-new")(ctx) + if err != nil { + t.Fatalf("opening the view: %v", err) + } + const fromANewerBuild = "a-reason-from-a-newer-build" + if err := (<-hostCh).Reset(fromANewerBuild); err != nil { + t.Fatalf("the host's reset: %v", err) + } + + readErr := readEnd(t, ch) + reason, ok := ReasonOf(readErr) + if !ok || reason != fromANewerBuild { + t.Fatalf("the view ended with %v (reason %q, %v), want the opaque reason carried through", readErr, reason, ok) + } + var ce *ChannelError + if errors.As(readErr, &ce) && ce.EndsView() { + t.Fatal("an unknown reason ended the view for good") + } + said := chatlist.LiveSaid(reason, "Desktop") + if said != "Lost the connection to Desktop." || strings.ContainsAny(said, "-_") { + t.Fatalf("an unknown reason is said as %q, want the plain loss of connection", said) + } + if st := link.State(); st.Kind == Revoked { + t.Fatalf("an unknown reason revoked the link: %+v", st) + } +} + +// The reason is a plain string on a frame every build already reads: no frame +// op, no field and no length changed with it. +func TestTheNewReasonIsAnOrdinaryResetPayload(t *testing.T) { + if len(ReasonRemoteControlOff) == 0 || len(ReasonRemoteControlOff) > ChunkBytes { + t.Fatalf("the reason %q does not fit a frame", ReasonRemoteControlOff) + } + if ReasonRemoteControlOff != "remote-control-off" { + t.Fatalf("the reason's bytes are %q: persisted and on-the-wire identifiers keep theirs", ReasonRemoteControlOff) + } +} diff --git a/internal/livedoor/resolve.go b/internal/livedoor/resolve.go new file mode 100644 index 0000000000..00ad07c69c --- /dev/null +++ b/internal/livedoor/resolve.go @@ -0,0 +1,322 @@ +package livedoor + +import ( + "context" + "encoding/json" + "errors" + "net" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/home" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" +) + +// ErrNotRunning reports that no live process currently holds the requested chat. +var ErrNotRunning = errors.New("livedoor: nobody is running that chat") + +const ( + // defaultPresenceTTL bounds how long one presence directory walk is reused + // across channel open requests before the disk is consulted again. + defaultPresenceTTL = 2 * time.Second + + // maxChatNameLen caps a chat folder name so oversized inputs are rejected + // before touching presence or the filesystem. + maxChatNameLen = 128 +) + +var errNothingHolding = errors.New("engine host: nothing is holding this workspace") + +// Holder describes the engine host process holding one workspace's chats, as the +// engine-host package reports it. +type Holder struct { + Self remote.HostSelf + Answered bool +} + +// DaemonDoors is how a resolver reaches the engine host that holds a workspace +// without this package importing the engine-host package, which imports the +// sync package that the live door is started from. The program's own entry +// point installs the real ones once at start; a resolver whose doors were never +// installed finds no daemon and answers from the registry alone. +type DaemonDoors struct { + // Inspect asks the host holding workspace who it is, as the engine-host + // package does (including filling in a pid an older host does not state). + Inspect func(workspace string) (Holder, error) + // Dial opens one connection to that host and never starts one. + Dial func(workspace string) (net.Conn, error) +} + +var ( + daemonDoorsMu sync.RWMutex + daemonDoors DaemonDoors +) + +// SetDaemonDoors installs the doors a resolver uses to reach an engine host. It +// is meant to be called once, before any resolver runs. +func SetDaemonDoors(d DaemonDoors) { + daemonDoorsMu.Lock() + daemonDoors = d + daemonDoorsMu.Unlock() +} + +// DaemonDoorsInstalled says whether both doors are in place, so the program can +// pin that its entry point wired them: without them a chat held by a daemon is +// never found, and nothing else would say so. +func DaemonDoorsInstalled() bool { + d := installedDaemonDoors() + return d.Inspect != nil && d.Dial != nil +} + +func installedDaemonDoors() DaemonDoors { + daemonDoorsMu.RLock() + defer daemonDoorsMu.RUnlock() + return daemonDoors +} + +// Route describes the holder process that answered for a chat and carries the +// transcript path and workspace needed to rewrite the viewer's initial hello. +type Route struct { + Kind string + PID int + Session string + Workspace string + Build string +} + +// Resolver locates the OS process holding an already-running chat and dials its +// local attach socket without ever booting or spawning a conversation. +type Resolver interface { + Resolve(ctx context.Context, chat string) (net.Conn, Route, error) +} + +// ResolverOptions configures the seams used by a Resolver so unit tests can +// substitute presence, flock, daemon inspection, and transport dependencies. +type ResolverOptions struct { + Presence func(exclude string) []session.SessionPresence + InUse func(path string) bool + Inspect func(workspace string) (Holder, error) + DialDaemon func(workspace string) (net.Conn, error) + RegistryDir string + Transport Transport + Clock Clock + PresenceTTL time.Duration +} + +type presenceFlight struct { + done chan struct{} + rows []session.SessionPresence +} + +type resolver struct { + presence func(exclude string) []session.SessionPresence + inUse func(path string) bool + inspect func(workspace string) (Holder, error) + dialDaemon func(workspace string) (net.Conn, error) + registryDir string + transport Transport + clock Clock + presenceTTL time.Duration + + mu sync.Mutex + cached []session.SessionPresence + cachedAt time.Time + hasCache bool + flight *presenceFlight +} + +// NewResolver constructs a Resolver rooted at homeDir, filling any unset option +// with its production default. +func NewResolver(homeDir string, opt ResolverOptions) Resolver { + homeDir = strings.TrimSpace(homeDir) + if homeDir == "" { + homeDir = home.Dir() + } + if opt.Presence == nil { + opt.Presence = session.HomePresence + } + if opt.InUse == nil { + opt.InUse = session.InUse + } + if opt.Inspect == nil { + opt.Inspect = func(workspace string) (Holder, error) { + if inspect := installedDaemonDoors().Inspect; inspect != nil { + return inspect(workspace) + } + return Holder{}, errNothingHolding + } + } + if opt.DialDaemon == nil { + opt.DialDaemon = func(workspace string) (net.Conn, error) { + if dial := installedDaemonDoors().Dial; dial != nil { + return dial(workspace) + } + return nil, errNothingHolding + } + } + if strings.TrimSpace(opt.RegistryDir) == "" { + opt.RegistryDir = filepath.Join(homeDir, "v3", "live") + } + if opt.Transport == nil { + opt.Transport = UnixTransport() + } + if opt.Clock == nil { + opt.Clock = RealClock() + } + if opt.PresenceTTL <= 0 { + opt.PresenceTTL = defaultPresenceTTL + } + return &resolver{ + presence: opt.Presence, + inUse: opt.InUse, + inspect: opt.Inspect, + dialDaemon: opt.DialDaemon, + registryDir: opt.RegistryDir, + transport: opt.Transport, + clock: opt.Clock, + presenceTTL: opt.PresenceTTL, + } +} + +func (r *resolver) Resolve(ctx context.Context, chat string) (net.Conn, Route, error) { + if !validChatName(chat) { + return nil, Route{}, ErrNotRunning + } + rows := r.readPresence() + for _, row := range rows { + place := session.Place{Dir: row.Dir} + if place.ID() != chat { + continue + } + transcript := place.Transcript() + if transcript == "" || row.PID <= 0 || !r.inUse(transcript) { + continue + } + if ws := strings.TrimSpace(row.Workspace); ws != "" { + if holder, err := r.inspect(ws); err == nil && holder.Self.PID == row.PID { + conn, err := r.dialDaemon(ws) + if err != nil || conn == nil { + return nil, Route{}, ErrNotRunning + } + build := strings.TrimSpace(row.Build) + if build == "" { + build = strings.TrimSpace(holder.Self.Revision) + } + if build == "" { + build = strings.TrimSpace(holder.Self.Build) + } + return conn, Route{ + Kind: "daemon", + PID: row.PID, + Session: transcript, + Workspace: row.Workspace, + Build: build, + }, nil + } + } + conn, regBuild, err := r.dialRegistry(ctx, row.PID) + if err != nil { + return nil, Route{}, ErrNotRunning + } + build := strings.TrimSpace(regBuild) + if build == "" { + build = strings.TrimSpace(row.Build) + } + return conn, Route{ + Kind: "registry", + PID: row.PID, + Session: transcript, + Workspace: row.Workspace, + Build: build, + }, nil + } + return nil, Route{}, ErrNotRunning +} + +func (r *resolver) readPresence() []session.SessionPresence { + r.mu.Lock() + now := r.clock.Now() + if r.hasCache && !now.Before(r.cachedAt) && now.Sub(r.cachedAt) < r.presenceTTL { + rows := r.cached + r.mu.Unlock() + return rows + } + if f := r.flight; f != nil { + r.mu.Unlock() + <-f.done + return f.rows + } + f := &presenceFlight{done: make(chan struct{})} + r.flight = f + r.mu.Unlock() + + rows := r.presence("") + + r.mu.Lock() + f.rows = rows + r.cached = rows + r.cachedAt = r.clock.Now() + r.hasCache = true + r.flight = nil + close(f.done) + r.mu.Unlock() + return rows +} + +func (r *resolver) dialRegistry(ctx context.Context, pid int) (net.Conn, string, error) { + path := filepath.Join(r.registryDir, strconv.Itoa(pid)+".json") + raw, err := os.ReadFile(path) + if err != nil { + return nil, "", ErrNotRunning + } + var entry registryEntry + if err := json.Unmarshal(raw, &entry); err != nil || entry.PID != pid { + return nil, "", ErrNotRunning + } + sock := strings.TrimSpace(entry.Socket) + if sock == "" { + return nil, "", ErrNotRunning + } + if !filepath.IsAbs(sock) { + if !validRelativeSocketName(sock) { + return nil, "", ErrNotRunning + } + sock = filepath.Join(r.registryDir, sock) + } + conn, err := r.transport.Dial(ctx, sock) + if err != nil || conn == nil { + return nil, "", ErrNotRunning + } + return conn, entry.Build, nil +} + +func validChatName(chat string) bool { + if chat == "" || len(chat) > maxChatNameLen { + return false + } + if chat == "." || chat == ".." { + return false + } + if strings.TrimSpace(chat) != chat { + return false + } + if strings.ContainsAny(chat, "/\\\x00") { + return false + } + return filepath.Base(chat) == chat +} + +func validRelativeSocketName(name string) bool { + if name == "" || name == "." || name == ".." { + return false + } + if strings.ContainsAny(name, "/\\\x00") { + return false + } + return filepath.Base(name) == name +} diff --git a/internal/livedoor/resolve_test.go b/internal/livedoor/resolve_test.go new file mode 100644 index 0000000000..2452155fc6 --- /dev/null +++ b/internal/livedoor/resolve_test.go @@ -0,0 +1,435 @@ +package livedoor + +import ( + "context" + "encoding/json" + "errors" + "net" + "os" + "path/filepath" + "reflect" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" +) + +func shortTempDir(t *testing.T) string { + t.Helper() + dir, err := os.MkdirTemp("/tmp", "ld-") + if err != nil { + t.Fatalf("MkdirTemp(/tmp, ld-) failed: %v", err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + return dir +} + +// TestTheResolverFindsTheHolderOfAChatThroughTheDaemonAndTheRegistryAndNeverStartsOne +// verifies contract V1 and V29: the resolver routes a chat to the workspace +// daemon when Inspect matches the presence PID, routes through the per-PID +// registry file when the daemon does not hold it, refuses missing or unlocked +// or unreachable holders with ErrNotRunning, and never invokes or exposes any +// host-spawning path. +func TestTheResolverFindsTheHolderOfAChatThroughTheDaemonAndTheRegistryAndNeverStartsOne(t *testing.T) { + // ResolverOptions must not carry any spawn, attach, or boot callback so the + // resolver is structurally incapable of starting a conversation or daemon. + optType := reflect.TypeFor[ResolverOptions]() + for i := 0; i < optType.NumField(); i++ { + name := strings.ToLower(optType.Field(i).Name) + if strings.Contains(name, "spawn") || strings.Contains(name, "attach") || strings.Contains(name, "boot") || strings.Contains(name, "start") { + t.Fatalf("ResolverOptions has start-capable field %q", optType.Field(i).Name) + } + } + + root := shortTempDir(t) + regDir := filepath.Join(root, "v3", "live") + if err := os.MkdirAll(regDir, 0o700); err != nil { + t.Fatalf("MkdirAll(%q) failed: %v", regDir, err) + } + + // Start a unix socket for the live registry route (PID 5151). + const regPID = 5151 + regSockName := strconv.Itoa(regPID) + ".sock" + regSockPath := filepath.Join(regDir, regSockName) + tr := UnixTransport() + regListener, err := tr.Listen(regSockPath) + if err != nil { + t.Fatalf("Listen(%q) failed: %v", regSockPath, err) + } + t.Cleanup(func() { _ = regListener.Close() }) + guard.Go("livedoor.test.resolve.regAccept", func() { + for { + c, err := regListener.Accept() + if err != nil { + return + } + _, _ = c.Write([]byte("from-registry")) + _ = c.Close() + } + }) + regJSON, err := json.Marshal(map[string]any{ + "pid": regPID, + "socket": regSockName, + "build": "build-reg", + }) + if err != nil { + t.Fatalf("Marshal registry json failed: %v", err) + } + if err := os.WriteFile(filepath.Join(regDir, strconv.Itoa(regPID)+".json"), regJSON, 0o600); err != nil { + t.Fatalf("WriteFile registry json failed: %v", err) + } + + // Write a registry file pointing at a dead socket (PID 7001). + const deadPID = 7001 + deadJSON, err := json.Marshal(map[string]any{ + "pid": deadPID, + "socket": strconv.Itoa(deadPID) + ".sock", + "build": "build-dead", + }) + if err != nil { + t.Fatalf("Marshal dead registry json failed: %v", err) + } + if err := os.WriteFile(filepath.Join(regDir, strconv.Itoa(deadPID)+".json"), deadJSON, 0o600); err != nil { + t.Fatalf("WriteFile dead registry json failed: %v", err) + } + + chatDir := func(chat string) string { + return filepath.Join(root, "projects", "bucket", chat) + } + transcriptOf := func(chat string) string { + return (session.Place{Dir: chatDir(chat)}).Transcript() + } + + cases := []struct { + name string + chat string + rows []session.SessionPresence + inUse bool + daemonPID int + inspectErr error + wantErr error + wantKind string + wantPID int + wantWorkspace string + wantBuild string + wantBanner string + wantNoInspect bool + wantNoDaemon bool + wantNoRegDial bool + }{ + { + name: "presence row + in-use + daemon pid matches -> daemon route with the daemon conn", + chat: "chat-daemon", + rows: []session.SessionPresence{{ + SessionID: "chat-daemon", + Workspace: "/work/daemon-proj", + PID: 4242, + Build: "build-daemon", + Dir: chatDir("chat-daemon"), + }}, + inUse: true, + daemonPID: 4242, + wantKind: "daemon", + wantPID: 4242, + wantWorkspace: "/work/daemon-proj", + wantBuild: "build-daemon", + wantBanner: "from-daemon", + wantNoRegDial: true, + }, + { + name: "presence row + registry file for that pid -> registry route", + chat: "chat-registry", + rows: []session.SessionPresence{{ + SessionID: "chat-registry", + Workspace: "/work/desk-proj", + PID: regPID, + Build: "build-presence", + Dir: chatDir("chat-registry"), + }}, + inUse: true, + inspectErr: errNothingHolding, + wantKind: "registry", + wantPID: regPID, + wantWorkspace: "/work/desk-proj", + wantBuild: "build-reg", + wantBanner: "from-registry", + wantNoDaemon: true, + }, + { + name: "no row -> ErrNotRunning", + chat: "chat-missing", + rows: nil, + wantErr: ErrNotRunning, + wantNoInspect: true, + wantNoDaemon: true, + wantNoRegDial: true, + }, + { + name: "row but InUse false -> ErrNotRunning", + chat: "chat-stale", + rows: []session.SessionPresence{{ + SessionID: "chat-stale", + Workspace: "/work/stale-proj", + PID: 4242, + Build: "build-stale", + Dir: chatDir("chat-stale"), + }}, + inUse: false, + daemonPID: 4242, + wantErr: ErrNotRunning, + wantNoInspect: true, + wantNoDaemon: true, + wantNoRegDial: true, + }, + { + name: "row, in use, daemon pid mismatch and no registry file -> ErrNotRunning", + chat: "chat-mismatch", + rows: []session.SessionPresence{{ + SessionID: "chat-mismatch", + Workspace: "/work/mismatch-proj", + PID: 6001, + Build: "build-mismatch", + Dir: chatDir("chat-mismatch"), + }}, + inUse: true, + daemonPID: 6002, + wantErr: ErrNotRunning, + wantNoDaemon: true, + wantNoRegDial: true, + }, + { + name: "registry file with a dead socket -> ErrNotRunning", + chat: "chat-dead", + rows: []session.SessionPresence{{ + SessionID: "chat-dead", + Workspace: "/work/dead-proj", + PID: deadPID, + Build: "build-dead", + Dir: chatDir("chat-dead"), + }}, + inUse: true, + inspectErr: errNothingHolding, + wantErr: ErrNotRunning, + wantNoDaemon: true, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var inspectCalls, daemonDialCalls, regDialCalls atomic.Int32 + wantTranscript := transcriptOf(tc.chat) + + spyTransport := &spyDialTransport{ + inner: tr, + onDial: func() { + regDialCalls.Add(1) + }, + } + + res := NewResolver(root, ResolverOptions{ + Presence: func(string) []session.SessionPresence { + return tc.rows + }, + InUse: func(path string) bool { + if path != wantTranscript { + t.Errorf("InUse called with %q, want %q", path, wantTranscript) + return false + } + return tc.inUse + }, + Inspect: func(workspace string) (Holder, error) { + inspectCalls.Add(1) + if tc.inspectErr != nil { + return Holder{}, tc.inspectErr + } + return Holder{ + Self: remote.HostSelf{PID: tc.daemonPID, Workspace: workspace}, + Answered: true, + }, nil + }, + DialDaemon: func(workspace string) (net.Conn, error) { + daemonDialCalls.Add(1) + c1, c2 := net.Pipe() + guard.Go("livedoor.test.resolve.daemonBanner", func() { + _, _ = c2.Write([]byte("from-daemon")) + _ = c2.Close() + }) + return c1, nil + }, + RegistryDir: regDir, + Transport: spyTransport, + Clock: NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)), + PresenceTTL: 2 * time.Second, + }) + + conn, route, err := res.Resolve(context.Background(), tc.chat) + if tc.wantErr != nil { + if !errors.Is(err, tc.wantErr) { + t.Fatalf("Resolve(%q) err = %v, want %v", tc.chat, err, tc.wantErr) + } + if conn != nil { + _ = conn.Close() + t.Fatalf("Resolve(%q) returned non-nil conn on error", tc.chat) + } + } else { + if err != nil { + t.Fatalf("Resolve(%q) unexpected error: %v", tc.chat, err) + } + defer conn.Close() + if route.Kind != tc.wantKind || route.PID != tc.wantPID || route.Session != wantTranscript || route.Workspace != tc.wantWorkspace || route.Build != tc.wantBuild { + t.Fatalf("Resolve(%q) route = %+v, want Kind=%q PID=%d Session=%q Workspace=%q Build=%q", + tc.chat, route, tc.wantKind, tc.wantPID, wantTranscript, tc.wantWorkspace, tc.wantBuild) + } + var buf [32]byte + n, _ := conn.Read(buf[:]) + if got := string(buf[:n]); got != tc.wantBanner { + t.Fatalf("conn read %q, want %q", got, tc.wantBanner) + } + } + + if tc.wantNoInspect && inspectCalls.Load() != 0 { + t.Fatalf("Inspect called %d times, want 0", inspectCalls.Load()) + } + if tc.wantNoDaemon && daemonDialCalls.Load() != 0 { + t.Fatalf("DialDaemon called %d times, want 0", daemonDialCalls.Load()) + } + if tc.wantNoRegDial && regDialCalls.Load() != 0 { + t.Fatalf("Transport.Dial called %d times, want 0", regDialCalls.Load()) + } + }) + } +} + +// TestTheResolverCachesPresenceWithinItsWindowAndCoalescesConcurrentReads +// verifies contract (resolver cache): two Resolve calls inside PresenceTTL read +// presence once, advancing the fake clock past PresenceTTL triggers a fresh read, +// and 16 concurrent Resolve calls coalesce into a single presence read. +func TestTheResolverCachesPresenceWithinItsWindowAndCoalescesConcurrentReads(t *testing.T) { + root := shortTempDir(t) + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + var presenceReads atomic.Int32 + + res := NewResolver(root, ResolverOptions{ + Presence: func(string) []session.SessionPresence { + presenceReads.Add(1) + return nil + }, + InUse: func(string) bool { return false }, + Clock: fc, + PresenceTTL: 2 * time.Second, + }) + + if _, _, err := res.Resolve(context.Background(), "chat-a"); !errors.Is(err, ErrNotRunning) { + t.Fatalf("first Resolve err = %v, want ErrNotRunning", err) + } + fc.Advance(time.Second) + if _, _, err := res.Resolve(context.Background(), "chat-b"); !errors.Is(err, ErrNotRunning) { + t.Fatalf("second Resolve inside TTL err = %v, want ErrNotRunning", err) + } + if got := presenceReads.Load(); got != 1 { + t.Fatalf("presence reads inside PresenceTTL = %d, want 1", got) + } + + // Pass the 2 s TTL window; the third Resolve must read presence again. + fc.Advance(2 * time.Second) + if _, _, err := res.Resolve(context.Background(), "chat-c"); !errors.Is(err, ErrNotRunning) { + t.Fatalf("third Resolve after TTL err = %v, want ErrNotRunning", err) + } + if got := presenceReads.Load(); got != 2 { + t.Fatalf("presence reads after PresenceTTL = %d, want 2", got) + } + + // 16 concurrent resolves on an expired cache must read presence once (single-flight). + fc.Advance(3 * time.Second) + const workers = 16 + var flightReads atomic.Int32 + entered := make(chan struct{}) + release := make(chan struct{}) + + concurrentRes := NewResolver(root, ResolverOptions{ + Presence: func(string) []session.SessionPresence { + if flightReads.Add(1) == 1 { + close(entered) + } + <-release + return nil + }, + InUse: func(string) bool { return false }, + Clock: fc, + PresenceTTL: 2 * time.Second, + }) + + var wg sync.WaitGroup + wg.Add(workers) + for i := 0; i < workers; i++ { + if i == 1 { + // Ensure the first worker has entered Presence before launching the rest. + <-entered + } + guard.Go("livedoor.test.resolve.singleflight", func() { + defer wg.Done() + _, _, _ = concurrentRes.Resolve(context.Background(), "chat-concurrent") + }) + } + close(release) + wg.Wait() + + if got := flightReads.Load(); got != 1 { + t.Fatalf("16 concurrent Resolve calls read presence %d times, want 1", got) + } +} + +// TestTheResolverRejectsUnsafeAndOversizedChatNamesWithoutReadingPresence +// verifies contract (resolver names): "../x", "a/b", "", ".", and a +// 300-character name all return ErrNotRunning without touching presence. +func TestTheResolverRejectsUnsafeAndOversizedChatNamesWithoutReadingPresence(t *testing.T) { + root := shortTempDir(t) + var presenceReads atomic.Int32 + res := NewResolver(root, ResolverOptions{ + Presence: func(string) []session.SessionPresence { + presenceReads.Add(1) + return nil + }, + }) + + badNames := []string{ + "../x", + "a/b", + "", + ".", + "..", + `a\b`, + strings.Repeat("x", 300), + } + for _, bad := range badNames { + _, _, err := res.Resolve(context.Background(), bad) + if !errors.Is(err, ErrNotRunning) { + t.Fatalf("Resolve(%q) err = %v, want ErrNotRunning", bad, err) + } + } + if got := presenceReads.Load(); got != 0 { + t.Fatalf("presence was read %d times for invalid chat names, want 0", got) + } +} + +type spyDialTransport struct { + inner Transport + onDial func() +} + +func (s *spyDialTransport) Listen(addr string) (net.Listener, error) { + return s.inner.Listen(addr) +} + +func (s *spyDialTransport) Dial(ctx context.Context, addr string) (net.Conn, error) { + if s.onDial != nil { + s.onDial() + } + return s.inner.Dial(ctx, addr) +} diff --git a/internal/livedoor/router.go b/internal/livedoor/router.go new file mode 100644 index 0000000000..a1e1d540f2 --- /dev/null +++ b/internal/livedoor/router.go @@ -0,0 +1,1011 @@ +package livedoor + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net" + "sync" + "sync/atomic" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/remote" +) + +const ( + defaultRoad = RoadRelay + hostBackstopExtra = time.Minute + opFlushClose uint8 = 0xff +) + +// Peer identifies the authenticated viewer computer at the other end of a live +// door tunnel along with its permit at connection time. +type Peer struct { + Device string + Label string + Permit pair.Permit + Class pair.PermitClass +} + +// ServeConfig configures a host-side live door router over one viewer tunnel. +type ServeConfig struct { + Resolver Resolver + Registry *Registry + Budget *Budget + Permit func(device string) pair.Permit + Clock Clock + Limits Limits + Host string + // Road is "relay" (the default) or "direct", and the CALLER chooses it from + // how the tunnel arrived, never from anything the viewer said. A direct + // tunnel is served with no daily budget at all, whatever Budget says, and + // with the direct road's pacing and liveness wherever Limits leaves them + // unset. + Road string + // Direct, when set on a relay tunnel, is the host half of the direct road: + // the link advertises it in the HelloAck and hands it every offer a viewer + // signals. A nil Direct means this host takes no offers, and an offer that + // arrives anyway is refused before anything is allocated. + Direct DirectHost + // Off, when set, says whether the person has turned remote control off on + // this computer. The permit func already answers "no watching" for every + // device while it is off, which is all a viewer can be refused with, but a + // viewer that is told its permit CHANGED reads a different computer than the + // one that went quiet: the host did not change what it may do, it stopped + // doing it. So while Off says true, a view ended for want of a watch permit + // is ended with [ReasonRemoteControlOff], and every other no-watch permit + // keeps [ReasonPermitChanged]. Nil keeps the permit reasons everywhere. + Off func() bool +} + +type tunnelRWC struct { + rwc io.ReadWriteCloser +} + +func (t *tunnelRWC) Read(p []byte) (int, error) { + return t.rwc.Read(p) +} + +func (t *tunnelRWC) Write(p []byte) (int, error) { + if len(p) >= frameHeaderBytes && p[0] == opFlushClose { + return 0, ErrLinkClosed + } + return t.rwc.Write(p) +} + +func (t *tunnelRWC) Close() error { + return t.rwc.Close() +} + +type serverTunnel struct { + peer Peer + cfg ServeConfig + clock Clock + limits Limits + road string + mux *Mux + + mu sync.Mutex + lastRead time.Time + lastPermit pair.Permit + chans map[uint32]*activeChan + closing bool + droppedFrames atomic.Int64 + + // ctx is the lifetime of the tunnel's Serve call. sessions holds the direct + // attempts this tunnel's viewer has pending, by attempt id. + ctx context.Context + sessions map[string]DirectSession + // muxReady closes once st.mux is assigned. The mux's reader goroutine starts + // inside NewMux, so a signalling frame could arrive before the assignment + // completes, and a handler that answers on the mux waits for this first. + muxReady chan struct{} +} + +type activeChan struct { + ch *Channel + outQ *chanOutQueue + + mu sync.Mutex + holderConn net.Conn + drive bool + closed bool +} + +func (a *activeChan) setDrive(drive bool) { + a.mu.Lock() + a.drive = drive + a.mu.Unlock() +} + +func (a *activeChan) isDrive() bool { + a.mu.Lock() + defer a.mu.Unlock() + return a.drive +} + +func (a *activeChan) setOutQueue(q *chanOutQueue) { + a.mu.Lock() + closed := a.closed + a.outQ = q + a.mu.Unlock() + if closed { + q.abort() + } +} + +func (a *activeChan) closeHolderAndQueue() { + a.mu.Lock() + a.closed = true + conn := a.holderConn + q := a.outQ + a.mu.Unlock() + + if q != nil { + q.abort() + } + if conn != nil { + _ = conn.Close() + } +} + +type chanOutQueue struct { + mu sync.Mutex + cond *sync.Cond + lines [][]byte + buffered int + limit int + aborted bool + overflowed bool + eof bool +} + +func newChanOutQueue(limit int) *chanOutQueue { + if limit <= 0 { + limit = QueueMax + } + q := &chanOutQueue{limit: limit} + q.cond = sync.NewCond(&q.mu) + return q +} + +func (q *chanOutQueue) enqueue(line []byte) bool { + q.mu.Lock() + if q.aborted || q.eof { + q.mu.Unlock() + return false + } + if q.buffered+len(line) > q.limit { + q.aborted = true + q.overflowed = true + q.lines = nil + q.buffered = 0 + q.cond.Broadcast() + q.mu.Unlock() + return false + } + cp := append([]byte(nil), line...) + q.lines = append(q.lines, cp) + q.buffered += len(cp) + q.cond.Signal() + q.mu.Unlock() + return true +} + +func (q *chanOutQueue) didOverflow() bool { + q.mu.Lock() + defer q.mu.Unlock() + return q.overflowed +} + +func (q *chanOutQueue) finishHolderEOF() { + q.mu.Lock() + if !q.aborted { + q.eof = true + q.cond.Broadcast() + } + q.mu.Unlock() +} + +func (q *chanOutQueue) abort() { + q.mu.Lock() + if !q.aborted { + q.aborted = true + q.lines = nil + q.buffered = 0 + q.cond.Broadcast() + } + q.mu.Unlock() +} + +func (q *chanOutQueue) pop() (line []byte, eof bool, ok bool) { + q.mu.Lock() + for len(q.lines) == 0 && !q.aborted && !q.eof { + q.cond.Wait() + } + if q.aborted { + q.mu.Unlock() + return nil, false, false + } + if len(q.lines) > 0 { + line = q.lines[0] + q.lines[0] = nil + q.lines = q.lines[1:] + q.buffered -= len(line) + if q.buffered < 0 { + q.buffered = 0 + } + eof = len(q.lines) == 0 && q.eof + q.mu.Unlock() + return line, eof, true + } + if q.eof { + q.aborted = true + q.mu.Unlock() + return nil, true, true + } + q.mu.Unlock() + return nil, false, false +} + +// Serve runs a Host-role multiplexer over tun, registers the tunnel for +// revocation and permit updates, sends the initial HELLO_ACK reflecting the +// peer's current permit, and routes accepted channels to local holders. +func Serve(ctx context.Context, tun io.ReadWriteCloser, peer Peer, cfg ServeConfig) error { + if ctx == nil { + ctx = context.Background() + } + clk := cfg.Clock + if clk == nil { + clk = RealClock() + } + road := cfg.Road + if road == "" { + road = defaultRoad + } + if road == RoadDirect { + // THE ROAD DECIDES THE LIMITS, NOT THE CALLER'S MEMORY OF THEM. The daily + // byte budget exists for the relay's cost, so a direct tunnel is neither + // counted by it nor cut by it, and a viewer that spent the day's relay + // allowance can still type on a direct path. + cfg.Budget = nil + cfg.Limits = cfg.Limits.directDefaults() + // A direct tunnel offers no further direct road. + cfg.Direct = nil + } + lim := cfg.Limits.withDefaults() + + st := &serverTunnel{ + peer: peer, + cfg: cfg, + clock: clk, + limits: lim, + road: road, + lastRead: clk.Now(), + chans: make(map[uint32]*activeChan), + ctx: ctx, + sessions: make(map[string]DirectSession), + muxReady: make(chan struct{}), + } + // A direct attempt still pending when the tunnel ends is closed with it, so a + // viewer that goes away cannot leave a peer connection half built on the host. + defer st.closeSessions() + curPermit := st.readPermit() + st.lastPermit = curPermit + + wrapped := &tunnelRWC{rwc: tun} + st.mux = NewMux(wrapped, Host, MuxConfig{ + Clock: clk, + Limits: lim, + OnFrameRead: st.onFrameRead, + OnFrameWritten: st.onFrameWritten, + OnSignal: st.onSignal, + }) + close(st.muxReady) + + if !curPermit.Watch { + _ = st.mux.SendHelloAck(HelloAck{ + V: 1, + Watch: false, + Drive: false, + Road: road, + Limits: lim, + Off: st.noWatchReason() == ReasonRemoteControlOff, + }) + st.flushAndClose() + return nil + } + + if cfg.Registry != nil { + removeReg := cfg.Registry.Add(peer.Device, st) + defer removeReg() + } + if cfg.Budget != nil { + removeBudget := cfg.Budget.addOnExhausted(func() { + st.resetAllChannels(ReasonBudget) + }) + defer removeBudget() + if cfg.Registry != nil { + removeRegBudget := cfg.Budget.addOnExhausted(cfg.Registry.onBudgetExhausted) + defer removeRegBudget() + } + } + + curPermit = st.readPermit() + st.mu.Lock() + st.lastPermit = curPermit + closing := st.closing + st.mu.Unlock() + if closing { + st.flushAndClose() + return nil + } + if !curPermit.Watch { + _ = st.mux.SendHelloAck(HelloAck{ + V: 1, + Watch: false, + Drive: false, + Road: road, + Limits: lim, + Off: st.noWatchReason() == ReasonRemoteControlOff, + }) + st.flushAndClose() + return nil + } + + drive := curPermit.Drive && (cfg.Budget == nil || !cfg.Budget.Exhausted()) + if err := st.mux.SendHelloAck(HelloAck{ + V: 1, + Watch: true, + Drive: drive, + Road: road, + Limits: lim, + Direct: st.directAdvertised(), + }); err != nil { + _ = st.mux.Close() + return nil + } + + backstopWait := lim.IdleDetach + hostBackstopExtra + initialTimer := clk.NewTimer(backstopWait) + stopBackstop := make(chan struct{}) + defer close(stopBackstop) + + guard.Go("livedoor.router.backstop", func() { + timer := initialTimer + defer func() { + if timer != nil { + timer.Stop() + } + }() + for { + select { + case <-timer.C(): + st.mu.Lock() + elapsed := clk.Now().Sub(st.lastRead) + st.mu.Unlock() + if elapsed >= backstopWait { + // A RELAY TUNNEL THAT IS A SILENT STANDBY IS NOT DEAD. While a + // direct tunnel of the same device is registered the viewer + // sends nothing on the relay on purpose (the Durable Object + // keeps hibernating), so silence here is the design. The + // exemption is derived from the registry, with no message, and + // ends the next time the timer fires after the direct tunnel + // is gone. + if st.standbyExempt() { + timer = clk.NewTimer(hostBackstopExtra) + continue + } + _ = st.mux.Close() + return + } + rem := backstopWait - elapsed + if rem <= 0 { + rem = time.Nanosecond + } + timer = clk.NewTimer(rem) + case <-st.mux.Done(): + return + case <-stopBackstop: + return + case <-ctx.Done(): + _ = st.mux.Close() + return + } + } + }) + + var wg sync.WaitGroup + for { + ch, req, err := st.mux.Accept(ctx) + if err != nil { + break + } + wg.Add(1) + guard.Go("livedoor.router.channel", func() { + defer wg.Done() + st.serveChannel(ctx, ch, req) + }) + } + + _ = st.mux.Close() + wg.Wait() + return nil +} + +func (st *serverTunnel) maxTunnelsPerDevice() int { + return st.limits.MaxTunnelsPerDevice +} + +// roadName is the road this tunnel arrived on; the registry caps tunnels and +// skips the budget reset per road with it. +func (st *serverTunnel) roadName() string { + return st.road +} + +// standbyExempt reports whether this relay tunnel's silence is excused because +// a direct tunnel of the same device is open. +func (st *serverTunnel) standbyExempt() bool { + return st.road != RoadDirect && st.cfg.Registry != nil && st.cfg.Registry.HasRoad(st.peer.Device, RoadDirect) +} + +// directAdvertised is what the HelloAck says about the direct road: yes only +// for a relay tunnel whose host has a direct half to answer with and room for +// another direct tunnel. +func (st *serverTunnel) directAdvertised() bool { + if st.road != RoadRelay || st.cfg.Direct == nil { + return false + } + return st.cfg.Registry == nil || st.cfg.Registry.countRoad(RoadDirect) < MaxDirect +} + +// muxSignaller sends a host's signalling frames over the relay link they +// belong to. +type muxSignaller struct{ m *Mux } + +func (s muxSignaller) Send(payload []byte) error { return s.m.SendSignal(payload) } + +// onSignal handles one signalling payload from the viewer. It runs on the +// link's reader goroutine, so it only decides, hands over, and answers; the +// peer-to-peer work happens behind the DirectHost. +// +// A payload that does not decode is dropped: the mux has already bounded its +// size and rate, and a viewer cannot make a host do anything with a frame this +// code does not understand. Frames for an attempt this tunnel does not have +// pending are dropped too, which is what keeps a stale attempt's late candidates +// from reaching a new one. +func (st *serverTunnel) onSignal(payload []byte) { + sig, err := DecodeSignal(payload) + if err != nil || sig.ID == "" { + return + } + select { + case <-st.muxReady: + case <-st.ctx.Done(): + return + } + switch sig.T { + case SignalOffer: + st.onOffer(sig, payload) + case SignalCandidate: + st.mu.Lock() + session := st.sessions[sig.ID] + st.mu.Unlock() + if session != nil { + session.Deliver(payload) + } + case SignalEnd: + st.endSession(sig.ID) + } +} + +// onOffer answers an offer by refusing it before anything is allocated, or by +// handing it to the host's direct half. A new offer from a viewer SUPERSEDES +// its earlier pending one, because a viewer that retried after a lost `end` +// must not be locked out by its own dead attempt. +func (st *serverTunnel) onOffer(sig Signal, payload []byte) { + refuse := func(reason string) { + if raw, err := EncodeSignal(Signal{T: SignalRefuse, ID: sig.ID, Reason: reason}); err == nil { + _ = st.mux.SendSignal(raw) + } + } + switch { + case st.road != RoadRelay: + refuse(RefuseOff) + return + // THE PERMIT IS READ AGAIN, because an edit that took watching away may not + // have reached this tunnel yet (the watcher runs on a timer), and a direct + // attempt is real work the host would do for a device it no longer lets in. + case !st.readPermit().Watch: + refuse(RefuseOff) + return + case st.cfg.Direct == nil: + refuse(RefuseRelayOnly) + return + case st.cfg.Registry != nil && st.cfg.Registry.countRoad(RoadDirect) >= MaxDirect: + refuse(RefuseBusy) + return + } + st.mu.Lock() + closing := st.closing + st.mu.Unlock() + if closing { + return + } + st.closeSessions() + session := st.cfg.Direct.Offered(st.ctx, st.peer, payload, muxSignaller{st.mux}) + if session == nil { + refuse(RefuseBusy) + return + } + st.mu.Lock() + if st.closing { + st.mu.Unlock() + session.Close() + return + } + st.sessions[sig.ID] = session + st.mu.Unlock() +} + +// endSession closes one pending attempt, if this tunnel has it. +func (st *serverTunnel) endSession(id string) { + st.mu.Lock() + session := st.sessions[id] + delete(st.sessions, id) + st.mu.Unlock() + if session != nil { + session.Close() + } +} + +// closeSessions closes every pending attempt of this tunnel. +func (st *serverTunnel) closeSessions() { + st.mu.Lock() + sessions := st.sessions + st.sessions = make(map[string]DirectSession) + st.mu.Unlock() + for _, session := range sessions { + session.Close() + } +} + +func (st *serverTunnel) readPermit() pair.Permit { + if st.cfg.Permit != nil { + return st.cfg.Permit(st.peer.Device) + } + return st.peer.Permit +} + +func (st *serverTunnel) onFrameRead(n int) { + st.mu.Lock() + st.lastRead = st.clock.Now() + st.mu.Unlock() + if st.cfg.Budget != nil && n > 0 { + st.cfg.Budget.Charge(int64(n)) + } +} + +func (st *serverTunnel) onFrameWritten(n int) { + if st.cfg.Budget != nil && n > 0 { + st.cfg.Budget.Charge(int64(n)) + } +} + +func (st *serverTunnel) flushAndClose() { + m := st.mux + if m == nil { + return + } + m.mu.Lock() + if m.closed { + m.mu.Unlock() + return + } + m.enqueueControlLocked(frame{op: opFlushClose}) + m.mu.Unlock() + + select { + case <-m.Done(): + case <-time.After(50 * time.Millisecond): + _ = m.Close() + } +} + +func (st *serverTunnel) CloseWithReason(reason string) { + st.mu.Lock() + st.closing = true + st.mu.Unlock() + st.closeSessions() + st.mu.Lock() + active := make([]*activeChan, 0, len(st.chans)) + for _, ac := range st.chans { + active = append(active, ac) + } + st.mu.Unlock() + + for _, ac := range active { + _ = ac.ch.Reset(reason) + } + + if m := st.mux; m != nil { + m.mu.Lock() + muxChans := make([]*Channel, 0, len(m.channels)) + for _, ch := range m.channels { + muxChans = append(muxChans, ch) + } + m.mu.Unlock() + + for _, ch := range muxChans { + m.mu.Lock() + pending := ch.pendingAccept + m.mu.Unlock() + if pending { + _ = ch.Refuse(reason) + } else { + _ = ch.Reset(reason) + } + } + } + + for _, ac := range active { + ac.closeHolderAndQueue() + } + + st.flushAndClose() +} + +// noWatchReason is the reason a view is ended with when the permit read just now +// no longer lets its computer watch: remote control being off, when it is, else +// the permit having changed. +func (st *serverTunnel) noWatchReason() string { + if st.cfg.Off != nil && st.cfg.Off() { + return ReasonRemoteControlOff + } + return ReasonPermitChanged +} + +func (st *serverTunnel) PermitsChanged() { + cur := st.readPermit() + if !cur.Watch { + st.CloseWithReason(st.noWatchReason()) + return + } + st.mu.Lock() + wasDrive := st.lastPermit.Drive + st.lastPermit = cur + active := make([]*activeChan, 0, len(st.chans)) + for _, ac := range st.chans { + active = append(active, ac) + } + st.mu.Unlock() + + if !cur.Drive { + for _, ac := range active { + if wasDrive || ac.isDrive() { + _ = ac.ch.Reset(ReasonPermitChanged) + ac.closeHolderAndQueue() + } + } + } +} + +func (st *serverTunnel) resetAllChannels(reason string) { + st.mu.Lock() + active := make([]*activeChan, 0, len(st.chans)) + for _, ac := range st.chans { + active = append(active, ac) + } + st.mu.Unlock() + + for _, ac := range active { + _ = ac.ch.Reset(reason) + ac.closeHolderAndQueue() + } + + if m := st.mux; m != nil { + m.mu.Lock() + muxChans := make([]*Channel, 0, len(m.channels)) + for _, ch := range m.channels { + muxChans = append(muxChans, ch) + } + m.mu.Unlock() + + for _, ch := range muxChans { + m.mu.Lock() + pending := ch.pendingAccept + m.mu.Unlock() + if pending { + _ = ch.Refuse(reason) + } else { + _ = ch.Reset(reason) + } + } + } +} + +func (st *serverTunnel) serveChannel(ctx context.Context, ch *Channel, req OpenRequest) { + // 2a. Resolve the running chat holder; THE LIVE DOOR NEVER STARTS A CHAT. + if st.cfg.Resolver == nil { + _ = ch.Refuse(ReasonNotRunning) + return + } + holderConn, route, err := st.cfg.Resolver.Resolve(ctx, req.Chat) + if err != nil || holderConn == nil { + if holderConn != nil { + _ = holderConn.Close() + } + _ = ch.Refuse(ReasonNotRunning) + return + } + + curPermit := st.readPermit() + ac := &activeChan{ + ch: ch, + holderConn: holderConn, + drive: curPermit.Drive, + } + st.mu.Lock() + if st.closing { + st.mu.Unlock() + _ = holderConn.Close() + _ = ch.Refuse(ReasonHostClosing) + return + } + st.chans[ch.ID()] = ac + st.mu.Unlock() + + spliceDone := make(chan struct{}) + defer func() { + close(spliceDone) + st.mu.Lock() + delete(st.chans, ch.ID()) + st.mu.Unlock() + ac.closeHolderAndQueue() + }() + + // 2b. Accept the channel and read the viewer's initial hello line bounded by FirstLineMax. + if err := ch.Accept(); err != nil { + return + } + + guard.Go("livedoor.router.chanWatch", func() { + select { + case <-ch.Done(): + ac.closeHolderAndQueue() + case <-ctx.Done(): + ac.closeHolderAndQueue() + case <-spliceDone: + } + }) + + viewerScan := newLineScanner(ch, st.limits.MaxLine) + firstLine, err := viewerScan.ReadLine(st.limits.FirstLineMax) + if err != nil { + if errors.Is(err, errLineTooLong) || errors.Is(err, errNoNewline) { + _ = ch.Reset(ReasonFrameTooLarge) + } + return + } + + var firstFrame remote.Frame + if err := json.Unmarshal(bytes.TrimRight(firstLine, "\r\n"), &firstFrame); err != nil || firstFrame.Kind != "hello" { + _ = ch.Reset(ReasonNotAllowed) + return + } + var viewerHello remote.Hello + if len(firstFrame.Payload) > 0 { + if err := json.Unmarshal(firstFrame.Payload, &viewerHello); err != nil { + _ = ch.Reset(ReasonNotAllowed) + return + } + } + + // 2c. Rewrite Hello from the authenticated peer state, discarding any viewer + // claim over Session, Workspace, Join, New, Watch, Back, or Remote. + curPermit = st.readPermit() + if !curPermit.Watch { + _ = ch.Reset(st.noWatchReason()) + return + } + exhausted := st.cfg.Budget != nil && st.cfg.Budget.Exhausted() + drive := curPermit.Drive && !exhausted + ac.setDrive(drive) + + stamp := remote.RemoteViewer{ + Device: st.peer.Device, + Label: st.peer.Label, + Watch: true, + Drive: drive, + Road: st.road, + } + rewrittenHello := remote.Hello{ + Version: viewerHello.Version, + Workspace: route.Workspace, + Session: route.Session, + SessionInstance: viewerHello.SessionInstance, + Encodings: viewerHello.Encodings, + Resume: viewerHello.Resume, + Surface: viewerHello.Surface, + ClientID: viewerHello.ClientID, + Back: true, + Join: true, + New: false, + Watch: !drive, + Remote: &stamp, + } + rewrittenPayload, err := json.Marshal(rewrittenHello) + if err != nil { + _ = ch.Reset(ReasonNotRunning) + return + } + rewrittenLine, err := json.Marshal(remote.Frame{ + Kind: "hello", + Payload: rewrittenPayload, + }) + if err != nil { + _ = ch.Reset(ReasonNotRunning) + return + } + if _, err := holderConn.Write(append(rewrittenLine, '\n')); err != nil { + if !channelEnded(ch) { + _ = ch.CloseWithReason(ReasonHolderGone) + } + return + } + + // 2d. D10: Read and verify the holder's stamped welcome BEFORE any viewer + // byte after the hello is read or forwarded to the holder. + welcomeCap := remote.DefaultMaxLine + if st.limits.MaxLine > 0 && st.limits.MaxLine < welcomeCap { + welcomeCap = st.limits.MaxLine + } + holderScanCap := st.limits.MaxLine + if holderScanCap < welcomeCap { + holderScanCap = welcomeCap + } + holderScan := newLineScanner(holderConn, holderScanCap) + replyLine, err := holderScan.ReadLine(welcomeCap) + if err != nil { + if errors.Is(err, errLineTooLong) { + _ = ch.Reset(ReasonFrameTooLarge) + } else if !channelEnded(ch) { + _ = ch.Reset(ReasonNotRunning) + } + return + } + + var replyFrame remote.Frame + if err := json.Unmarshal(bytes.TrimRight(replyLine, "\r\n"), &replyFrame); err != nil { + _ = ch.Reset(ReasonNotRunning) + return + } + if replyFrame.Kind != "welcome" { + _ = ch.Reset(ReasonNotRunning) + return + } + var welcome remote.Welcome + if err := json.Unmarshal(replyFrame.Payload, &welcome); err != nil { + _ = ch.Reset(ReasonNotRunning) + return + } + if welcome.Remote == nil || *welcome.Remote != stamp { + _ = ch.Reset(ReasonHolderOld) + return + } + + // 2e & 3. Forward the verified welcome and splice in both directions through + // the policy scanners and bounded outbound queue. + outQ := newChanOutQueue(st.limits.QueueMax) + ac.setOutQueue(outQ) + if !outQ.enqueue(replyLine) { + if outQ.didOverflow() && !channelEnded(ch) { + _ = ch.Reset(ReasonLagging) + } + return + } + + var childWG sync.WaitGroup + childWG.Add(2) + + // Single writer goroutine draining outQ into ch so the holder reader never + // blocks on viewer consumption. + guard.Go("livedoor.router.chanWriter", func() { + defer childWG.Done() + for { + line, eof, ok := outQ.pop() + if !ok { + return + } + if len(line) > 0 { + if _, wErr := ch.Write(line); wErr != nil { + ac.closeHolderAndQueue() + return + } + } + if eof { + if !channelEnded(ch) { + _ = ch.CloseWithReason(ReasonHolderGone) + } + ac.closeHolderAndQueue() + return + } + } + }) + + // Viewer -> holder policy scanner. + guard.Go("livedoor.router.viewerToHolder", func() { + defer childWG.Done() + for { + vLine, rErr := viewerScan.ReadLine(st.limits.MaxLine) + if rErr != nil { + if errors.Is(rErr, errLineTooLong) || errors.Is(rErr, errNoNewline) { + outQ.abort() + _ = ch.Reset(ReasonFrameTooLarge) + } else { + outQ.abort() + } + _ = holderConn.Close() + return + } + act, refusalLine := classifyViewerLine(vLine, st.cfg.Host, drive) + switch act { + case viewerLineForward: + if _, wErr := holderConn.Write(vLine); wErr != nil { + return + } + case viewerLineRefuse: + if !outQ.enqueue(refusalLine) { + if outQ.didOverflow() && !channelEnded(ch) { + _ = ch.Reset(ReasonLagging) + } + ac.closeHolderAndQueue() + return + } + case viewerLineDrop: + st.droppedFrames.Add(1) + } + } + }) + + // Holder -> viewer bounded line scanner. + for { + hLine, rErr := holderScan.ReadLine(st.limits.MaxLine) + if rErr != nil { + if errors.Is(rErr, errLineTooLong) { + outQ.abort() + _ = ch.Reset(ReasonFrameTooLarge) + _ = holderConn.Close() + break + } + if !channelEnded(ch) { + outQ.finishHolderEOF() + } else { + outQ.abort() + } + break + } + if !outQ.enqueue(hLine) { + if outQ.didOverflow() && !channelEnded(ch) { + _ = ch.Reset(ReasonLagging) + } + ac.closeHolderAndQueue() + break + } + } + + childWG.Wait() +} + +func channelEnded(ch *Channel) bool { + select { + case <-ch.Done(): + return true + default: + return false + } +} diff --git a/internal/livedoor/scan.go b/internal/livedoor/scan.go new file mode 100644 index 0000000000..e7e4b6ba2d --- /dev/null +++ b/internal/livedoor/scan.go @@ -0,0 +1,156 @@ +package livedoor + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "strings" + + "github.com/Agent-Field/codeaf/internal/remote" +) + +var ( + errLineTooLong = errors.New("livedoor: line exceeds maximum length") + errNoNewline = errors.New("livedoor: line ended without a newline") +) + +const initialScanBuffer = 4096 + +// lineScanner reads newline-delimited EventWire JSON lines from r while never +// allocating a buffer larger than maxCap + 1 bytes. +type lineScanner struct { + r io.Reader + maxCap int + buf []byte + rpos int + wpos int +} + +func newLineScanner(r io.Reader, maxCap int) *lineScanner { + if maxCap <= 0 { + maxCap = MaxLine + } + initCap := initialScanBuffer + if initCap > maxCap+1 { + initCap = maxCap + 1 + } + return &lineScanner{ + r: r, + maxCap: maxCap, + buf: make([]byte, initCap), + } +} + +// ReadLine returns the next newline-terminated line (including its trailing '\n') +// whose content before '\n' is at most limit bytes. If more than limit bytes +// arrive before '\n', ReadLine returns errLineTooLong without allocating beyond +// maxCap + 1 bytes. +func (s *lineScanner) ReadLine(limit int) ([]byte, error) { + if limit <= 0 || limit > s.maxCap { + limit = s.maxCap + } + for { + unconsumed := s.buf[s.rpos:s.wpos] + if idx := bytes.IndexByte(unconsumed, '\n'); idx >= 0 { + if idx > limit { + return nil, errLineTooLong + } + line := unconsumed[:idx+1] + s.rpos += idx + 1 + return line, nil + } + + have := s.wpos - s.rpos + if have > limit { + return nil, errLineTooLong + } + + if s.rpos > 0 { + copy(s.buf, s.buf[s.rpos:s.wpos]) + s.wpos = have + s.rpos = 0 + } + + maxBuf := s.maxCap + 1 + if len(s.buf) == s.wpos { + if len(s.buf) >= maxBuf { + return nil, errLineTooLong + } + newCap := len(s.buf) * 2 + if newCap < initialScanBuffer { + newCap = initialScanBuffer + } + if newCap > maxBuf { + newCap = maxBuf + } + next := make([]byte, newCap) + copy(next, s.buf[:s.wpos]) + s.buf = next + } + + readCap := limit + 1 + if readCap > len(s.buf) { + readCap = len(s.buf) + } + n, err := s.r.Read(s.buf[s.wpos:readCap]) + s.wpos += n + if n > 0 { + continue + } + if err != nil { + if errors.Is(err, io.EOF) { + if s.wpos-s.rpos == 0 { + return nil, io.EOF + } + return nil, errNoNewline + } + return nil, err + } + } +} + +type viewerFrameHeader struct { + Kind string `json:"kind"` + ID uint64 `json:"id,omitempty"` + Method string `json:"method,omitempty"` +} + +type viewerLineAction int + +const ( + viewerLineForward viewerLineAction = iota + viewerLineRefuse + viewerLineDrop +) + +// classifyViewerLine inspects a single post-handshake line from a remote viewer +// and applies the default-deny frame-kind and method policy. Only well-formed +// "call" frames are eligible; calls prohibited by remote.GuestMay produce a +// synthesized result frame with the same ID and the host's refusal sentence. +func classifyViewerLine(line []byte, host string, drive bool) (viewerLineAction, []byte) { + trimmed := bytes.TrimRight(line, "\r\n") + var hdr viewerFrameHeader + if err := json.Unmarshal(trimmed, &hdr); err != nil { + return viewerLineDrop, nil + } + if hdr.Kind != "call" { + return viewerLineDrop, nil + } + method := strings.TrimSpace(hdr.Method) + if method == "" { + return viewerLineDrop, nil + } + if remote.GuestMay(method, drive) { + return viewerLineForward, nil + } + reply, err := json.Marshal(remote.Frame{ + Kind: "result", + ID: hdr.ID, + Error: remote.GuestRefusal(host, method, drive), + }) + if err != nil { + return viewerLineDrop, nil + } + return viewerLineRefuse, append(reply, '\n') +} diff --git a/internal/livedoor/serve_direct_test.go b/internal/livedoor/serve_direct_test.go new file mode 100644 index 0000000000..51d6b5cb0f --- /dev/null +++ b/internal/livedoor/serve_direct_test.go @@ -0,0 +1,804 @@ +package livedoor + +import ( + "bytes" + "context" + "encoding/json" + "net" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/remote" +) + +// fakeDirectSession is the host half's record of one pending attempt: what was +// delivered to it, in order, and whether it was closed. +type fakeDirectSession struct { + mu sync.Mutex + delivered [][]byte + closed chan struct{} + once sync.Once +} + +func newFakeDirectSession() *fakeDirectSession { + return &fakeDirectSession{closed: make(chan struct{})} +} + +func (s *fakeDirectSession) Deliver(p []byte) { + s.mu.Lock() + s.delivered = append(s.delivered, append([]byte(nil), p...)) + s.mu.Unlock() +} +func (s *fakeDirectSession) Close() { s.once.Do(func() { close(s.closed) }) } + +func (s *fakeDirectSession) deliveries() [][]byte { + s.mu.Lock() + defer s.mu.Unlock() + return append([][]byte(nil), s.delivered...) +} + +func (s *fakeDirectSession) isClosed() bool { + select { + case <-s.closed: + return true + default: + return false + } +} + +// fakeDirectHost records every offer it is handed. It answers with a session, or +// with nil (a refusal) when refuse is set. +type fakeDirectHost struct { + mu sync.Mutex + refuse bool + devices []string + payloads [][]byte + sessions []*fakeDirectSession + signals []Signaller +} + +func (f *fakeDirectHost) Offered(_ context.Context, peer Peer, offer []byte, s Signaller) DirectSession { + f.mu.Lock() + defer f.mu.Unlock() + f.devices = append(f.devices, peer.Device) + f.payloads = append(f.payloads, append([]byte(nil), offer...)) + f.signals = append(f.signals, s) + if f.refuse { + return nil + } + session := newFakeDirectSession() + f.sessions = append(f.sessions, session) + return session +} + +func (f *fakeDirectHost) offers() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.devices) +} + +func (f *fakeDirectHost) session(i int) *fakeDirectSession { + f.mu.Lock() + defer f.mu.Unlock() + return f.sessions[i] +} + +// fakeRoadTunnel is a registry entry with a road and nothing else, for the +// registry's own rules. +type fakeRoadTunnel struct { + road string + reasons chan string + permits atomic.Int64 +} + +func newFakeRoadTunnel(road string) *fakeRoadTunnel { + return &fakeRoadTunnel{road: road, reasons: make(chan string, 4)} +} +func (f *fakeRoadTunnel) CloseWithReason(reason string) { f.reasons <- reason } +func (f *fakeRoadTunnel) PermitsChanged() { f.permits.Add(1) } +func (f *fakeRoadTunnel) roadName() string { return f.road } + +func (f *fakeRoadTunnel) closedWith() (string, bool) { + select { + case reason := <-f.reasons: + return reason, true + default: + return "", false + } +} + +// signalRig is one host tunnel over a pipe and the viewer's end of it. +type signalRig struct { + v *Mux + ack HelloAck + inbox *signalInbox + done chan error + pongs atomic.Int64 +} + +// startTunnel serves one tunnel for peer under cfg and returns the viewer's side +// once the host's HelloAck has arrived. +func startTunnel(t *testing.T, ctx context.Context, peer Peer, cfg ServeConfig) *signalRig { + t.Helper() + vConn, hConn := net.Pipe() + t.Cleanup(func() { _ = vConn.Close(); _ = hConn.Close() }) + rig := &signalRig{inbox: newSignalInbox(), done: make(chan error, 1)} + guard.Go("livedoor.test.direct.serve", func() { rig.done <- Serve(ctx, hConn, peer, cfg) }) + rig.v = NewMux(vConn, Viewer, MuxConfig{Clock: cfg.Clock, OnSignal: rig.inbox.onSignal, OnPong: func(uint32) { rig.pongs.Add(1) }}) + t.Cleanup(func() { _ = rig.v.Close() }) + ack, err := rig.v.WaitHelloAck(ctx) + if err != nil { + t.Fatalf("WaitHelloAck: %v", err) + } + rig.ack = ack + return rig +} + +func (r *signalRig) send(t *testing.T, s Signal) []byte { + t.Helper() + payload, err := EncodeSignal(s) + if err != nil { + t.Fatal(err) + } + if err := r.v.SendSignal(payload); err != nil { + t.Fatal(err) + } + return payload +} + +// roundTrip sends a ping and waits for its pong. The host answers in the order it +// handled frames, so everything it queued before that pong has already been read +// by the viewer: a way to prove that something did NOT arrive. +func (r *signalRig) roundTrip(t *testing.T) { + t.Helper() + want := r.pongs.Load() + 1 + if err := r.v.SendPing(uint32(want)); err != nil { + t.Fatal(err) + } + eventually(t, "the host to answer a ping", func() bool { return r.pongs.Load() >= want }) +} + +func watchPeer(device string) Peer { + return Peer{Device: device, Label: device, Permit: pair.Permit{Watch: true, Drive: true}} +} + +func expectSignal(t *testing.T, inbox *signalInbox) Signal { + t.Helper() + sig, err := DecodeSignal(inbox.take(t)) + if err != nil { + t.Fatalf("the host sent a signal that does not decode: %v", err) + } + return sig +} + +// V38: the HelloAck advertises the direct road only when the host has a direct +// half, the tunnel is a relay tunnel, the viewer is allowed to watch, and the host +// has room for another direct tunnel. +func TestHelloAckAdvertisesDirectOnlyWhenTheHostAllows(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host := &fakeDirectHost{} + + if ack := startTunnel(t, ctx, watchPeer("dev-a"), ServeConfig{Host: "h"}).ack; ack.Direct { + t.Fatal("a host with no direct half advertised the direct road") + } + if ack := startTunnel(t, ctx, watchPeer("dev-b"), ServeConfig{Host: "h", Direct: host}).ack; !ack.Direct { + t.Fatal("a host with a direct half did not advertise the direct road") + } + if ack := startTunnel(t, ctx, watchPeer("dev-c"), ServeConfig{Host: "h", Direct: host, Road: RoadDirect}).ack; ack.Direct || ack.Road != RoadDirect { + t.Fatalf("a direct tunnel's ack = %+v, want road direct and no further offer", ack) + } + noWatch := Peer{Device: "dev-d", Label: "d", Permit: pair.Permit{Watch: false}} + if ack := startTunnel(t, ctx, noWatch, ServeConfig{Host: "h", Direct: host}).ack; ack.Direct || ack.Watch { + t.Fatalf("a peer that may not watch was offered the direct road: %+v", ack) + } + + full := NewRegistry() + var removers []func() + for i := 0; i < MaxDirect; i++ { + removers = append(removers, full.Add("dev-full-"+string(rune('a'+i)), newFakeRoadTunnel(RoadDirect))) + } + if ack := startTunnel(t, ctx, watchPeer("dev-e"), ServeConfig{Host: "h", Direct: host, Registry: full}).ack; ack.Direct { + t.Fatalf("a host holding %d direct tunnels still advertised the direct road", MaxDirect) + } + removers[0]() + if ack := startTunnel(t, ctx, watchPeer("dev-f"), ServeConfig{Host: "h", Direct: host, Registry: full}).ack; !ack.Direct { + t.Fatal("a host with one direct slot free did not advertise the direct road") + } + for _, remove := range removers { + remove() + } +} + +// V38: an older host never advertises and an older viewer ignores the field, so +// nobody offers to a host that cannot answer; a signal an older host does not +// understand is skipped and the link carries on. +func TestAnOlderHostThatAdvertisesNothingIsNeverOffered(t *testing.T) { + older, err := json.Marshal(HelloAck{V: 1, Watch: true, Drive: true, Road: RoadRelay}) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(older, []byte(`"direct"`)) { + t.Fatalf("an ack with no direct half carries the field anyway: %s", older) + } + var ack HelloAck + if err := json.Unmarshal([]byte(`{"v":1,"watch":true,"drive":true,"road":"relay","limits":{}}`), &ack); err != nil || ack.Direct { + t.Fatalf("an older host's ack read as %+v, %v; want Direct=false", ack, err) + } + var newer HelloAck + if err := json.Unmarshal([]byte(`{"v":1,"watch":true,"drive":false,"road":"relay","limits":{},"direct":true,"a_field_from_the_future":9}`), &newer); err != nil || !newer.Direct { + t.Fatalf("a newer host's ack read as %+v, %v; want Direct=true and the unknown field ignored", newer, err) + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + rig := startTunnel(t, ctx, watchPeer("dev-old"), ServeConfig{Host: "h"}) + // A host with no direct half, handed junk and a signal it has no use for, + // answers neither and keeps the link up. + if err := rig.v.SendSignal([]byte("not json at all")); err != nil { + t.Fatal(err) + } + rig.send(t, Signal{T: SignalCandidate, ID: "nobody", C: "x"}) + if err := rig.v.SendPing(9); err != nil { + t.Fatal(err) + } + select { + case <-rig.v.Done(): + t.Fatal("a signal the host had no use for ended the link") + case <-time.After(50 * time.Millisecond): + } +} + +// V36 / V38: an offer is refused with a closed word and NOTHING is allocated when +// the host has no direct half (relay-only), when its half says no (busy), when +// the host holds MaxDirect tunnels, and when it arrives on a direct tunnel. +func TestAnOfferIsRefusedWhenTheRoadIsRelayOnlyAndNothingIsAllocated(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + t.Run("no direct half", func(t *testing.T) { + rig := startTunnel(t, ctx, watchPeer("dev-1"), ServeConfig{Host: "h"}) + rig.send(t, Signal{T: SignalOffer, ID: "attempt-1", SDP: "v=0"}) + got := expectSignal(t, rig.inbox) + if got.T != SignalRefuse || got.Reason != RefuseRelayOnly || got.ID != "attempt-1" { + t.Fatalf("the answer was %+v, want refuse relay-only for attempt-1", got) + } + }) + t.Run("the direct half says no", func(t *testing.T) { + host := &fakeDirectHost{refuse: true} + rig := startTunnel(t, ctx, watchPeer("dev-2"), ServeConfig{Host: "h", Direct: host}) + rig.send(t, Signal{T: SignalOffer, ID: "attempt-2", SDP: "v=0"}) + if got := expectSignal(t, rig.inbox); got.T != SignalRefuse || got.Reason != RefuseBusy { + t.Fatalf("the answer was %+v, want refuse busy", got) + } + if host.offers() != 1 { + t.Fatalf("the host half was asked %d times, want once", host.offers()) + } + }) + t.Run("the host already holds its direct tunnels", func(t *testing.T) { + host := &fakeDirectHost{} + full := NewRegistry() + for i := 0; i < MaxDirect; i++ { + full.Add("full-"+string(rune('a'+i)), newFakeRoadTunnel(RoadDirect)) + } + // A host that advertised just before it filled up, as a race can have it, + // still refuses the offer; with a full registry the ack itself says no + // direct, which the viewer is free to ignore. + rigFull := startTunnel(t, ctx, watchPeer("dev-3"), ServeConfig{Host: "h", Direct: host, Registry: full}) + rigFull.send(t, Signal{T: SignalOffer, ID: "attempt-3", SDP: "v=0"}) + if got := expectSignal(t, rigFull.inbox); got.T != SignalRefuse || got.Reason != RefuseBusy { + t.Fatalf("the answer was %+v, want refuse busy", got) + } + if host.offers() != 0 { + t.Fatalf("the host half was asked %d times while full, want never", host.offers()) + } + }) + t.Run("an offer on a direct tunnel", func(t *testing.T) { + host := &fakeDirectHost{} + rig := startTunnel(t, ctx, watchPeer("dev-4"), ServeConfig{Host: "h", Direct: host, Road: RoadDirect}) + rig.send(t, Signal{T: SignalOffer, ID: "attempt-4", SDP: "v=0"}) + if got := expectSignal(t, rig.inbox); got.T != SignalRefuse || got.Reason != RefuseOff { + t.Fatalf("the answer was %+v, want refuse off", got) + } + if host.offers() != 0 { + t.Fatal("a direct tunnel's offer reached the host half") + } + }) +} + +// V34: an offer is refused, with nothing allocated, when the host has already +// taken watching away from the peer, even before the permit watcher has told the +// tunnel to close. +func TestAnOfferFromAPeerWhoseWatchWasTakenAwayIsRefusedBeforeAnythingIsAllocated(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host := &fakeDirectHost{} + var watching atomic.Bool + watching.Store(true) + permit := func(string) pair.Permit { return pair.Permit{Watch: watching.Load(), Drive: true} } + rig := startTunnel(t, ctx, watchPeer("dev-edited"), ServeConfig{Host: "h", Direct: host, Permit: permit}) + if !rig.ack.Direct { + t.Fatal("the host did not advertise the direct road to a peer that may watch") + } + watching.Store(false) + rig.send(t, Signal{T: SignalOffer, ID: "too-late", SDP: "v=0"}) + if got := expectSignal(t, rig.inbox); got.T != SignalRefuse || got.Reason != RefuseOff { + t.Fatalf("the answer was %+v, want refuse off", got) + } + if host.offers() != 0 { + t.Fatal("the host half was asked to answer a peer that may no longer watch") + } +} + +// V30 (router half): an offer reaches the host half with the AUTHENTICATED peer +// and the payload untouched, later candidates of the same attempt reach its +// session in order, a candidate for another attempt is dropped, the host's own +// signals go back through the same link, `end` closes the session, and a new +// offer from the same viewer supersedes the pending one. +func TestAnOfferIsHandedToTheHostAndLaterSignalsReachItsSessionInOrder(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host := &fakeDirectHost{} + rig := startTunnel(t, ctx, watchPeer("dev-real"), ServeConfig{Host: "h", Direct: host}) + + offer := rig.send(t, Signal{T: SignalOffer, ID: "first", SDP: "v=0 offer"}) + eventually(t, "the host half to be offered", func() bool { return host.offers() == 1 }) + host.mu.Lock() + gotDevice, gotPayload, signaller := host.devices[0], host.payloads[0], host.signals[0] + host.mu.Unlock() + if gotDevice != "dev-real" || !bytes.Equal(gotPayload, offer) { + t.Fatalf("offered device %q payload %q; want the authenticated peer and the payload as sent", gotDevice, gotPayload) + } + + for _, c := range []string{"c1", "c2", "c3"} { + rig.send(t, Signal{T: SignalCandidate, ID: "first", C: c}) + } + rig.send(t, Signal{T: SignalCandidate, ID: "someone-else", C: "stray"}) + first := host.session(0) + eventually(t, "three candidates to arrive", func() bool { return len(first.deliveries()) == 3 }) + for i, want := range []string{"c1", "c2", "c3"} { + sig, err := DecodeSignal(first.deliveries()[i]) + if err != nil || sig.C != want { + t.Fatalf("delivery %d = %+v, %v; want candidate %q in order", i, sig, err, want) + } + } + + answer, err := EncodeSignal(Signal{T: SignalAnswer, ID: "first", SDP: "v=0 answer"}) + if err != nil { + t.Fatal(err) + } + if err := signaller.Send(answer); err != nil { + t.Fatal(err) + } + if got := expectSignal(t, rig.inbox); got.T != SignalAnswer || got.SDP != "v=0 answer" { + t.Fatalf("the viewer got %+v from the host's signaller", got) + } + + rig.send(t, Signal{T: SignalOffer, ID: "second", SDP: "v=0 again"}) + eventually(t, "the second offer to reach the host half", func() bool { return host.offers() == 2 }) + eventually(t, "the first session to be closed by its successor", first.isClosed) + if len(first.deliveries()) != 3 { + t.Fatalf("the superseded session saw %d deliveries, want its original three", len(first.deliveries())) + } + + second := host.session(1) + rig.send(t, Signal{T: SignalEnd, ID: "second"}) + eventually(t, "`end` to close the session", second.isClosed) +} + +// V34: a pending direct attempt dies with its relay tunnel, so a viewer that goes +// away, is removed, or whose tunnel is closed by the host cannot leave a peer +// connection half built; and once the tunnel is closing a late offer is ignored. +func TestARemovedDeviceCannotOpenADirectRoad(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + reg := NewRegistry() + host := &fakeDirectHost{} + rig := startTunnel(t, ctx, watchPeer("dev-gone"), ServeConfig{Host: "h", Direct: host, Registry: reg}) + + rig.send(t, Signal{T: SignalOffer, ID: "mid-setup", SDP: "v=0"}) + eventually(t, "the offer to reach the host half", func() bool { return host.offers() == 1 }) + session := host.session(0) + + reg.Revoke("dev-gone") + eventually(t, "a revoked device's pending attempt to be closed", session.isClosed) + select { + case <-rig.done: + case <-time.After(5 * time.Second): + t.Fatal("the revoked tunnel did not end") + } + + // The viewer's end of a revoked tunnel is gone too, so a late offer has + // nowhere to go and says so, and nothing more reaches the host half. (The + // door refuses the same device's NEXT direct tunnel before Noise: that is + // filesdoor's TestARemovedDeviceLosesItsDirectStreamAndCannotOpenAnother.) + select { + case <-rig.v.Done(): + case <-time.After(5 * time.Second): + t.Fatal("the viewer's link outlived a revoked tunnel") + } + if err := rig.v.SendSignal([]byte(`{"v":1,"t":"offer","id":"late","sdp":"v=0"}`)); err == nil { + t.Fatal("a signal was accepted on a link that has been closed") + } + if host.offers() != 1 { + t.Fatalf("an offer on a revoked tunnel reached the host half (%d offers)", host.offers()) + } +} + +// V34: a pending direct attempt is closed when its relay tunnel simply ends. +func TestAClosingTunnelClosesItsPendingDirectSessions(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host := &fakeDirectHost{} + rig := startTunnel(t, ctx, watchPeer("dev-leaves"), ServeConfig{Host: "h", Direct: host}) + rig.send(t, Signal{T: SignalOffer, ID: "pending", SDP: "v=0"}) + eventually(t, "the offer to reach the host half", func() bool { return host.offers() == 1 }) + session := host.session(0) + _ = rig.v.Close() + eventually(t, "the pending session to close with its tunnel", session.isClosed) + select { + case <-rig.done: + case <-time.After(5 * time.Second): + t.Fatal("Serve did not return") + } +} + +// directRoadRig is one device with a relay tunnel and a direct tunnel to the same +// host and registry, a channel open on each, and the holder's stamps recorded. +type directRoadRig struct { + reg *Registry + relay *signalRig + direct *signalRig + relayMux *Mux + directMux *Mux + relayCh *Channel + directCh *Channel + relayAck HelloAck + directAck HelloAck + hellos chan remote.Hello +} + +func startBothRoads(t *testing.T, ctx context.Context, device string, permit func(string) pair.Permit, budget *Budget, clk Clock) *directRoadRig { + t.Helper() + rig := &directRoadRig{reg: NewRegistry(), hellos: make(chan remote.Hello, 8)} + resolver := newEchoStampResolver(func(h remote.Hello) { rig.hellos <- h }) + peer := watchPeer(device) + relayCfg := ServeConfig{Resolver: resolver, Registry: rig.reg, Budget: budget, Permit: permit, Clock: clk, Host: "workstation", Road: RoadRelay} + // THE DIRECT TUNNEL IS GIVEN THE SAME BUDGET ON PURPOSE: Serve must ignore it. + directCfg := ServeConfig{Resolver: resolver, Registry: rig.reg, Budget: budget, Permit: permit, Clock: clk, Host: "workstation", Road: RoadDirect} + relay := startTunnel(t, ctx, peer, relayCfg) + direct := startTunnel(t, ctx, peer, directCfg) + rig.relay, rig.direct = relay, direct + rig.relayMux, rig.directMux = relay.v, direct.v + rig.relayAck, rig.directAck = relay.ack, direct.ack + rig.relayCh = openAndHandshake(t, ctx, relay.v, "chat-both") + <-rig.hellos + rig.directCh = openAndHandshake(t, ctx, direct.v, "chat-both") + <-rig.hellos + return rig +} + +func endedWith(t *testing.T, ch *Channel) string { + t.Helper() + var buf [64]byte + done := make(chan error, 1) + guard.Go("livedoor.test.direct.read", func() { + _, err := ch.Read(buf[:]) + done <- err + }) + select { + case err := <-done: + return reasonOf(err) + case <-time.After(5 * time.Second): + t.Fatal("the channel did not end") + return "" + } +} + +// V34: Registry.Revoke closes the relay tunnel and the direct tunnel of a device +// together, each with the reason `removed`. +func TestARevokeClosesRelayAndDirectTunnelsTogetherWithRemoved(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + rig := startBothRoads(t, ctx, "dev-revoked", nil, nil, nil) + if !rig.reg.HasRoad("dev-revoked", RoadRelay) || !rig.reg.HasRoad("dev-revoked", RoadDirect) { + t.Fatal("the registry does not hold one tunnel on each road") + } + rig.reg.Revoke("dev-revoked") + if got := endedWith(t, rig.relayCh); got != ReasonRemoved { + t.Fatalf("the relay channel ended with %q, want %q", got, ReasonRemoved) + } + if got := endedWith(t, rig.directCh); got != ReasonRemoved { + t.Fatalf("the direct channel ended with %q, want %q", got, ReasonRemoved) + } + if rig.reg.HasRoad("dev-revoked", RoadRelay) || rig.reg.HasRoad("dev-revoked", RoadDirect) { + t.Fatal("a revoked device is still registered on a road") + } +} + +// V34: a permit edit that takes away typing ends the channels of BOTH roads with +// `permit-changed`. +func TestAPermitEditEndsDirectChannelsWithPermitChanged(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var drive atomic.Bool + drive.Store(true) + permit := func(string) pair.Permit { return pair.Permit{Watch: true, Drive: drive.Load()} } + rig := startBothRoads(t, ctx, "dev-edit", permit, nil, nil) + drive.Store(false) + rig.reg.PermitsChanged("dev-edit") + if got := endedWith(t, rig.directCh); got != ReasonPermitChanged { + t.Fatalf("the direct channel ended with %q, want %q", got, ReasonPermitChanged) + } + if got := endedWith(t, rig.relayCh); got != ReasonPermitChanged { + t.Fatalf("the relay channel ended with %q, want %q", got, ReasonPermitChanged) + } +} + +// V35: a direct tunnel is served with no budget and the direct pacing, even when +// its caller hands it a budget: nothing it carries is counted, and it types. +func TestADirectTunnelIsServedWithNoBudgetAndNoPacing(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + fc := NewFakeClock(time.Date(2026, 11, 23, 14, 0, 0, 0, time.UTC)) + budget := OpenBudget(shortTempDir(t), fc, 4096) + t.Cleanup(func() { budget.Close() }) + + resolver := newEchoStampResolver(nil) + direct := startTunnel(t, ctx, watchPeer("dev-direct"), ServeConfig{ + Resolver: resolver, Budget: budget, Clock: fc, Host: "workstation", Road: RoadDirect, + }) + if direct.ack.Limits.Rate != DirectRate || direct.ack.Limits.RateBurst != DirectRate { + t.Fatalf("the direct tunnel's pacing is %d/%d, want %d", direct.ack.Limits.Rate, direct.ack.Limits.RateBurst, DirectRate) + } + if direct.ack.Limits.PingEvery != DirectPingEvery || direct.ack.Limits.DeadAfter != DirectDeadAfter { + t.Fatalf("the direct tunnel's liveness is %v/%v, want %v/%v", direct.ack.Limits.PingEvery, direct.ack.Limits.DeadAfter, DirectPingEvery, DirectDeadAfter) + } + if !direct.ack.Drive { + t.Fatal("a direct tunnel was not offered typing") + } + ch := openAndHandshake(t, ctx, direct.v, "chat-direct") + before := budget.Bytes() + big := makeFrameLineOfExactLength(t, "call", remote.MethodPing, 8192) + if _, err := ch.Write(big); err != nil { + t.Fatal(err) + } + direct.roundTrip(t) + if budget.Exhausted() || budget.Bytes() != before { + t.Fatalf("a direct tunnel was counted by the daily budget: %d bytes (was %d), exhausted=%v", budget.Bytes(), before, budget.Exhausted()) + } + + // The control: the same bytes on a relay tunnel DO spend it. + relay := startTunnel(t, ctx, watchPeer("dev-relay"), ServeConfig{Resolver: resolver, Budget: budget, Clock: fc, Host: "workstation", Road: RoadRelay}) + relayCh := openAndHandshake(t, ctx, relay.v, "chat-relay") + if _, err := relayCh.Write(big); err != nil { + t.Fatal(err) + } + eventually(t, "the relay's bytes to be counted", budget.Exhausted) + if relay.ack.Limits.Rate != Rate { + t.Fatalf("the relay tunnel's pacing is %d, want %d", relay.ack.Limits.Rate, Rate) + } +} + +// V35: with the daily budget spent a relay view is watch-only while the same +// device's direct view still types. +func TestPastTheDailyBudgetADirectViewerStillTypes(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + fc := NewFakeClock(time.Date(2026, 11, 23, 14, 0, 0, 0, time.UTC)) + budget := OpenBudget(shortTempDir(t), fc, 1) + t.Cleanup(func() { budget.Close() }) + budget.Charge(1 << 20) + if !budget.Exhausted() { + t.Fatal("the budget is not spent") + } + + rig := startBothRoads(t, ctx, "dev-spent", nil, budget, fc) + if rig.relayAck.Drive { + t.Fatal("a relay view could type with the budget spent") + } + if !rig.directAck.Drive { + t.Fatal("a direct view could not type with the relay's budget spent") + } + // The same chat: the holder was told Drive=false for the relay stamp and + // Drive=true for the direct stamp. startBothRoads consumed those hellos, so + // open a second channel on each road and read them. + _ = openAndHandshake(t, ctx, rig.directMux, "chat-second") + if h := <-rig.hellos; h.Remote == nil || !h.Remote.Drive || h.Remote.Road != RoadDirect { + t.Fatalf("the holder's stamp on the direct road = %+v, want Drive=true road=direct", h.Remote) + } + _ = openAndHandshake(t, ctx, rig.relayMux, "chat-second") + if h := <-rig.hellos; h.Remote == nil || h.Remote.Drive || h.Remote.Road != RoadRelay { + t.Fatalf("the holder's stamp on the relay = %+v, want Drive=false road=relay", h.Remote) + } +} + +// V35 / D12: the per-device cap applies within a road, so a reconnecting relay +// tunnel never evicts a healthy direct one and the reverse; HasRoad answers from +// the registry. +func TestTheRegistryCapsTunnelsPerRoadAndNeverEvictsADirectOneForARelayOne(t *testing.T) { + reg := NewRegistry() + relayOld, relayNew := newFakeRoadTunnel(RoadRelay), newFakeRoadTunnel(RoadRelay) + directOld, directNew := newFakeRoadTunnel(RoadDirect), newFakeRoadTunnel(RoadDirect) + const device = "dev-caps" + + reg.Add(device, relayOld) + reg.Add(device, directOld) + reg.Add(device, newFakeRoadTunnel(RoadRelay)) + if _, evicted := directOld.closedWith(); evicted { + t.Fatal("a second relay tunnel evicted the direct one") + } + if reg.Count(device) != 3 || !reg.HasRoad(device, RoadDirect) { + t.Fatalf("registry holds %d tunnels, direct=%v; want 3 and a direct one", reg.Count(device), reg.HasRoad(device, RoadDirect)) + } + + // A third relay tunnel (the cap is 2 per road) evicts the OLDEST RELAY tunnel. + reg.Add(device, relayNew) + if reason, evicted := relayOld.closedWith(); !evicted || reason != ReasonHostClosing { + t.Fatalf("the oldest relay tunnel was not evicted with %q (got %q, %v)", ReasonHostClosing, reason, evicted) + } + if _, evicted := directOld.closedWith(); evicted { + t.Fatal("a third relay tunnel evicted the direct one") + } + + // And a third direct tunnel evicts only the oldest direct one. + reg.Add(device, newFakeRoadTunnel(RoadDirect)) + reg.Add(device, directNew) + if reason, evicted := directOld.closedWith(); !evicted || reason != ReasonHostClosing { + t.Fatalf("the oldest direct tunnel was not evicted (got %q, %v)", reason, evicted) + } + if _, evicted := relayNew.closedWith(); evicted { + t.Fatal("a direct tunnel evicted a relay one") + } + if reg.HasRoad("someone-else", RoadDirect) || reg.HasRoad(device, "carrier-pigeon") { + t.Fatal("HasRoad answered true for a device or road with no tunnel") + } +} + +// V35: the daily budget running out resets the channels of relay tunnels and +// leaves direct tunnels alone. +func TestTheDailyBudgetResetSkipsDirectTunnels(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + rig := startBothRoads(t, ctx, "dev-reset", nil, nil, nil) + rig.reg.onBudgetExhausted() + if got := endedWith(t, rig.relayCh); got != ReasonBudget { + t.Fatalf("the relay channel ended with %q, want %q", got, ReasonBudget) + } + // The pong proves the host has handled everything it queued before it, so a + // reset of the direct channel would already have reached this side. + rig.direct.roundTrip(t) + if channelEnded(rig.directCh) { + t.Fatal("the budget reset a direct channel") + } + select { + case <-rig.direct.v.Done(): + t.Fatal("the budget reset closed a direct tunnel") + default: + } + if !rig.reg.HasRoad("dev-reset", RoadDirect) { + t.Fatal("the direct tunnel left the registry") + } +} + +// D7 / V38: a relay tunnel that is a silent standby outlives the host's silence +// backstop while a direct tunnel of the same device is registered, and is closed +// by the next firing once that direct tunnel is gone. +func TestAStandbyRelayTunnelOutlivesTheSilenceBackstopWhileItsDirectOneLivesAndNotAfter(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + reg := NewRegistry() + removeDirect := reg.Add("dev-standby", newFakeRoadTunnel(RoadDirect)) + rig := startTunnel(t, ctx, watchPeer("dev-standby"), ServeConfig{Registry: reg, Clock: fc, Host: "workstation", Road: RoadRelay}) + fc.WaitForTimers(1) + + fc.Advance(IdleDetach + hostBackstopExtra + time.Second) + // The backstop fired, saw a direct tunnel of the same device, and armed again. + fc.WaitForTimers(1) + select { + case <-rig.v.Done(): + t.Fatal("the standby relay tunnel was closed while its direct tunnel was open") + default: + } + + // An unrelated device's direct tunnel does not excuse it. + other := reg.Add("another-device", newFakeRoadTunnel(RoadDirect)) + defer other() + removeDirect() + fc.Advance(hostBackstopExtra + time.Second) + select { + case <-rig.v.Done(): + case <-time.After(5 * time.Second): + t.Fatal("the standby relay tunnel outlived the direct tunnel that excused it") + } + if err := <-rig.done; err != nil { + t.Fatalf("Serve returned %v, want nil on a clean backstop close", err) + } +} + +// V40: a watch-only peer on a direct tunnel is refused calls that type, with the +// same words as on the relay, and an allowed read still reaches the holder. +func TestAWatchOnlyPeerOnADirectTunnelIsRefusedCallsThatTypeAndToldWhy(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + const hostName = "mini-server" + holderCalls := make(chan remote.Frame, 4) + resolver := newEchoStampResolverWithCalls(holderCalls) + rig := startTunnel(t, ctx, Peer{Device: "dev-watch", Label: "ipad", Permit: pair.Permit{Watch: true, Drive: false}}, + ServeConfig{Resolver: resolver, Host: hostName, Road: RoadDirect}) + ch := openAndHandshake(t, ctx, rig.v, "chat-watch") + scan := newLineScanner(ch, MaxLine) + + submit, _ := json.Marshal(remote.Frame{Kind: "call", ID: 41, Method: remote.MethodSubmit}) + if _, err := ch.Write(append(submit, '\n')); err != nil { + t.Fatal(err) + } + line, err := scan.ReadLine(MaxLine) + if err != nil { + t.Fatal(err) + } + var res remote.Frame + if err := json.Unmarshal(bytes.TrimRight(line, "\r\n"), &res); err != nil { + t.Fatal(err) + } + if want := remote.GuestRefusal(hostName, remote.MethodSubmit, false); res.Kind != "result" || res.ID != 41 || res.Error != want { + t.Fatalf("the Submit answer was %+v, want a result for 41 saying %q", res, want) + } + ping, _ := json.Marshal(remote.Frame{Kind: "call", ID: 42, Method: remote.MethodPing}) + if _, err := ch.Write(append(ping, '\n')); err != nil { + t.Fatal(err) + } + select { + case call := <-holderCalls: + if call.Method != remote.MethodPing { + t.Fatalf("the holder saw %q first; only Ping may reach it", call.Method) + } + case <-time.After(5 * time.Second): + t.Fatal("an allowed read did not reach the holder") + } +} + +// newEchoStampResolverWithCalls is newEchoStampResolver with the holder also +// recording every call frame the router lets through. +func newEchoStampResolverWithCalls(calls chan<- remote.Frame) Resolver { + return fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.direct.holder", func() { + defer holderSide.Close() + scan := newLineScanner(holderSide, MaxLine) + line, err := scan.ReadLine(FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f) != nil { + return + } + var h remote.Hello + if json.Unmarshal(f.Payload, &h) != nil { + return + } + wPayload, _ := json.Marshal(remote.Welcome{Version: remote.Version, Workspace: h.Workspace, SessionFile: h.Session, Remote: h.Remote}) + wFrame, _ := json.Marshal(remote.Frame{Kind: "welcome", Payload: wPayload}) + if _, err := holderSide.Write(append(wFrame, '\n')); err != nil { + return + } + for { + callLine, err := scan.ReadLine(MaxLine) + if err != nil { + return + } + var call remote.Frame + if json.Unmarshal(bytes.TrimRight(callLine, "\r\n"), &call) == nil { + calls <- call + } + } + }) + return routerSide, Route{Kind: "daemon", PID: 7002, Session: "/work/direct/" + chat + "/transcript.jsonl", Workspace: "/work/direct"}, nil + }) +} diff --git a/internal/livedoor/serve_test.go b/internal/livedoor/serve_test.go new file mode 100644 index 0000000000..ade5ae84a9 --- /dev/null +++ b/internal/livedoor/serve_test.go @@ -0,0 +1,693 @@ +package livedoor + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/pair" + "github.com/Agent-Field/codeaf/internal/remote" +) + +type fakeResolverFunc func(ctx context.Context, chat string) (net.Conn, Route, error) + +func (f fakeResolverFunc) Resolve(ctx context.Context, chat string) (net.Conn, Route, error) { + return f(ctx, chat) +} + +func reasonOf(err error) string { + var r interface{ Reason() string } + if errors.As(err, &r) { + return r.Reason() + } + var ref *RefusedError + if errors.As(err, &ref) { + return ref.Reason + } + return "" +} + +// TestAnOlderHolderThatEchoesNoStampGetsNoViewerBytes verifies contract V28 +// (D10): when a holder replies with a welcome frame that lacks the echoed +// Remote stamp, the router resets the channel with holder-old, forwards zero +// viewer bytes after the rewritten hello to the holder (even when the viewer +// pipelined a Submit call right behind its hello), never forwards the old +// holder's welcome to the viewer, and forwards the same pipelined Submit when +// connected to a holder that echoes the stamp. +func TestAnOlderHolderThatEchoesNoStampGetsNoViewerBytes(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + // 1. Old holder: reads hello, ignores unknown fields, replies with a welcome + // without Remote, and records every byte that arrives after the hello line. + var ( + oldMu sync.Mutex + oldHello remote.Hello + oldPostBytes bytes.Buffer + oldHolderEnded = make(chan struct{}) + ) + oldResolver := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.v28.oldHolder", func() { + defer close(oldHolderEnded) + defer holderSide.Close() + + scan := newLineScanner(holderSide, MaxLine) + line, err := scan.ReadLine(FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f) == nil { + oldMu.Lock() + _ = json.Unmarshal(f.Payload, &oldHello) + oldMu.Unlock() + } + if scan.wpos > scan.rpos { + oldMu.Lock() + oldPostBytes.Write(scan.buf[scan.rpos:scan.wpos]) + oldMu.Unlock() + } + + welcomePayload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: "/work/proj", + SessionFile: "/work/proj/transcript.jsonl", + Model: "test-model", + }) + welcomeFrame, _ := json.Marshal(remote.Frame{ + Kind: "welcome", + Payload: welcomePayload, + }) + _, _ = holderSide.Write(append(welcomeFrame, '\n')) + + var buf [1024]byte + for { + n, rErr := holderSide.Read(buf[:]) + if n > 0 { + oldMu.Lock() + oldPostBytes.Write(buf[:n]) + oldMu.Unlock() + } + if rErr != nil { + return + } + } + }) + return routerSide, Route{ + Kind: "daemon", + PID: 1001, + Session: "/work/proj/transcript.jsonl", + Workspace: "/work/proj", + }, nil + }) + + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + + peer := Peer{ + Device: "dev-viewer-1", + Label: "laptop", + Permit: pair.Permit{Watch: true, Drive: true}, + Class: pair.ClassNew, + } + guard.Go("livedoor.test.v28.serveOld", func() { + _ = Serve(ctx, hConn, peer, ServeConfig{ + Resolver: oldResolver, + Host: "workstation", + Road: "relay", + }) + }) + + vMux := NewMux(vConn, Viewer, MuxConfig{}) + t.Cleanup(func() { _ = vMux.Close() }) + + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + vCh, err := vMux.Open(ctx, "chat-old") + if err != nil { + t.Fatalf("Open(chat-old) failed: %v", err) + } + + helloPayload, _ := json.Marshal(remote.Hello{ + Version: remote.Version, + ClientID: "client-v28", + Surface: "laptop", + }) + helloLine, _ := json.Marshal(remote.Frame{ + Kind: "hello", + Payload: helloPayload, + }) + submitPayload, _ := json.Marshal(remote.SubmitArgs{Text: "pipelined secret command"}) + submitLine, _ := json.Marshal(remote.Frame{ + Kind: "call", + ID: 7, + Method: remote.MethodSubmit, + Payload: submitPayload, + }) + + pipelined := append(append(helloLine, '\n'), append(submitLine, '\n')...) + if _, err := vCh.Write(pipelined); err != nil { + t.Fatalf("writing pipelined hello+submit failed: %v", err) + } + + var readBuf [4096]byte + n, readErr := vCh.Read(readBuf[:]) + if n != 0 { + t.Fatalf("viewer received %d bytes (%q) from old holder, want 0 bytes", n, readBuf[:n]) + } + if got := reasonOf(readErr); got != ReasonHolderOld { + t.Fatalf("vCh.Read err = %v (reason=%q), want %q", readErr, got, ReasonHolderOld) + } + <-oldHolderEnded + + oldMu.Lock() + gotPost := oldPostBytes.String() + gotOldRemote := oldHello.Remote + oldMu.Unlock() + + if gotOldRemote == nil || gotOldRemote.Device != peer.Device || !gotOldRemote.Drive { + t.Fatalf("rewritten hello sent to old holder had Remote=%+v, want Device=%q Drive=true", gotOldRemote, peer.Device) + } + if gotPost != "" { + t.Fatalf("old holder received %d bytes after hello (%q), want nothing", len(gotPost), gotPost) + } + + // 2. Correct holder: echoes Welcome.Remote matching the stamp, and receives + // the exact same pipelined Submit call line. + submitReceived := make(chan remote.Frame, 1) + goodResolver := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.v28.goodHolder", func() { + defer holderSide.Close() + scan := newLineScanner(holderSide, MaxLine) + line, err := scan.ReadLine(FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if err := json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f); err != nil { + return + } + var h remote.Hello + if err := json.Unmarshal(f.Payload, &h); err != nil { + return + } + welcomePayload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: h.Workspace, + SessionFile: h.Session, + Model: "test-model", + Remote: h.Remote, + }) + welcomeFrame, _ := json.Marshal(remote.Frame{ + Kind: "welcome", + Payload: welcomePayload, + }) + if _, err := holderSide.Write(append(welcomeFrame, '\n')); err != nil { + return + } + callLine, err := scan.ReadLine(MaxLine) + if err != nil { + return + } + var callFrame remote.Frame + if err := json.Unmarshal(bytes.TrimRight(callLine, "\r\n"), &callFrame); err == nil { + submitReceived <- callFrame + } + }) + return routerSide, Route{ + Kind: "daemon", + PID: 1002, + Session: "/work/proj/transcript.jsonl", + Workspace: "/work/proj", + }, nil + }) + + vConn2, hConn2 := net.Pipe() + t.Cleanup(func() { + _ = vConn2.Close() + _ = hConn2.Close() + }) + guard.Go("livedoor.test.v28.serveGood", func() { + _ = Serve(ctx, hConn2, peer, ServeConfig{ + Resolver: goodResolver, + Host: "workstation", + Road: "relay", + }) + }) + + vMux2 := NewMux(vConn2, Viewer, MuxConfig{}) + t.Cleanup(func() { _ = vMux2.Close() }) + + if _, err := vMux2.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck (good holder) failed: %v", err) + } + vCh2, err := vMux2.Open(ctx, "chat-good") + if err != nil { + t.Fatalf("Open(chat-good) failed: %v", err) + } + if _, err := vCh2.Write(pipelined); err != nil { + t.Fatalf("writing pipelined hello+submit to good holder failed: %v", err) + } + + vScan2 := newLineScanner(vCh2, MaxLine) + wLine, err := vScan2.ReadLine(MaxLine) + if err != nil { + t.Fatalf("reading welcome from good holder failed: %v", err) + } + var wFrame remote.Frame + if err := json.Unmarshal(bytes.TrimRight(wLine, "\r\n"), &wFrame); err != nil || wFrame.Kind != "welcome" { + t.Fatalf("first frame from good holder = %+v (err=%v), want welcome", wFrame, err) + } + + gotCall := <-submitReceived + if gotCall.Kind != "call" || gotCall.ID != 7 || gotCall.Method != remote.MethodSubmit { + t.Fatalf("good holder received frame %+v, want call ID=7 Method=%q", gotCall, remote.MethodSubmit) + } + var gotArgs remote.SubmitArgs + if err := json.Unmarshal(gotCall.Payload, &gotArgs); err != nil || gotArgs.Text != "pipelined secret command" { + t.Fatalf("good holder SubmitArgs = %+v (err=%v), want Text=%q", gotArgs, err, "pipelined secret command") + } +} + +// TestWhenTheHolderExitsTheViewerIsToldAndNoChatIsEverStarted verifies contract +// V29: when the holder closes mid-session the viewer channel ends with reason +// holder-gone, a fresh Open for the same chat is refused with not-running, and +// no start path is ever invoked. +func TestWhenTheHolderExitsTheViewerIsToldAndNoChatIsEverStarted(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + var ( + running atomic.Bool + resolveCount atomic.Int32 + startCount atomic.Int32 + exitHolder = make(chan struct{}) + ) + running.Store(true) + + resolver := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + resolveCount.Add(1) + if !running.Load() { + return nil, Route{}, ErrNotRunning + } + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.v29.holder", func() { + defer holderSide.Close() + scan := newLineScanner(holderSide, MaxLine) + line, err := scan.ReadLine(FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if err := json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f); err != nil { + return + } + var h remote.Hello + if err := json.Unmarshal(f.Payload, &h); err != nil { + return + } + if !h.Join || h.New { + startCount.Add(1) + } + welcomePayload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: h.Workspace, + SessionFile: h.Session, + Model: "test-model", + Remote: h.Remote, + }) + welcomeFrame, _ := json.Marshal(remote.Frame{ + Kind: "welcome", + Payload: welcomePayload, + }) + _, _ = holderSide.Write(append(welcomeFrame, '\n')) + <-exitHolder + running.Store(false) + }) + return routerSide, Route{ + Kind: "daemon", + PID: 2001, + Session: "/work/v29/transcript.jsonl", + Workspace: "/work/v29", + }, nil + }) + + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + peer := Peer{ + Device: "dev-v29", + Label: "tablet", + Permit: pair.Permit{Watch: true, Drive: true}, + } + guard.Go("livedoor.test.v29.serve", func() { + _ = Serve(ctx, hConn, peer, ServeConfig{ + Resolver: resolver, + Host: "workstation", + Road: "relay", + }) + }) + + vMux := NewMux(vConn, Viewer, MuxConfig{}) + t.Cleanup(func() { _ = vMux.Close() }) + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + + vCh, err := vMux.Open(ctx, "chat-v29") + if err != nil { + t.Fatalf("Open(chat-v29) failed: %v", err) + } + helloPayload, _ := json.Marshal(remote.Hello{Version: remote.Version}) + helloLine, _ := json.Marshal(remote.Frame{Kind: "hello", Payload: helloPayload}) + if _, err := vCh.Write(append(helloLine, '\n')); err != nil { + t.Fatalf("writing hello failed: %v", err) + } + + vScan := newLineScanner(vCh, MaxLine) + if _, err := vScan.ReadLine(MaxLine); err != nil { + t.Fatalf("reading welcome failed: %v", err) + } + + // Close the holder mid-session and assert the viewer channel ends with holder-gone. + close(exitHolder) + var buf [256]byte + _, readErr := vCh.Read(buf[:]) + if got := reasonOf(readErr); got != ReasonHolderGone { + t.Fatalf("after holder exit, vCh.Read err = %v (reason=%q), want %q", readErr, got, ReasonHolderGone) + } + + // A fresh Open for the same chat is refused with not-running and never starts a chat. + _, openErr := vMux.Open(ctx, "chat-v29") + if got := reasonOf(openErr); got != ReasonNotRunning { + t.Fatalf("second Open after holder exit returned %v (reason=%q), want %q", openErr, got, ReasonNotRunning) + } + if got := startCount.Load(); got != 0 { + t.Fatalf("startCount = %d, want 0 (live door must never start a chat)", got) + } + if got := resolveCount.Load(); got != 2 { + t.Fatalf("resolveCount = %d, want 2", got) + } +} + +// TestAHostBackstopClosesALinkSilentForTheIdleDetachPlusAMinute verifies link +// bookkeeping: the host-side backstop timer closes a tunnel that has received no +// frame at all for IdleDetach + 1 minute on the injected Clock. +func TestAHostBackstopClosesALinkSilentForTheIdleDetachPlusAMinute(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + fc := NewFakeClock(time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC)) + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + + serveDone := make(chan error, 1) + peer := Peer{ + Device: "dev-idle-backstop", + Label: "laptop", + Permit: pair.Permit{Watch: true, Drive: true}, + } + guard.Go("livedoor.test.backstop.serve", func() { + serveDone <- Serve(ctx, hConn, peer, ServeConfig{ + Clock: fc, + Host: "workstation", + Road: "relay", + }) + }) + + vMux := NewMux(vConn, Viewer, MuxConfig{Clock: fc}) + t.Cleanup(func() { _ = vMux.Close() }) + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + fc.WaitForTimers(1) + + // Advance to 1 second shy of IdleDetach + 1 minute: link must still be alive. + fc.Advance(IdleDetach + 59*time.Second) + select { + case <-vMux.Done(): + t.Fatal("link closed at IdleDetach + 59s, want still open before IdleDetach + 1m") + default: + } + + // Advance 2 more seconds past IdleDetach + 1 minute: host backstop closes the link. + fc.Advance(2 * time.Second) + <-vMux.Done() + if err := <-serveDone; err != nil { + t.Fatalf("Serve returned %v, want nil on clean backstop close", err) + } +} + +// TestAThirdTunnelOfOneDeviceClosesTheOldest verifies link bookkeeping: when a +// single viewer device opens a third tunnel beyond MaxTunnelsPerDevice (2), the +// oldest tunnel is closed with host-closing while the second and third stay open. +func TestAThirdTunnelOfOneDeviceClosesTheOldest(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + reg := NewRegistry() + peer := Peer{ + Device: "dev-multi-tun", + Label: "laptop", + Permit: pair.Permit{Watch: true, Drive: true}, + } + + resolver := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.third.holder", func() { + defer holderSide.Close() + scan := newLineScanner(holderSide, MaxLine) + line, err := scan.ReadLine(FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f) != nil { + return + } + var h remote.Hello + if json.Unmarshal(f.Payload, &h) != nil { + return + } + wPayload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: h.Workspace, + SessionFile: h.Session, + Remote: h.Remote, + }) + wFrame, _ := json.Marshal(remote.Frame{Kind: "welcome", Payload: wPayload}) + _, _ = holderSide.Write(append(wFrame, '\n')) + _, _ = io.Copy(io.Discard, holderSide) + }) + return routerSide, Route{ + Kind: "daemon", + PID: 3001, + Session: "/work/p/" + chat + "/transcript.jsonl", + Workspace: "/work/p", + }, nil + }) + + startTunnel := func(chat string) (*Mux, *Channel) { + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + guard.Go("livedoor.test.third.serve", func() { + _ = Serve(ctx, hConn, peer, ServeConfig{ + Resolver: resolver, + Registry: reg, + Host: "workstation", + Road: "relay", + }) + }) + vMux := NewMux(vConn, Viewer, MuxConfig{}) + t.Cleanup(func() { _ = vMux.Close() }) + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck(%s) failed: %v", chat, err) + } + vCh, err := vMux.Open(ctx, chat) + if err != nil { + t.Fatalf("Open(%s) failed: %v", chat, err) + } + hPayload, _ := json.Marshal(remote.Hello{Version: remote.Version}) + hLine, _ := json.Marshal(remote.Frame{Kind: "hello", Payload: hPayload}) + if _, err := vCh.Write(append(hLine, '\n')); err != nil { + t.Fatalf("Write hello (%s) failed: %v", chat, err) + } + scan := newLineScanner(vCh, MaxLine) + if _, err := scan.ReadLine(MaxLine); err != nil { + t.Fatalf("Read welcome (%s) failed: %v", chat, err) + } + return vMux, vCh + } + + mux1, ch1 := startTunnel("chat-1") + mux2, ch2 := startTunnel("chat-2") + if got := reg.Count(peer.Device); got != MaxTunnelsPerDevice { + t.Fatalf("reg.Count after 2 tunnels = %d, want %d", got, MaxTunnelsPerDevice) + } + + // Opening a 3rd tunnel for the same device must evict the 1st (oldest) with host-closing. + mux3, ch3 := startTunnel("chat-3") + if got := reg.Count(peer.Device); got != MaxTunnelsPerDevice { + t.Fatalf("reg.Count after 3rd tunnel = %d, want %d", got, MaxTunnelsPerDevice) + } + + var buf [64]byte + _, err1 := ch1.Read(buf[:]) + if got := reasonOf(err1); got != ReasonHostClosing { + t.Fatalf("oldest channel ch1 ended with %v (reason=%q), want %q", err1, got, ReasonHostClosing) + } + <-mux1.Done() + + select { + case <-mux2.Done(): + t.Fatal("second tunnel mux2 closed when third tunnel opened") + case <-ch2.Done(): + t.Fatal("second tunnel channel ch2 closed when third tunnel opened") + case <-mux3.Done(): + t.Fatal("third tunnel mux3 closed") + case <-ch3.Done(): + t.Fatal("third tunnel channel ch3 closed") + default: + } +} + +// TestRevocationNeverHoldsALockAcrossASpliceWrite verifies link bookkeeping: +// calling Registry.Revoke while a channel's writer is blocked on flow-control +// credit returns promptly without deadlocking on any splice write. +func TestRevocationNeverHoldsALockAcrossASpliceWrite(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + reg := NewRegistry() + peer := Peer{ + Device: "dev-credit-blocked", + Label: "laptop", + Permit: pair.Permit{Watch: true, Drive: true}, + } + + lim := DefaultLimits() + lim.ChannelWindow = 32 << 10 + lim.LinkWindow = 64 << 10 + lim.QueueMax = 512 << 10 + lim.Rate = 64 << 20 + lim.RateBurst = 64 << 20 + + holderQueued := make(chan struct{}) + resolver := fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.revokelock.holder", func() { + defer holderSide.Close() + scan := newLineScanner(holderSide, MaxLine) + line, err := scan.ReadLine(FirstLineMax) + if err != nil { + return + } + var f remote.Frame + if json.Unmarshal(bytes.TrimRight(line, "\r\n"), &f) != nil { + return + } + var h remote.Hello + if json.Unmarshal(f.Payload, &h) != nil { + return + } + wPayload, _ := json.Marshal(remote.Welcome{ + Version: remote.Version, + Workspace: h.Workspace, + SessionFile: h.Session, + Remote: h.Remote, + }) + wFrame, _ := json.Marshal(remote.Frame{Kind: "welcome", Payload: wPayload}) + _, _ = holderSide.Write(append(wFrame, '\n')) + + // Stream enough events (> ChannelWindow, < QueueMax) so the channel + // writer blocks on Channel.Write waiting for credit that never comes. + evLine := append(bytes.Repeat([]byte{'e'}, 4096), '\n') + for i := 0; i < 16; i++ { + if _, err := holderSide.Write(evLine); err != nil { + return + } + } + close(holderQueued) + _, _ = io.Copy(io.Discard, holderSide) + }) + return routerSide, Route{ + Kind: "daemon", + PID: 4001, + Session: "/work/p/transcript.jsonl", + Workspace: "/work/p", + }, nil + }) + + vConn, hConn := net.Pipe() + t.Cleanup(func() { + _ = vConn.Close() + _ = hConn.Close() + }) + guard.Go("livedoor.test.revokelock.serve", func() { + _ = Serve(ctx, hConn, peer, ServeConfig{ + Resolver: resolver, + Registry: reg, + Limits: lim, + Host: "workstation", + Road: "relay", + }) + }) + + vMux := NewMux(vConn, Viewer, MuxConfig{Limits: lim}) + t.Cleanup(func() { _ = vMux.Close() }) + if _, err := vMux.WaitHelloAck(ctx); err != nil { + t.Fatalf("WaitHelloAck failed: %v", err) + } + vCh, err := vMux.Open(ctx, "chat-blocked") + if err != nil { + t.Fatalf("Open failed: %v", err) + } + hPayload, _ := json.Marshal(remote.Hello{Version: remote.Version}) + hLine, _ := json.Marshal(remote.Frame{Kind: "hello", Payload: hPayload}) + if _, err := vCh.Write(append(hLine, '\n')); err != nil { + t.Fatalf("Write hello failed: %v", err) + } + + // Never call vCh.Read so the channel's send credit fills completely and + // chanWriter blocks inside ch.Write. + <-holderQueued + + revokeDone := make(chan struct{}) + guard.Go("livedoor.test.revokelock.revoke", func() { + reg.Revoke(peer.Device) + close(revokeDone) + }) + + select { + case <-revokeDone: + case <-time.After(time.Second): + t.Fatal("Registry.Revoke blocked while channel writer was parked on credit") + } + + <-vCh.Done() + if got := vCh.Reason(); got != ReasonRemoved { + t.Fatalf("vCh.Reason() after Revoke = %q, want %q", got, ReasonRemoved) + } +} diff --git a/internal/livedoor/state.go b/internal/livedoor/state.go new file mode 100644 index 0000000000..28bae8c460 --- /dev/null +++ b/internal/livedoor/state.go @@ -0,0 +1,136 @@ +package livedoor + +import ( + "errors" + "time" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/pair" +) + +// StateKind identifies the lifecycle posture of a viewer's live door link to a +// single host computer. +type StateKind int + +const ( + // Connecting is the initial zero-value posture of a link before its first + // tunnel handshake has completed. + Connecting StateKind = iota + // Live reports that the tunnel is open and the viewer holds both watch and + // drive permission on the host. + Live + // Reconnecting reports that an active tunnel dropped and the link is waiting + // on its jittered backoff timer or dialling a replacement tunnel. + Reconnecting + // WentOffline reports that the host stopped answering active liveness pings, + // closed an idle tunnel, or had no live door registered at the relay. + WentOffline + // Idle reports that the viewer detached locally after IdleDetach of quiet + // with no user action and no running turn so the relay can hibernate. + Idle + // Revoked reports that the host removed this viewer computer or denied watch + // permission, stopping automatic retries for good. A host that turned + // remote control off reads the same way with Reason [ReasonRemoteControlOff], + // except that it is dialled again when a person next opens a view on it. + Revoked + // WatchOnly reports that the tunnel is open with watch permission while + // drive permission is off. + WatchOnly + // StateBudget reports that the host's daily live byte allowance is exhausted + // so sessions stay open and readable without typing until midnight UTC. + // It is named StateBudget (with alias BudgetExhausted) because type Budget + // in budget.go already occupies the package-level identifier Budget. + StateBudget + + // BudgetExhausted aliases StateBudget for callers checking daily budget exhaustion. + BudgetExhausted = StateBudget +) + +func (k StateKind) String() string { + switch k { + case Connecting: + return "connecting" + case Live: + return "live" + case Reconnecting: + return "reconnecting" + case WentOffline: + return "went-offline" + case Idle: + return "idle" + case Revoked: + return "revoked" + case WatchOnly: + return "watch-only" + case StateBudget: + return "budget" + default: + return "unknown" + } +} + +// State is the snapshot of a viewer link's connection posture, the closed-set +// close or refusal reason when one caused the transition, the clock reading +// when this posture began, the host permit, and the transport road name. +type State struct { + Kind StateKind + Reason string + Since time.Time + Permit pair.Permit + Road string +} + +// ErrHostOffline is wrapped by a LinkConfig.Dial implementation when the relay +// reports no live door registration for the host so the link transitions +// straight to WentOffline at the fifteen-second retry cap instead of polling. +var ErrHostOffline = errors.New("livedoor: host offline") + +// ReasonError carries a closed-set live door reason whose Error text is the +// exact person-facing sentence from internal/chatlist so remote.Roam treats a +// channel refusal or link failure as the host's own words. +type ReasonError struct { + Reason string + Host string + Err error +} + +func (e *ReasonError) Error() string { + if e == nil { + return "" + } + return chatlist.LiveSaid(e.Reason, e.Host) +} + +func (e *ReasonError) Unwrap() error { + if e == nil { + return nil + } + return e.Err +} + +// ReasonOf extracts the closed-set live door reason from err when one is +// present on a ReasonError, RefusedError, ChannelError, or reason-bearing error. +func ReasonOf(err error) (string, bool) { + if err == nil { + return "", false + } + var re *ReasonError + if errors.As(err, &re) && re != nil && re.Reason != "" { + return re.Reason, true + } + var ref *RefusedError + if errors.As(err, &ref) && ref != nil && ref.Reason != "" { + return ref.Reason, true + } + var ce *ChannelError + if errors.As(err, &ce) && ce != nil && ce.Why != "" { + return ce.Why, true + } + var r interface{ Reason() string } + if errors.As(err, &r) { + if why := r.Reason(); why != "" { + return why, true + } + } + return "", false +} diff --git a/internal/livedoor/swap_test.go b/internal/livedoor/swap_test.go new file mode 100644 index 0000000000..154da522d2 --- /dev/null +++ b/internal/livedoor/swap_test.go @@ -0,0 +1,541 @@ +package livedoor + +import ( + "context" + "fmt" + "io" + "net" + "runtime" + "sync" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" +) + +// The tests in this file are derived from the validation contract (SPEC-P2 V31 +// and V37). They run a REAL holder (remote.Session behind remote.ServeAttach) and +// a REAL roaming client (remote.Roam over the Link's opener), so that "arrives +// once" is a property of the whole path a person's words take, not of a stub. + +// swapGate holds one message inside the agent until the test lets it go, so that +// a send is IN FLIGHT at the holder at the instant a road swap commits. +type swapGate struct { + entered chan struct{} + release chan struct{} + enterOnce sync.Once + releaseOnce sync.Once +} + +// swapAgent is the Desktop's agent as the contract sees it: it counts how many +// times each message was APPLIED, and it hands the test the event stream of every +// turn so that the test decides when the turn says what. +type swapAgent struct { + *minimalWrappedAgent + + mu sync.Mutex + applied map[string]int + plain int + gates map[string]*swapGate + streams map[string]chan session.Event + next map[string]int + said map[string]string +} + +func newSwapAgent() *swapAgent { + return &swapAgent{ + minimalWrappedAgent: &minimalWrappedAgent{title: "Swap Chat"}, + applied: map[string]int{}, + gates: map[string]*swapGate{}, + streams: map[string]chan session.Event{}, + next: map[string]int{}, + said: map[string]string{}, + } +} + +// SubmitMessage is the door a send carrying a ClientID comes in by. Its count is +// the answer to "how many times did the Desktop's transcript take this message". +func (a *swapAgent) SubmitMessage(_ context.Context, m session.Submission) (<-chan session.Event, error) { + a.mu.Lock() + a.applied[m.ClientID]++ + gate := a.gates[m.ClientID] + ch := make(chan session.Event, 4096) + a.streams[m.ClientID] = ch + a.mu.Unlock() + if gate != nil { + gate.enterOnce.Do(func() { close(gate.entered) }) + <-gate.release + } + return ch, nil +} + +// Submit is the door a send with NO ClientID would come in by. The test sends none +// without one, so a count here means the id was lost on the way. +func (a *swapAgent) Submit(context.Context, string) (<-chan session.Event, error) { + a.mu.Lock() + a.plain++ + a.mu.Unlock() + ch := make(chan session.Event) + close(ch) + return ch, nil +} + +// hold makes the agent keep message id inside SubmitMessage until released. +func (a *swapAgent) hold(id string) *swapGate { + g := &swapGate{entered: make(chan struct{}), release: make(chan struct{})} + a.mu.Lock() + defer a.mu.Unlock() + a.gates[id] = g + return g +} + +func (g *swapGate) let() { g.releaseOnce.Do(func() { close(g.release) }) } + +// pushNext has stream id say its next n words, numbered, under one lock so that +// two goroutines pushing the same stream can never interleave the numbering. +func (a *swapAgent) pushNext(id string, n int) error { + a.mu.Lock() + defer a.mu.Unlock() + ch := a.streams[id] + if ch == nil { + return fmt.Errorf("the agent holds no stream for %q", id) + } + for i := 0; i < n; i++ { + text := fmt.Sprintf("%s:%04d;", id, a.next[id]) + a.next[id]++ + a.said[id] += text + ch <- session.Event{Kind: session.EventTextDelta, Text: text} + } + return nil +} + +// finish ends the turn of stream id. +func (a *swapAgent) finish(id string) { + a.mu.Lock() + ch := a.streams[id] + a.mu.Unlock() + if ch == nil { + return + } + ch <- session.Event{Kind: session.EventTurnDone} + close(ch) +} + +func (a *swapAgent) saidOn(id string) string { + a.mu.Lock() + defer a.mu.Unlock() + return a.said[id] +} + +func (a *swapAgent) appliedOf(id string) int { + a.mu.Lock() + defer a.mu.Unlock() + return a.applied[id] +} + +func (a *swapAgent) plainCount() int { + a.mu.Lock() + defer a.mu.Unlock() + return a.plain +} + +// collected is what a viewer saw of one stream: every word in the order it +// arrived, and how many times the turn was reported done. +type collected struct { + mu sync.Mutex + text string + dones int +} + +// collect reads events in its own goroutine for as long as the stream lives. +func collect(events <-chan session.Event) *collected { + c := &collected{} + guard.Go("livedoor.test.swap.collect", func() { + for ev := range events { + c.mu.Lock() + switch ev.Kind { + case session.EventTextDelta: + c.text += ev.Text + case session.EventTurnDone: + c.dones++ + } + c.mu.Unlock() + } + }) + return c +} + +func (c *collected) seen() (string, int) { + c.mu.Lock() + defer c.mu.Unlock() + return c.text, c.dones +} + +// swapRig is the direct rig with a real holder behind every road and a roaming +// client in front of the Link. +type swapRig struct { + *directRig + ag *swapAgent + cl *remote.Client +} + +const swapSessionFile = "/work/p/swap.jsonl" + +func newSwapRig(t *testing.T) *swapRig { + t.Helper() + ag := newSwapAgent() + sess := remote.NewSession(&remote.Engine{Agent: ag, Workspace: "/work/p", SessionFile: swapSessionFile}, true) + t.Cleanup(func() { _ = sess.Close() }) + holder := func(r *directRig, road string, tunnel int) Resolver { + return fakeResolverFunc(func(_ context.Context, chat string) (net.Conn, Route, error) { + r.recordOpen(road, tunnel, chat) + routerSide, holderSide := net.Pipe() + guard.Go("livedoor.test.swap.holder", func() { + defer holderSide.Close() + _ = remote.ServeAttach(holderSide, holderSide, remote.AttachOptions{ + Open: func(remote.Hello) (*remote.Session, error) { return sess, nil }, + }) + }) + return routerSide, Route{Kind: "daemon", PID: 7002, Session: swapSessionFile, Workspace: "/work/p"}, nil + }) + } + // A hundred hours of idle time: the test moves the fake clock by minutes and the + // view must not detach under it. + rig := newDirectRig(t, rigOpts{idleDetach: 100 * time.Hour, holder: holder}) + return &swapRig{directRig: rig, ag: ag} +} + +// connect attaches the viewer the way the door does: a roaming client whose every +// dial is the Link's opener, with sends resent after a redial. +func (s *swapRig) connect() { + s.t.Helper() + cl, err := remote.Roam("desktop", remote.Hello{Workspace: "/work/p", Session: swapSessionFile, Join: true}, remote.Roaming{ + Dial: func() (io.ReadWriteCloser, error) { return s.openChatErr("chat-swap") }, + Window: 30 * time.Second, + ResendUnanswered: true, + }) + if err != nil { + s.t.Fatalf("attaching the viewer failed: %v", err) + } + s.t.Cleanup(func() { _ = cl.Close() }) + s.cl = cl + if err := cl.Take(); err != nil { + s.t.Fatalf("taking the keyboard failed: %v", err) + } +} + +// send types one message with a fixed ClientID and, when the call is refused +// because the link is between roads, types the SAME message again, which is +// exactly what a person's retry is and what the host must not apply twice. +func (s *swapRig) send(id string) (<-chan session.Event, error) { + var last error + deadline := time.Now().Add(20 * time.Second) + for time.Now().Before(deadline) { + events, err := s.cl.Agent().SubmitMessage(s.ctx, session.Submission{Text: "message " + id, ClientID: id}) + if err == nil { + return events, nil + } + last = err + quiesce() + } + return nil, fmt.Errorf("the send %s never succeeded: %w", id, last) +} + +// upgrade moves the clock in small steps until a direct attempt begins and the +// road reads direct. It gives up after twenty seconds of fake time, which is +// longer than the first rung of the retry ladder. +func (s *swapRig) upgrade() { + s.t.Helper() + before := s.directDials.Load() + for i := 0; s.directDials.Load() == before; i++ { + if i > 200 { + s.t.Fatalf("no direct attempt began in twenty seconds of fake time (timers: %v)", timersWithin(s.fc, 1000*time.Hour)) + } + s.advanceFine(100 * time.Millisecond) + } + s.waitRoad(RoadDirect) +} + +// reattached waits until the client's redial has opened a channel on road beyond +// before opens and the client answers a call there. +func (s *swapRig) reattached(road string, before int) { + s.t.Helper() + within(s.t, "the client to redial onto "+road, func() bool { return len(s.opensOn(road)) > before }) + within(s.t, "the client to be answered on "+road, func() bool { + if err := s.cl.Err(); err != nil { + s.t.Fatalf("the client ended during a swap: %v", err) + } + _, err := s.cl.Ping() + return err == nil + }) +} + +// V31: a message typed at the instant the road changes, in either direction, +// arrives once: the Desktop's agent applies it once, and the events of a running +// turn arrive once and in order. Twenty swaps alternate relay to direct and back; +// at each one a held send is in flight at the holder, a second send is typed at +// a different distance from the commit every time, and the running turn is +// talking while the swap commits. +func TestASendAcrossARoadSwapIsAppliedOnceAndEventsArriveOnceInOrder(t *testing.T) { + const swaps = 20 + s := newSwapRig(t) + s.connect() + ag := s.ag + + // waitDone fails with everything a reader needs to see what went missing: what + // the viewer showed, what the agent said and how often it was told. + waitDone := func(id string, c *collected) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + if _, dones := c.seen(); dones >= 1 { + return + } + quiesce() + } + got, dones := c.seen() + t.Fatalf("the turn of %s never finished on the viewer: it showed %q (done %d times), the agent said %q (applied %d times, %d unnamed), the client's error is %v", + id, got, dones, ag.saidOn(id), ag.appliedOf(id), ag.plainCount(), s.cl.Err()) + } + + // The running turn lives across every swap. + turnEvents, err := s.send("turn") + if err != nil { + t.Fatal(err) + } + turn := collect(turnEvents) + if err := ag.pushNext("turn", 2); err != nil { + t.Fatal(err) + } + + type sent struct { + events <-chan session.Event + err error + } + streams := map[string]*collected{} + var ids []string + + // typed starts a send on its own goroutine and says where its answer will be. + typed := func(id string) chan sent { + result := make(chan sent, 1) + guard.Go("livedoor.test.swap.send", func() { + events, err := s.send(id) + result <- sent{events: events, err: err} + }) + return result + } + // answered waits for a typed send's answer and starts reading its stream. + answered := func(i int, id string, result chan sent) { + t.Helper() + var res sent + select { + case res = <-result: + case <-time.After(20 * time.Second): + t.Fatalf("swap %d: the send %s never returned", i, id) + } + if res.err != nil { + t.Fatalf("swap %d: the send %s failed: %v", i, id, res.err) + } + streams[id] = collect(res.events) + } + + for i := 0; i < swaps; i++ { + to := RoadDirect + if i%2 == 1 { + to = RoadRelay + } + before := len(s.opensOn(to)) + held := fmt.Sprintf("held-%02d", i) + raced := fmt.Sprintf("race-%02d", i) + ids = append(ids, held, raced) + + // The first message is typed and waits at the holder, in flight. + gate := ag.hold(held) + heldResult := typed(held) + select { + case <-gate.entered: + case <-time.After(10 * time.Second): + gate.let() + t.Fatalf("swap %d: the message %s never reached the holder", i, held) + } + + // The second is typed a little before the road changes, a little further + // from it each time, so that across the swaps it lands before the commit, + // across it and after it. + racedResult := typed(raced) + for k := 0; k < i*25; k++ { + runtime.Gosched() + } + + // The running turn keeps talking from another goroutine while the road + // changes under it. + talked := make(chan error, 1) + guard.Go("livedoor.test.swap.talk", func() { + for k := 0; k < 4; k++ { + if err := ag.pushNext("turn", 3); err != nil { + talked <- err + return + } + quiesce() + } + talked <- nil + }) + + // The road changes. + if to == RoadDirect { + s.upgrade() + } else { + s.swapToRelay() + } + gate.let() + if err := <-talked; err != nil { + t.Fatalf("swap %d: %v", i, err) + } + answered(i, held, heldResult) + answered(i, raced, racedResult) + s.reattached(to, before) + if road := s.link.Road(); road != to { + t.Fatalf("swap %d: the road reads %q, want %q", i, road, to) + } + + // After the swap everything still flows: each send's own turn speaks and + // ends, and the running turn goes on. A turn that FINISHES is allowed to + // be seen finishing before the road changes again: the ring of a finished + // stream is gone and the transcript is the authority on its tail (the + // remote package's own law), so only a turn still running has its events + // carried across a swap, and the running turn above is that. + for _, id := range []string{held, raced} { + if err := ag.pushNext(id, 2); err != nil { + t.Fatalf("swap %d: %v", i, err) + } + ag.finish(id) + } + if err := ag.pushNext("turn", 2); err != nil { + t.Fatalf("swap %d: %v", i, err) + } + waitDone(held, streams[held]) + waitDone(raced, streams[raced]) + + // A direct link that stays up a minute is a link whose later death starts + // no ladder climb, so every direction of the next swap is a first attempt. + if to == RoadDirect { + s.advanceHealthy(s.latest(RoadDirect), DirectStableAfter+time.Second) + } + } + + // The running turn ends. + if err := ag.pushNext("turn", 1); err != nil { + t.Fatal(err) + } + ag.finish("turn") + waitDone("turn", turn) + quiesce() + + // Every word arrived once, in the order it was said, and every turn ended once. + if got, dones := turn.seen(); got != ag.saidOn("turn") || dones != 1 { + t.Fatalf("the running turn showed %q (done %d times), the agent said %q", got, dones, ag.saidOn("turn")) + } + for _, id := range ids { + if n := ag.appliedOf(id); n != 1 { + t.Fatalf("the message %s was applied %d times, want once", id, n) + } + if got, dones := streams[id].seen(); got != ag.saidOn(id) || dones != 1 { + t.Fatalf("the turn of %s showed %q (done %d times), the agent said %q", id, got, dones, ag.saidOn(id)) + } + } + if n := ag.appliedOf("turn"); n != 1 { + t.Fatalf("the running turn's own message was applied %d times, want once", n) + } + if n := ag.plainCount(); n != 0 { + t.Fatalf("%d messages reached the agent with no id, want none", n) + } + // The swaps really happened: both roads carried the client, and it never ended. + if d, r := len(s.opensOn(RoadDirect)), len(s.opensOn(RoadRelay)); d < swaps/2 || r < swaps/2+1 { + t.Fatalf("the holder was reached %d times over direct and %d over the relay in %d swaps", d, r, swaps) + } + if err := s.cl.Err(); err != nil { + t.Fatalf("the client ended across the swaps: %v", err) + } +} + +// settleTap waits until no frame has crossed tap for a run of yields, which is the +// moment an after-the-swap count is fair: the swap's own closing frame has left. +func settleTap(tap *frameTap) { + for stable := 0; stable < 4; { + n := tap.mark() + quiesce() + if tap.mark() == n { + stable++ + } else { + stable = 0 + } + } +} + +// V37: after the swap the relay standby sends no frame. The channel the swap +// closed leaves one closing frame, and from then on, through traffic on the +// direct road, key presses and minutes of fake time, the relay carrier sees no +// frame from the viewer, and the host sends it nothing that carries a word. +func TestTheRelayCarriesNoFrameAfterTheSwap(t *testing.T) { + rig := newDirectRig(t, rigOpts{}) + first := rig.openChat("chat-a") + rig.speak(first) + rig.swapToDirect() + relay := rig.tunnel(RoadRelay, 1) + if !isPlanned(rig.endOf(first)) { + t.Fatal("the swap did not end the relay channel with the planned redial") + } + + ch := rig.openChat("chat-a") + if road := rig.speak(ch); road != RoadDirect { + t.Fatalf("chat-a was carried on %q after the swap, want direct", road) + } + other := rig.openChat("chat-b") + if road := rig.speak(other); road != RoadDirect { + t.Fatalf("chat-b was carried on %q after the swap, want direct", road) + } + direct := rig.latest(RoadDirect) + settleTap(&relay.viewer.sent) + settleTap(&relay.hostTap) + viewerMark := relay.viewer.sent.mark() + hostMark := relay.hostTap.mark() + directMark := direct.viewer.sent.mark() + + // A working view: words both ways on the direct road, keys, scrolling, and + // minutes of a link that is alive. + for i := 0; i < 40; i++ { + if _, err := ch.Write([]byte("a line typed on the direct road\n")); err != nil { + t.Fatalf("a write on the direct channel failed: %v", err) + } + if _, err := other.Write([]byte("and another\n")); err != nil { + t.Fatalf("a write on the second direct channel failed: %v", err) + } + rig.link.Touch() + } + rig.advanceHealthy(direct, 3*time.Minute) + rig.link.Touch() + rig.advanceHealthy(direct, 3*time.Minute) + + if frames := relay.viewer.sent.since(viewerMark); len(frames) != 0 { + t.Fatalf("the viewer sent %v on the relay after the swap, want no frame", frames) + } + for _, fr := range relay.hostTap.since(hostMark) { + switch fr.op { + case OpData, OpOpen, OpOpened, OpPing, OpPong, OpSignal: + t.Fatalf("the host sent the relay carrier %v after the swap; want nothing that carries a word", relay.hostTap.since(hostMark)) + } + } + if relay.viewer.closed.Load() { + t.Fatal("the relay standby was closed while direct carried") + } + // The traffic did cross the direct road, so the silence above is not an idle + // test. + if n := direct.viewer.sent.opsSince(directMark, OpData); n < 40 { + t.Fatalf("only %d data frames crossed the direct road, want the traffic the test wrote", n) + } + if st := rig.link.State(); st.Kind != Live || st.Road != RoadDirect { + t.Fatalf("State() = %+v, want Live on direct", st) + } +} diff --git a/internal/livedoor/transport.go b/internal/livedoor/transport.go new file mode 100644 index 0000000000..e56c4e39c6 --- /dev/null +++ b/internal/livedoor/transport.go @@ -0,0 +1,25 @@ +package livedoor + +import ( + "context" + "fmt" + "net" +) + +// maxUnixSocketPath is the 103-byte limit before a path overflows sockaddr_un's +// 104-byte sun_path buffer (including NUL) on BSD and macOS systems. +const maxUnixSocketPath = 103 + +// Transport abstracts local holder discovery sockets so unix domain sockets +// and test pipes sit behind one seam. +type Transport interface { + Listen(addr string) (net.Listener, error) + Dial(ctx context.Context, addr string) (net.Conn, error) +} + +func checkUnixSocketPath(addr string) error { + if len(addr) > maxUnixSocketPath { + return fmt.Errorf("livedoor: unix socket path %q is %d bytes (limit %d bytes for sun_path)", addr, len(addr), maxUnixSocketPath) + } + return nil +} diff --git a/internal/livedoor/transport_unix.go b/internal/livedoor/transport_unix.go new file mode 100644 index 0000000000..91b2e6a039 --- /dev/null +++ b/internal/livedoor/transport_unix.go @@ -0,0 +1,31 @@ +//go:build !windows + +package livedoor + +import ( + "context" + "net" +) + +type unixTransport struct{} + +// UnixTransport returns a Transport over AF_UNIX domain sockets with a 103-byte +// sun_path length check. +func UnixTransport() Transport { + return unixTransport{} +} + +func (unixTransport) Listen(addr string) (net.Listener, error) { + if err := checkUnixSocketPath(addr); err != nil { + return nil, err + } + return net.Listen("unix", addr) +} + +func (unixTransport) Dial(ctx context.Context, addr string) (net.Conn, error) { + if err := checkUnixSocketPath(addr); err != nil { + return nil, err + } + var d net.Dialer + return d.DialContext(ctx, "unix", addr) +} diff --git a/internal/livedoor/transport_windows.go b/internal/livedoor/transport_windows.go new file mode 100644 index 0000000000..d9930d21b6 --- /dev/null +++ b/internal/livedoor/transport_windows.go @@ -0,0 +1,36 @@ +//go:build windows + +package livedoor + +import ( + "context" + "net" +) + +// unixTransport uses AF_UNIX on Windows the same way as on Unix platforms. +// Its behaviour on Windows remains unproven until a manual check on a Windows +// host, and a loopback-TCP-plus-token transport can replace it behind the +// Transport interface if AF_UNIX proves unreliable there. +type unixTransport struct{} + +// UnixTransport returns a Transport over AF_UNIX sockets on Windows. Its +// behaviour on Windows is unproven until a hand check, and a loopback-TCP +// plus token transport would replace it behind Transport if needed. +func UnixTransport() Transport { + return unixTransport{} +} + +func (unixTransport) Listen(addr string) (net.Listener, error) { + if err := checkUnixSocketPath(addr); err != nil { + return nil, err + } + return net.Listen("unix", addr) +} + +func (unixTransport) Dial(ctx context.Context, addr string) (net.Conn, error) { + if err := checkUnixSocketPath(addr); err != nil { + return nil, err + } + var d net.Dialer + return d.DialContext(ctx, "unix", addr) +} diff --git a/internal/manual/chat/a-dev-box-on-your-own-railway.md b/internal/manual/chat/a-dev-box-on-your-own-railway.md index b8863cdfed..b25265d946 100644 --- a/internal/manual/chat/a-dev-box-on-your-own-railway.md +++ b/internal/manual/chat/a-dev-box-on-your-own-railway.md @@ -60,7 +60,7 @@ removal of the one-time setup values. Then open `codeaf chat --at build-box`. ## How saved provider keys, settings and shared memories reach the box -Saved keys, settings and shared memories wait for hosted sync storage approval (Settings → Devices → sync storage). A self-hosted sync service with `--store` needs no request. +Saved keys, settings and shared memories wait for hosted relay storage approval (Settings → Devices → relay storage). A self-hosted relay with `--store` needs no request. The box starts `codeaf serve` with `CODEAF_SERVE_SYNC=1`, so it pulls the identity's saved provider keys, settings and shared memories at startup and every five seconds by default, @@ -152,7 +152,7 @@ to admit another computer yet; use the creating laptop. ## Send a task to my dev box -On the hosted sync service this needs sync storage approval (Settings → Devices → sync storage). +On the hosted relay this needs relay storage approval (Settings → Devices → relay storage). A dev box also takes tasks. It starts `codeaf serve --take-tasks` whenever its installed build lists that option, so a chat on your laptop can run one task on the diff --git a/internal/manual/chat/add-or-remove-a-computer.md b/internal/manual/chat/add-or-remove-a-computer.md index a65fe49c04..03be57ed88 100644 --- a/internal/manual/chat/add-or-remove-a-computer.md +++ b/internal/manual/chat/add-or-remove-a-computer.md @@ -2,7 +2,7 @@ ## How do I add another computer — the Add another device card (add another machine), codeaf pair, a link to paste, and pairing a server with no browser -While hosted sync storage is off, a chat still moves by blind pass-through between your paired computers when both are running codeaf; see *Blind pass-through*. +While hosted relay storage is off, a chat still moves by blind pass-through between your paired computers when both are running codeaf; see *Blind pass-through*. Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. @@ -14,7 +14,7 @@ confirming: existing chats stay here but stop syncing, shared memories and settings clear, and local provider keys stay here. A startup-only computer can pair directly. A home that only completed desktop setup and installed the bundled Canvas skill can still join. Startup lock files, empty app/service/factory folders and the -factory migration marker do not count as local work. Choosing a sync service and +factory migration marker do not count as local work. Choosing a relay and saving its storage status also leave an unused home eligible to join. Credential history is accepted only when it has the known digest-only metadata format; actual keys, unknown content and nonempty work folders remain protected. @@ -42,13 +42,13 @@ Click `+ Add another device` or press `alt+d` to open the steps. Click the headi 1. On the new device, install codeaf and run `codeaf pair`. It makes a link and waits. 2. On this device, click the card’s link field, type or paste the link, and press Enter. Opening the card also focuses its field. You can edit the link before submitting it; clicking inside the field places the caret there. Esc or Tab returns typing to the normal message box, and clicking the message box does the same. Your chat draft stays separate. You can also paste it anywhere on home when the card’s field is not focused, or type it as your message and press Enter. The approval replaces the steps on Home; approving, declining or closing it keeps you on Home. The link is never sent to the model (see "Approve a new device" below). -## Add a device through your own sync service — pairing instructions include --via +## Add a device through your own relay — pairing instructions include --via -When this computer uses your own sync service, step 1 includes its address: `1. On the new device, install and run: codeaf pair --via http://127.0.0.1:8901`. `/pair`, Settings → Devices → Add another device, and `codeaf pair --code` include the same `--via` argument. +When this computer uses your own relay, step 1 includes its address: `1. On the new device, install and run: codeaf pair --via http://127.0.0.1:8901`. `/pair`, Settings → Devices → Add another device, and `codeaf pair --code` include the same `--via` argument. Approving a self-hosted page's link in a terminal keeps that page's service when it matches this computer's selected service. A link waiting on a different service is refused before its code is sent. -The computer showing a numeric pairing code saves its selected sync service when +The computer showing a numeric pairing code saves its selected relay when it approves the joining computer, just before sending the identity. Showing or cancelling a code alone does not change the saved service. @@ -56,9 +56,9 @@ The card goes away once you have two devices. After that, `/pair` or Settings ## Do older chats move after pairing? -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. -Older chats move through an independent copy. Once paired, the terminal chat prepares chats active in the last 30 days in the background while it is open, one at a time; the desktop app does not. Opening another older chat prepares its copy then. This build shows and writes to the copy. The original files stay untouched and remain usable in older codeaf builds. While hosted sync storage is off, that background preparation sends nothing to the sync service: an older chat that is not open on its computer cannot move to another one until it is opened there (*Blind pass-through*) or sync storage is approved. +Older chats move through an independent copy. Once paired, the terminal chat prepares chats active in the last 30 days in the background while it is open, one at a time; the desktop app does not. Opening another older chat prepares its copy then. This build shows and writes to the copy. The original files stay untouched and remain usable in older codeaf builds. While hosted relay storage is off, that background preparation sends nothing to the relay: an older chat that is not open on its computer cannot move to another one until it is opened there (*Blind pass-through*) or relay storage is approved. ## Pairing a server with no browser — the link, token and check number @@ -83,7 +83,7 @@ A device with no screen or no browser, such as a server, does the same: run `cod Paired with laptop-a. Run codeaf to open your chats. ``` -The approving device says `desk-b is now paired. Your chats can continue there.` +The approving device says `desk-b is now paired. desk-b can also see and control your chats here. Change that in /devices.` ## What does codeaf pair --code do @@ -102,9 +102,9 @@ usage: codeaf pair [--name ] | codeaf pair approve | codea - `codeaf pair` with nothing after it is for the NEW device. It asks to join and shows a link. - `codeaf pair approve ` is for a device that is already in. It shows who is asking and the check number, then asks on its own line: `a approve · d decline:`. `a`, `y` and `yes` approve, without regard to case; `d`, Esc, Enter and unrecognised input decline. Pasting the link into the chat, or typing `/pair `, does the same thing on a screen. - `--name ` is what your devices call this computer. See the page *Naming a device*. -- `--via
` names the address of the sync service to go through when it is not the one this device already uses. Pass it to both `codeaf pair` and `codeaf pair approve`. The new device prints the full approve line with `--via` in it when one is needed. +- `--via
` names the address of the relay to go through when it is not the one this device already uses. Pass it to both `codeaf pair` and `codeaf pair approve`. The new device prints the full approve line with `--via` in it when one is needed. -With a self-hosted address (`CODEAF_SYNC_URL=` or `--via
`), the link opens that sync service’s own `/p/` page, and the terminal approval token includes `--via
`. It never prints a hosted page link for that invitation. The page shows the token command and an app link that keep the same address; the key stays after `#`. An address without a web page uses only the terminal token. Pasting a self-hosted link into a chat configured for another address sends no request and says `that link is waiting on codeaf.agentfield.ai, but this computer syncs through 127.0.0.1:8901 — on the new device run: codeaf pair --via http://127.0.0.1:8901`. +With a self-hosted address (`CODEAF_SYNC_URL=` or `--via
`), the link opens that relay’s own `/p/` page, and the terminal approval token includes `--via
`. It never prints a hosted page link for that invitation. The page shows the token command and an app link that keep the same address; the key stays after `#`. An address without a web page uses only the terminal token. Pasting a self-hosted link into a chat configured for another address sends no request and says `that link is waiting on codeaf.agentfield.ai, but this computer syncs through 127.0.0.1:8901 — on the new device run: codeaf pair --via http://127.0.0.1:8901`. A link is good for 10 minutes and one approval. If it ran out, run `codeaf pair` on the new device again. Ctrl+c while it waits ends with `Cancelled. Nothing was paired.` @@ -139,6 +139,7 @@ A new device wants to pair. △ laptop · Linux asked just now · 9 min left Check number 4821. Approve only if the new device shows the same number. +laptop can also see and control your chats here. Change that in /devices. a approve · d decline · esc later ``` @@ -153,10 +154,12 @@ While your answer is on its way the screen says `approving…` or `declining…` When you approve, your screen says: ``` -laptop is now paired. Your chats can continue there. +laptop is now paired. laptop can also see and control your chats here. Change that in /devices. ``` -Every other device that is on says it too, a moment later, from the same message. In a terminal approval the line is `laptop is now paired. Your chats can continue there.` and a no says `Declined. Nothing was paired.` The terminal first says `laptop (Linux) wants to pair.` (the system is left out when it is not known). `codeaf pair approve` with nothing after it says `usage: codeaf pair approve — the link or token the new device shows; for a numeric pairing code use codeaf pair `. +Every other device that is on says it too, a moment later, from the same message. In a terminal approval the line is `laptop is now paired. laptop can also see and control your chats here. Change that in /devices.` and a no says `Declined. Nothing was paired.` The terminal first says `laptop (Linux) wants to pair.` (the system is left out when it is not known). `codeaf pair approve` with nothing after it says `usage: codeaf pair approve — the link or token the new device shows; for a numeric pairing code use codeaf pair `. + +A computer paired from now on can also see and control your chats here, and one paired earlier can only watch until you allow it; both are changed in `/devices` or with `codeaf devices permit [--watch on|off] [--drive on|off]`. ## What does the dot next to a computer mean — the devices row, online and offline @@ -168,9 +171,9 @@ When you have two or more devices, home shows one row of them: ● This Mac ● tower ○ desk (offline) ``` -The plain repertoire uses a filled green dot `●` for online and a hollow dim dot `○` for offline. ASCII uses `#` and `o`; a patched font uses the same presence slots as `/devices`. Your own computer is filled while the strip is shown. A hollow dim dot `○` with `(offline)` is one that is not online: its lid is closed or codeaf is not running there. A computer counts as online only while it keeps answering: when another computer has not answered for 25 seconds (it is asleep, frozen, switched off or disconnected) its dot goes hollow and reads `(offline)`, within 30 seconds of its last answer, and a frozen computer no longer shows as online for minutes. It is back at once when it answers again. The row changes by itself, with no key to press, when a device comes or goes. As a backstop, home also reads the list again every 5 minutes while it is connected, and every minute while it is not. If the sync service has not answered for 25 seconds, Home cannot tell who is online and hides the strip. A stalled connection is subscribed again, so a late answer cannot keep an old online set alive. The strip returns with fresh presence; it never guesses that a silent service means every computer is offline. +The plain repertoire uses a filled green dot `●` for online and a hollow dim dot `○` for offline. ASCII uses `#` and `o`; a patched font uses the same presence slots as `/devices`. Your own computer is filled while the strip is shown. A hollow dim dot `○` with `(offline)` is one that is not online: its lid is closed or codeaf is not running there. A computer counts as online only while it keeps answering: when another computer has not answered for 25 seconds (it is asleep, frozen, switched off or disconnected) its dot goes hollow and reads `(offline)`, within 30 seconds of its last answer, and a frozen computer no longer shows as online for minutes. It is back at once when it answers again. The row changes by itself, with no key to press, when a device comes or goes. As a backstop, home also reads the list again every 5 minutes while it is connected, and every minute while it is not. If the relay has not answered for 25 seconds, Home cannot tell who is online and hides the strip. A stalled connection is subscribed again, so a late answer cannot keep an old online set alive. The strip returns with fresh presence; it never guesses that a silent service means every computer is offline. -Under the row, `alt+m bring work here` brings the newest chat of an online device to this one. With more than one choice it asks `Which device?` and the last choice is `leave it there`. If there is nothing to bring it says `no other device that is online has a chat to bring here`. The page *Continuing a chat on another device* tells what happens next. +Under the row, `alt+m move here` brings the newest chat of an online device to this one. With more than one choice it asks `Which device?` and the last choice is `leave it there`. If there is nothing to bring it says `no other device that is online has a chat to move here`. The page *Continuing a chat on another device* tells what happens next. ## Does the other computer appear on the device list straight after pairing — a just-paired device, devices empty after pairing @@ -190,7 +193,7 @@ Moving chats and pairing are available by default on Linux, macOS and native Win Type `/devices` to list them: ``` -sync service: 127.0.0.1:8901 (your own) +relay: 127.0.0.1:8901 (your own) ● This Mac Mac this device › ● tower Linux ○ desk Linux seen 3h ago @@ -233,7 +236,7 @@ the sync address also drops facts learned from the previous service. Open `/settings` (or `ctrl+,`) and walk with `←` and `→` to `Devices`, between `Connections` and `Privacy` — or type `devices`, `remove`, `revoke`, `pair` or `add device` in settings search. -While loading, the tab says `looking up your devices…`. Loaded, it begins with the same dim `sync service: 127.0.0.1:8901 (your own)` or `sync service: codeaf.agentfield.ai (hosted)` line as `/devices` and the terminal. It lists this computer even before pairing, with the same platform and presence columns and in the same order and words as `/devices` — `●` online, `○` away (`seen 3h ago`, or `offline`), `this device`, and `removed` — followed by `Add another device`. The open tab refreshes on its own when a computer joins, renames itself or is removed. +While loading, the tab says `looking up your devices…`. Loaded, it begins with the same dim `relay: 127.0.0.1:8901 (your own)` or `relay: codeaf.agentfield.ai (hosted)` line as `/devices` and the terminal. It lists this computer even before pairing, with the same platform and presence columns and in the same order and words as `/devices` — `●` online, `○` away (`seen 3h ago`, or `offline`), `this device`, and `removed` — followed by `Add another device`. The open tab refreshes on its own when a computer joins, renames itself or is removed. ## Keys in Settings Devices — add, rename and confirm removal @@ -243,7 +246,9 @@ In `/settings` → Devices, the key line shrinks to what works on the row (`↑ - `n rename` on `this device` opens `name this device: ` under the row with `enter save · ctrl+u clear · esc cancel`. While typing, `esc` cancels the edit without closing `/settings`; a second `esc` leaves `/settings`. On another row `n` says `a device renames itself — choose this device's row, or open /devices on the one you mean.` - `r remove` (called `codeaf devices revoke ` on the CLI) asks `remove desk? it must pair again to come back · y removes · any other key keeps it`. Only `y` removes it, marks its row `removed`, and says `desk was removed — it can no longer reach your chats.` Any other key cancels, keeps the same row selected, and does nothing else. On your own row `r` says `this device cannot remove itself — choose another row.` On `Add another device` or a `removed` row, `r` does nothing. -Where devices cannot work, the tab shows one sentence and no rows: `pairing is not available here` (a chat over `--host` or `--at`), `moving chats needs a newer furrow engine than this build carries`, or the read error. With `CODEAF_SYNC_URL=off` it lists this computer, and `enter add` answers `sync is off (CODEAF_SYNC_URL=off); pairing needs the sync service`, as `/pair` does. +With remote control on, on `/devices` and here, another computer's row also says what it may do with the chats on THIS computer, `watch and type`, `watch only` or `not shared`, and the key line gains `w watch` and `t type`: `↑↓ choose · n rename · r remove · w watch · t type · esc close`. `w` turns watching on or off (off turns typing off too); `t` turns typing off at once, and on only after `let desk type into chats on this computer? y turns it on, any other key keeps it off`. One line follows: `desk can watch chats on this computer.`, `desk can no longer watch chats on this computer.`, `desk can type into chats on this computer.` or `desk can watch, not type.` A build that cannot change it says `this build cannot change that`. Your own row, `Add another device` and a removed row have none of this, and with remote control off the rows are as above. + +Where devices cannot work, the tab shows one sentence and no rows: `pairing is not available here` (a chat over `--host` or `--at`), `moving chats needs a newer furrow engine than this build carries`, or the read error. With `CODEAF_SYNC_URL=off` it lists this computer, and `enter add` answers `sync is off (CODEAF_SYNC_URL=off); pairing needs the relay`, as `/pair` does. ## A device was removed but refreshing the list failed @@ -263,7 +268,7 @@ this device was removed by another of your devices, so this chat stays here only ## Can a removed computer rejoin — /devices, pairing again and retained local chats -Pairing again restores device access. On the hosted sync service, sending keys or shared state needs sync storage approval (Settings → Devices → sync storage); chats move by blind pass-through while both computers are running codeaf. +Pairing again restores device access. On the hosted relay, sending keys or shared state needs relay storage approval (Settings → Devices → relay storage); chats move by blind pass-through while both computers are running codeaf. `/devices` on a removed computer says the removal notice in place of the list. A terminal refusal uses `this device was removed by another of your devices, so this chat stays here only — run codeaf pair --replace to bring it back`. Home says `removed by another of your devices — pair again to sync`. The terminal command `codeaf devices` gives its removal explanation once, without following it with `nothing is paired yet`. Removal appears immediately in an open window and on Home, and after restarting, once only. Your local chats stay usable while this computer is removed, and no longer follow your other devices. @@ -285,9 +290,9 @@ Moving chats and pairing are available by default on Linux, macOS and native Win These are the screen's sentences when link pairing stops. Nothing was changed on either device when you read one of them. -- `that is not a codeaf pairing link or code; it looks like https://codeaf.agentfield.ai/p/k7m2q9xd#... or k7m2q9xd.`: what was pasted is neither shape. Paste the whole link or the whole `.` token. Links from your own sync service are accepted too. +- `that is not a codeaf pairing link or code; it looks like https://codeaf.agentfield.ai/p/k7m2q9xd#... or k7m2q9xd.`: what was pasted is neither shape. Paste the whole link or the whole `.` token. Links from your own relay are accepted too. - `the link ran out before anyone approved it; run `codeaf pair` again for a new one`: a link is good for 10 minutes. -- `that link is not waiting any more; run `codeaf pair` on the new device for a fresh one`: the link’s own sync service said it is gone or expired. A link on a different sync service is refused before any request is sent. +- `that link is not waiting any more; run `codeaf pair` on the new device for a fresh one`: the link’s own relay said it is gone or expired. A link on a different relay is refused before any request is sent. - `that request was already answered`: another of your devices approved or denied it first. - `the request was declined on your other device; run `codeaf pair` to ask again`: the new device sees this when you decline. - `the check number does not fit that device, so nothing was approved`: the number on the approve screen does not belong to the device that asked. Do not approve; ask again. @@ -298,9 +303,9 @@ Too many requests from one network are refused too: at most 10 new links in an h ## I quit on my laptop and opened my desktop after pairing -While hosted sync storage is off, `idle handoff` does not run, and a laptop where codeaf has quit cannot hand the chat over: the desktop can take it only while codeaf is running on the laptop. See *Blind pass-through*. +While hosted relay storage is off, `idle handoff` does not run, and a laptop where codeaf has quit cannot hand the chat over: the desktop can take it only while codeaf is running on the laptop. See *Blind pass-through*. -After a clean quit and final durable save, bare `codeaf` on another paired computer within 24 hours opens the released chat automatically. By default (**Settings → General → idle handoff** is off), open idle chats keep their hold and selecting a released chat on Home asks **Continue here**. Turn on **idle handoff** in `/settings` (or set `CODEAF_IDLE_HANDOFF=1`) so an idle paired chat lets go about 2 seconds after it goes idle once saved to the sync service, and Enter on Home (or `agents.open` in the app) opens a released chat directly. A lapsed hold on another computer still asks Continue here, including when its holder was working or its last working state is unknown. A laptop that went to sleep or disconnected while still holding the chat needs `alt+c` on Home while its hold is live. Local unsaved edits, another open local window, a named chat, `--host`, `--at` or `--session` prevent automatic continuation. A running chat never moves by itself. The arrival retains its `Moved from` banner and `not brought along:` facts; `esc` goes Home. +After a clean quit and final durable save, bare `codeaf` on another paired computer within 24 hours opens the released chat automatically. By default (**Settings → General → idle handoff** is off), open idle chats keep their hold and selecting a released chat on Home asks **Move here**. Turn on **idle handoff** in `/settings` (or set `CODEAF_IDLE_HANDOFF=1`) so an idle paired chat lets go about 2 seconds after it goes idle once saved to the relay, and Enter on Home (or `agents.open` in the app) opens a released chat directly. A lapsed hold on another computer still asks Move here, including when its holder was working or its last working state is unknown. A laptop that went to sleep or disconnected while still holding the chat needs `alt+c` on Home while its hold is live. Local unsaved edits, another open local window, a named chat, `--host`, `--at` or `--session` prevent automatic continuation. A running chat never moves by itself. The arrival retains its `Moved from` banner and `not brought along:` facts; `esc` goes Home. Personal memory and stored model, display, approval and limit defaults follow the paired computers too. Limits are shared as values; spending counted against them stays per computer. Automations and machine-specific paths and settings stay local. @@ -314,13 +319,13 @@ blocks its later requests; it cannot take back bytes the device already received ## After removal — does this machine keep syncing while its window is open -Once codeaf learns that this machine was removed, it stops asking for chats and stops sending updates. That refusal is remembered across windows and restarts. Your window stays usable for local chats. Home removes its offer to continue a chat from your other devices, its continue chord and the continue action on chat rows. The removal explanation stays visible. +Once codeaf learns that this machine was removed, it stops asking for chats and stops sending updates. That refusal is remembered across windows and restarts. Your window stays usable for local chats. Home removes its offer to continue a chat from your other devices, its continue chord and the move action on chat rows. The removal explanation stays visible. Run `codeaf pair` to pair it again. Pairing can still reach the service and gives this machine a new device key. An already open Home then shows your other devices again. -## Terminal device list — sync service, this computer, platform and duplicate names +## Terminal device list — relay, this computer, platform and duplicate names -`codeaf devices` begins with `sync service: codeaf.agentfield.ai (hosted)` or `sync service: 127.0.0.1:8901 (your own)`. It lists this computer as well as the other paired computers. A known platform and online state or last-seen time appear beside each name; unknown details are omitted. Removed devices come last under `removed`. +`codeaf devices` begins with `relay: codeaf.agentfield.ai (hosted)` or `relay: 127.0.0.1:8901 (your own)`. It lists this computer as well as the other paired computers. A known platform and online state or last-seen time appear beside each name; unknown details are omitted. Removed devices come last under `removed`. Duplicate names use the same short suffix as the chat picker, for example `desk-b #8381`. Remove that one with `codeaf devices revoke desk-b#8381` or `codeaf devices revoke "desk-b #8381"`. An ambiguous name lists the choices and an example command. Removal cannot erase anything already on that computer. @@ -332,11 +337,11 @@ creating a conversation. The device list and pairing approval stay over Home. `/pair` and Settings → Devices → Add another device offer both directions: `paste the link the new device shows, or on it run codeaf pair 43-209-648`. -The command includes `--via` when this computer uses your own sync service. +The command includes `--via` when this computer uses your own relay. The card also shows `> Paste pairing link`: paste or type the link there and press Enter. Closing the card cancels its code; submitting a link switches to the same approval card as Home, with the same check number and `a` / `d` keys. -A link for a different sync service is refused before looking it up. Your chat +A link for a different relay is refused before looking it up. Your chat draft stays separate. `c copy code` works until you start editing the link. @@ -358,7 +363,7 @@ If this build cannot move chats, the local row is followed by the existing remote-access instructions for `codeaf serve` and `codeaf chat --at `; it does not recommend unavailable chat pairing. With `CODEAF_SYNC_URL=off`, neither the terminal nor the device cards draws a -`sync service:` line. The local row remains available. +`relay:` line. The local row remains available. ## Pair again with the same devices after removal @@ -372,7 +377,7 @@ memories and settings are cleared, and locally saved provider keys remain. ## Sync is off — which address should I set A command that needs sync says -`sync is off: set CODEAF_SYNC_URL to your sync service's address`. +`sync is off: set CODEAF_SYNC_URL to your relay's address`. Set a service URL to enable syncing again. Device cards omit their service line while syncing is explicitly off; their local computer row still appears. @@ -383,9 +388,9 @@ ports omitted (`:443` for HTTPS, `:80` for HTTP) and trailing slashes omitted. An actual difference in scheme, port, host or path prefix remains a different service. A link for a different service is refused before any lookup there. -## The first /status after pairing — sync storage on your own service +## The first /status after pairing — relay storage on your own service -Successful pairing asks the sync service for your account's storage permission and saves its answer on this computer. It makes up to three attempts inside about 1.5 seconds, so a temporary startup refusal need not lose the answer. This applies to `codeaf pair`, `codeaf pair approve`, a link pasted on Home and `/pair`. An already-open window's next `/status` shows `sync storage off` when that answer is off, including with your own service address. A service that does not report storage permission adds no terminal line but its successful answer is saved; an unavailable service leaves the previous saved answer alone. +Successful pairing asks the relay for your account's storage permission and saves its answer on this computer. It makes up to three attempts inside about 1.5 seconds, so a temporary startup refusal need not lose the answer. This applies to `codeaf pair`, `codeaf pair approve`, a link pasted on Home and `/pair`. An already-open window's next `/status` shows `relay storage off` when that answer is off, including with your own service address. A service that does not report storage permission adds no terminal line but its successful answer is saved; an unavailable service leaves the previous saved answer alone. The desktop's pairing receipt confirms that the computers paired. It does not promise that chats can continue elsewhere while storage is off. A refusal diff --git a/internal/manual/chat/client-tools.md b/internal/manual/chat/client-tools.md index e5a7017889..25e2499723 100644 --- a/internal/manual/chat/client-tools.md +++ b/internal/manual/chat/client-tools.md @@ -32,6 +32,6 @@ answers take 1–4096 bytes. Joined holders forward tools when supported; older holders refuse attachment. Reconnect restores sets only to the same conversation. A holder switching to another chat drops the tools and ends their calls. A chat held on another -computer stores sets until "Continue here" or take. Each connection owns its +computer stores sets until "Move here" or take. Each connection owns its tools and calls. Link loss ends calls when observed or at their wait limit; later answers are refused. diff --git a/internal/manual/chat/closing-a-chat.md b/internal/manual/chat/closing-a-chat.md index c84b3ddd86..ac64cccf8e 100644 --- a/internal/manual/chat/closing-a-chat.md +++ b/internal/manual/chat/closing-a-chat.md @@ -2,6 +2,6 @@ ## A final save says another computer continued this chat or kept turns separately -If the final save finds that the chat has moved to a different machine, the window that closed it still receives ` continued this chat. This copy is read-only and may be behind`. Any sentence about turns kept as a separate copy arrives with it. +If the final save finds that the chat has moved to a different machine, the window that closed it still receives ` moved this chat. This copy is read-only and may be behind`. Any sentence about turns kept as a separate copy arrives with it. Closing one chat while another stays open puts these sentences in the window's notes. Quitting codeaf prints them once after the screen closes, alongside the saving receipt. This also works with `--no-host`. A clean final save adds no sentence. diff --git a/internal/manual/chat/commands.md b/internal/manual/chat/commands.md index 845f0d38f8..3a39ea3b8f 100644 --- a/internal/manual/chat/commands.md +++ b/internal/manual/chat/commands.md @@ -337,7 +337,7 @@ command). ## Pairing commands — /pair, /pair , /sync, /link and /laptop -While hosted sync storage is off, a chat still moves by blind pass-through between your paired computers when both are running codeaf; see *Blind pass-through*. +While hosted relay storage is off, a chat still moves by blind pass-through between your paired computers when both are running codeaf; see *Blind pass-through*. | Command | Aliases | Argument | Effect | |---|---|---|---| @@ -347,7 +347,7 @@ While hosted sync storage is off, a chat still moves by blind pass-through betwe | `/pair` | `/sync`, `/link`, `/laptop` | `` | on a device that is already paired: opens a new device's request from the link it shows, with its name, system, time and a check number to compare, then `a` approves and `d` declines | | `/devices` | — | — | lists your devices with `●` online and `○` away; `n` renames this device, `r` asks before removing the computer under the cursor; only `y` removes it and any other key keeps it, and a removed device can only return as a new request you approve (`/settings` → `Devices` holds the same list, including this computer and `Add another device`) | -The words to type are `/pair`, `/pair `, `/sync`, `/link` and `/laptop`. All five open the same door. In a terminal `codeaf pair --code` shows a code and `codeaf pair ` uses one; bare `codeaf pair` requests approval by link instead. The page *Pairing your chats with a second computer* has the whole story: the three words, one attempt for each code, and what revoking cannot take back. +The words to type are `/pair`, `/pair `, `/sync`, `/link` and `/laptop`. All five open the same door. In a terminal `codeaf pair --code` shows a code and `codeaf pair ` uses one; bare `codeaf pair` requests approval by link instead. From the terminal, `codeaf devices` lists your computers, `codeaf devices permit [--watch on|off] [--drive on|off]` shows or changes whether a paired computer may watch or type here, `codeaf devices revoke ` removes one, and `codeaf devices rename ` renames this computer. The page *Pairing your chats with a second computer* has the whole story: the three words, one attempt for each code, and what revoking cannot take back. ## Cache, display and export commands @@ -876,6 +876,11 @@ is where it is read. Every ordinary launch has a crew — auto is an answer, not so the line is always there; the one session that shows none is a **remote** one opened with `--host`, where the crew belongs to the other machine. +In a chat opened live from another of your computers (*Remote control*), `/status` adds a +`road` line that says how the view travels: `live · direct` between the two computers, or +`live · relay` through the server in between. It follows the road the view is on right now, with no +notice when it changes, and an offline copy and an ordinary chat draw none. + `/status` differs from the on-screen status sheet in two deliberate ways: - The session **file** is added. A path is a thing you copy into another program. @@ -1974,7 +1979,7 @@ the Memory tab. Tasks controls delegated work; AI teams sets defaults for groups of AI chats. Permissions controls approvals. Spending holds limits. Connections holds accounts, keys, web search and remote connection settings. Devices lists your paired computers, renames this one, removes another, and starts -`/pair` from `Add another device`. A paired account on a relay that reports storage permission also has `sync storage`: when off, Enter opens a request and shows its code and link, including from Settings search. Self-hosted storage needs no request. +`/pair` from `Add another device`. A paired account on a relay that reports storage permission also has `relay storage`: when off, Enter opens a request and shows its code and link, including from Settings search. Self-hosted storage needs no request. Privacy holds history, drafts and data-sharing choices. Old saved keys and values are unchanged. Search accepts old labels and keys, @@ -2341,6 +2346,6 @@ nothing was left behind, `/setup` says so and does nothing. Limits: a setup turn is never replayed on another machine (the agent does it again there), never attempts impossible items, and can be rewound like any turn. When it ends, codeaf looks at what is now on this machine and updates the record. Existing cells keep their declared class: an older sandboxed cell still has its folder limits and opens its network for the setup turn only. Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. A compatible furrow engine is required. Without a cell there is nothing to set up. -## Why pairing commands do not turn on sync storage — request access in Devices +## Why pairing commands do not turn on relay storage — request access in Devices -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. diff --git a/internal/manual/chat/continuing-a-chat-on-another-computer.md b/internal/manual/chat/continuing-a-chat-on-another-computer.md index 4d478a3f9e..758c1f5a75 100644 --- a/internal/manual/chat/continuing-a-chat-on-another-computer.md +++ b/internal/manual/chat/continuing-a-chat-on-another-computer.md @@ -1,81 +1,87 @@ # Continuing a chat that one of your machines holds -To continue on this machine, select the chat on home and choose `continue here` (the default while `idle handoff` is off; when **Settings → General → idle handoff** or `CODEAF_IDLE_HANDOFF=1` is turned on in a paired set, a released chat opens here automatically, while a live hold or a lapsed hold on another computer still offers `continue here`). When your paired computer is offline or has let go of its latest chat, home can ask `Continue tower's latest chat here?`: `alt+c` continues immediately when there is no local choice to make, and `alt+x` dismisses the offer. Moving chats is available by default on Linux, macOS and native Windows with a compatible engine. Older chats become movable through independent copies after pairing. +To move a chat to this computer, select it on home and choose `move here` (the default while `idle handoff` is off; when **Settings → General → idle handoff** or `CODEAF_IDLE_HANDOFF=1` is turned on in a paired set, a released chat opens here automatically, while a live hold or a lapsed hold on another computer still offers `move here`). When your paired computer is offline or has let go of its latest chat, home can ask `Move tower's latest chat here?`: `alt+c` moves it immediately when there is no local choice to make, and `alt+x` dismisses the offer. Moving chats is available by default on Linux, macOS and native Windows with a compatible engine. Older chats become movable through independent copies after pairing. ## Continue on another computer — moving chats and pairing availability Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. -Older chats move through an independent copy. Once paired, codeaf prepares chats active in the last 30 days in the background, one at a time; opening another older chat prepares its copy then. This build shows and writes to the copy. The original files stay untouched and remain usable in older codeaf builds. While hosted sync storage is off, a chat still moves by blind pass-through between your paired computers when both are running codeaf; see *Blind pass-through*. +Older chats move through an independent copy. Once paired, codeaf prepares chats active in the last 30 days in the background, one at a time; opening another older chat prepares its copy then. This build shows and writes to the copy. The original files stay untouched and remain usable in older codeaf builds. While hosted relay storage is off, a chat still moves by blind pass-through between your paired computers when both are running codeaf; see *Blind pass-through*. -## Blind pass-through — move a chat without sync storage, pass-through mode, move a chat while sync storage is off, does my other computer need to be on, continue here without sync storage approval +## Move here: also called "continue here", "take over" or "continue on this machine" -On the hosted sync service, sync storage is off for an account until it is approved (**Settings → Devices → sync storage**), and the service keeps no chat or file content while it is off. You can still move a chat between your own paired computers without it. This is **blind pass-through**, also called pass-through mode: the computer that has the chat sends its already-encrypted bytes straight through the sync service to the computer taking it, and the service, which cannot read them, stores nothing. It is on by default; beyond pairing there is nothing to set up. Everything stays encrypted end to end. +**Move here** is the one verb for carrying a chat from another computer to this one. If you are asking what happened to the continue button, or where did it go: nothing was removed, it was renamed. Older builds, older notes and older versions of this manual used the three names in this section's heading for the same act, on Home's rows, on the card that asks first, on the devices row and in the desktop app. Only the word changed. The card, its `1 move here` and `2 leave it there` answers, the `alt+m` chord on the devices row and the `alt+c` chord on the resume offer all work as they did. -Blind pass-through needs **both computers running codeaf**: a terminal, the app, or a background engine for that computer. It covers ordinary chats and their files, including a chat's `.env` and other secret files (*Do my .env files and secrets move to my other computer without sync storage*), and applies only when you have at least one other paired computer. Choose `continue here` as usual. If the computer that has the chat is not on, see *Continue here says the computer that has this chat is not on*. +If you remember one of those names, read it as `Move here` in every section of this page and on every page that names it. The sections below keep what the act does and what it refuses to do: *Move here says the computer that has this chat is not on*, *Move here does nothing* and *why move here failed* are the ones people reach most often. + +## Blind pass-through — move a chat without relay storage (it used to be called sync storage), pass-through mode, move a chat while relay storage is off, does my other computer need to be on, move here without relay storage approval + +On the hosted relay, relay storage is off for an account until it is approved (**Settings → Devices → relay storage**), and the service keeps no chat or file content while it is off. You can still move a chat between your own paired computers without it. This is **blind pass-through**, also called pass-through mode: the computer that has the chat sends its already-encrypted bytes straight through the relay to the computer taking it, and the service, which cannot read them, stores nothing. It is on by default; beyond pairing there is nothing to set up. Everything stays encrypted end to end. + +Blind pass-through needs **both computers running codeaf**: a terminal, the app, or a background engine for that computer. It covers ordinary chats and their files, including a chat's `.env` and other secret files (*Do my .env files and secrets move to my other computer without relay storage*), and applies only when you have at least one other paired computer. Choose `move here` as usual. If the computer that has the chat is not on, see *Move here says the computer that has this chat is not on*. Taking a chat on a second computer remembers it there, so that computer can serve it in turn: a third computer can take it from the second while the first is off. -Still waiting for sync storage approval, even with blind pass-through: saved provider keys and connections, memories, teams, shared preferences, idle handoff (an idle chat handing itself over) and task copies. They behave exactly as before while storage is off. A chat's own secret files are not in that list: they move with the chat. +Still waiting for relay storage approval, even with blind pass-through: saved provider keys and connections, memories, teams, shared preferences, idle handoff (an idle chat handing itself over) and task copies. They behave exactly as before while storage is off. A chat's own secret files are not in that list: they move with the chat. -When sync storage is approved later, chats that only lived on computers upload in the background by themselves. Until that finishes they can still be taken from a computer that is on. +When relay storage is approved later, chats that only lived on computers upload in the background by themselves. Until that finishes they can still be taken from a computer that is on. -Blind pass-through does nothing when storage is approved or when you use a self-hosted sync service: those behave as they always did. *Turn off blind pass-through* says how to switch it off. +Blind pass-through does nothing when storage is approved or when you use a self-hosted relay: those behave as they always did. *Turn off blind pass-through* says how to switch it off. -## Do my .env files and secrets move to my other computer without sync storage — will my secrets come with the chat, git shows my .env files deleted after moving a chat +## Do my .env files and secrets move to my other computer without relay storage — will my secrets come with the chat, git shows my .env files deleted after moving a chat -Yes. While hosted sync storage is off and a chat moves by blind pass-through, the files codeaf keeps out of a chat's saved history move with it: every `.env` and `.env.*` file anywhere in the folder, committed templates such as `.env.example` included, and any other file that looks like it holds a secret, such as a private key or a README with a token in it. They arrive in the same step that brings the chat's files, byte for byte at the same path with the same file permissions, so git on the other computer does not show them as deleted. +Yes. While hosted relay storage is off and a chat moves by blind pass-through, the files codeaf keeps out of a chat's saved history move with it: every `.env` and `.env.*` file anywhere in the folder, committed templates such as `.env.example` included, and any other file that looks like it holds a secret, such as a private key or a README with a token in it. They arrive in the same step that brings the chat's files, byte for byte at the same path with the same file permissions, so git on the other computer does not show them as deleted. -They leave the computer that has the chat sealed under your key, inside the encrypted pipe, and nothing about them is stored anywhere but the two folders. Only the chat's own secret files move this way: saved provider keys, connections and credentials, preferences, shared memories and teams still wait for sync storage approval. +They leave the computer that has the chat sealed under your key, inside the encrypted pipe, and nothing about them is stored anywhere but the two folders. Only the chat's own secret files move this way: saved provider keys, connections and credentials, preferences, shared memories and teams still wait for relay storage approval. Where it stops: - Both computers must run codeaf and be your own paired computers; a computer you removed gets nothing more. -- If the computer that has the chat is off, nothing moves, secret files included, and `continue here` ends with the sentence in *Continue here says the computer that has this chat is not on*. -- `CODEAF_PASSTHROUGH=off` turns blind pass-through off, and these files then wait for sync storage like the rest. With sync storage approved they travel through the key vault, as always. +- If the computer that has the chat is off, nothing moves, secret files included, and `move here` ends with the sentence in *Move here says the computer that has this chat is not on*. +- `CODEAF_PASSTHROUGH=off` turns blind pass-through off, and these files then wait for relay storage like the rest. With relay storage approved they travel through the key vault, as always. - A file you edit on the second computer comes back when you take the chat back there. The file saved last wins, so a copy saved later on the receiving computer is kept. - A secret file you delete on one computer is not deleted on the other by this road. A file too large for the key vault stays on the computer it is on (*A large file that looks like a secret did not arrive*). - A secret file the computer that has the chat has not saved a turn since creating may not have been noticed yet, so it can miss the move until the chat's next saved turn. -## Continue here says the computer that has this chat is not on — open codeaf there, then continue here +## Move here says the computer that has this chat is not on — open codeaf there, then move here -When the computer that has the chat is not running codeaf, `continue here` fails with this sentence, naming that computer: +When the computer that has the chat is not running codeaf, `move here` fails with this sentence, naming that computer: -` has this chat and is not on right now; open codeaf there, then continue here` +` has this chat and is not on right now; open codeaf there, then move here` -It says so within a few seconds. Nothing was moved and nothing is lost, and the chat's record still names the computer that has it. If you had typed words before choosing `continue here`, they stay in the box and the sentence ends `; your words are still in the box`; a chat that opens by itself at launch has no typed words, so that ending is left off. It works as soon as codeaf runs there again: open a terminal, the app or its background engine on that computer, then choose `continue here` again. +It says so within a few seconds. Nothing was moved and nothing is lost, and the chat's record still names the computer that has it. If you had typed words before choosing `move here`, they stay in the box and the sentence ends `; your words are still in the box`; a chat that opens by itself at launch has no typed words, so that ending is left off. It works as soon as codeaf runs there again: open a terminal, the app or its background engine on that computer, then choose `move here` again. -This happens while hosted sync storage is off, because blind pass-through carries the chat from the computer that has it. A chat that another of your computers has already taken can be served by that computer instead, so a third computer can take it from the second while the first is off. +This happens while hosted relay storage is off, because blind pass-through carries the chat from the computer that has it. A chat that another of your computers has already taken can be served by that computer instead, so a third computer can take it from the second while the first is off. If the other computer goes off after the chat has opened but before its files finish arriving, the chat stays open and the status line says `files couldn't arrive: · retry`. Once codeaf runs on that computer again, retrying fetches the rest. -A computer with blind pass-through turned off that meets such a chat on its list says so in a plain sentence instead of waiting: turn blind pass-through back on there. An older codeaf does not know blind pass-through and cannot fetch the chat; it ends `continue here` with its usual could-not-continue line, and your words stay in the box. Update codeaf there. +A computer with blind pass-through turned off that meets such a chat on its list says so in a plain sentence instead of waiting: turn blind pass-through back on there. An older codeaf does not know blind pass-through and cannot fetch the chat; it ends `move here` with its usual could-not-continue line, and your words stay in the box. Update codeaf there. ## Why a chat shows as untitled on my other computer — blind pass-through and chat titles -While blind pass-through is carrying chats, WorkAF reads the title directly from the computer that has the chat. The sync service keeps neither the title nor the folder name. If that computer is offline or runs an older version, Devices can show `untitled` until a title is available. After you move the chat, Devices reads the title from your local copy. +While blind pass-through is carrying chats, WorkAF reads the title directly from the computer that has the chat. The relay keeps neither the title nor the folder name. If that computer is offline or runs an older version, Devices can show `untitled` until a title is available. After you move the chat, Devices reads the title from your local copy. -In WorkAF’s Devices page, **Preview** reads a short excerpt of the last saved message and reply. When the saved chat is unavailable, **Details** shows its device and move status. You can choose **Continue here** from either view when the move is available. +In WorkAF’s Devices page, **Preview** reads a short excerpt of the last saved message and reply. When the saved chat is unavailable, **Details** shows its device and move status. You can choose **Move here** from either view when the move is available. ## Turn off blind pass-through — CODEAF_PASSTHROUGH=off, pass-through mode off switch -Set the environment variable `CODEAF_PASSTHROUGH=off` before starting codeaf to turn blind pass-through off. Chats then stay on the computer that has them while hosted sync storage is off, exactly as before blind pass-through existed: see *Continue a chat on its own computer while sync storage is off*. Any other value, or no value, leaves blind pass-through on. `codeaf help env` lists it. +Set the environment variable `CODEAF_PASSTHROUGH=off` before starting codeaf to turn blind pass-through off. Chats then stay on the computer that has them while hosted relay storage is off, exactly as before blind pass-through existed: see *Continue a chat on its own computer while relay storage is off*. Any other value, or no value, leaves blind pass-through on. `codeaf help env` lists it. -It changes nothing when sync storage is approved or when you use a self-hosted sync service: those behave exactly as before. It is not a Settings row, and it does not turn off pairing, `--at` or anything else. With sync off (`CODEAF_SYNC_URL=off`) nothing leaves the computer, so there is no blind pass-through either. +It changes nothing when relay storage is approved or when you use a self-hosted relay: those behave exactly as before. It is not a Settings row, and it does not turn off pairing, `--at` or anything else. With sync off (`CODEAF_SYNC_URL=off`) nothing leaves the computer, so there is no blind pass-through either. A computer with blind pass-through off that meets a chat living only on another computer says so in a plain sentence instead of waiting. The switch holds on a computer that already shared chats by blind pass-through too: while it is off, that computer neither answers for those chats nor fetches a chat from another computer. Set it on each computer where you want the previous behaviour. ## Idle chats release their hold — open on another paired computer, even when the first is off -**Settings → General → idle handoff** (`idle_handoff`, or `CODEAF_IDLE_HANDOFF=1`) is **off by default**: while off, open idle chats keep renewing their hold and a released remote chat still uses **Continue here**. When you turn `idle handoff` on with two or more paired computers (and sync storage on), an idle chat lets go of its hold about 2 seconds after it goes idle, once its saved turns, journal, working files, shared memory and settings are on the sync service. The open window stays as a reader. A running turn, queued or steering work, a running task or job, unsaved tail writes or an upload failure keeps the hold. Rebuildable folders such as `node_modules` follow the usual transfer exclusions. +**Settings → General → idle handoff** (`idle_handoff`, or `CODEAF_IDLE_HANDOFF=1`) is **off by default**: while off, open idle chats keep renewing their hold and a released remote chat still uses **Move here**. When you turn `idle handoff` on with two or more paired computers (and relay storage on), an idle chat lets go of its hold about 2 seconds after it goes idle, once its saved turns, journal, working files, shared memory and settings are on the relay. The open window stays as a reader. A running turn, queued or steering work, a running task or job, unsaved tail writes or an upload failure keeps the hold. Rebuildable folders such as `node_modules` follow the usual transfer exclusions. -With `idle handoff` on, a chat explicitly released by its holder opens directly on another paired computer with no Continue-here step: press Enter on terminal Home, or open its `can_open` row through `agents.open` in the app. The original computer can be off. A chat another computer still holds (`held on ` or `working on `, including an idle chat when `idle handoff` is off or on an older build that never releases) still asks, with **Move here** or **Continue here** as your choice. A hold that lapsed without a release also keeps that card, including one whose holder was working. This applies even when the last working state is unknown. Existing local edits use the ordinary kept-work rules during transfer. +With `idle handoff` on, a chat explicitly released by its holder opens directly on another paired computer with no Move-here step: press Enter on terminal Home, or open its `can_open` row through `agents.open` in the app. The original computer can be off. A chat another computer still holds (`held on ` or `working on `, including an idle chat when `idle handoff` is off or on an older build that never releases) still asks, with **Move here** as your choice. A hold that lapsed without a release also keeps that card, including one whose holder was working. This applies even when the last working state is unknown. Existing local edits use the ordinary kept-work rules during transfer. Sending new work in the window that released its idle hold takes the unchanged saved chat back in place, with no prompt, before recording your words or calling a model. If another computer took it, the window gets the held-elsewhere refusal. A hold that merely lapsed (not released by its window) admits nothing until you reopen or continue it. Only one computer can win a simultaneous open and send. A released window needs a successful ownership check before it can accept work; an outage leaves that work unsent. Unpaired, sync-off, single-device and default (`idle handoff` off) homes keep their hold while open. -## Continue on another computer — continuing a chat on another computer, why can't I type in this chat, my message did not send and home opened with a question +## Continue on another computer — continuing a chat on another computer, why can't I type in this chat, I cannot type in this chat, my message did not send and home opened with a question -While hosted sync storage is off, a chat still moves by blind pass-through between your paired computers when both are running codeaf; see *Blind pass-through*. +While hosted relay storage is off, a chat still moves by blind pass-through between your paired computers when both are running codeaf; see *Blind pass-through*. Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. @@ -84,9 +90,9 @@ Older chats move through an independent copy. Once paired, codeaf prepares chats A chat can be worked on by one device at a time. If you open a chat here that another of your devices is running right now, and you type a message and press enter, the message does not go to the chat. Home opens instead, with that chat's row under the cursor and the question up: ``` -Continue this chat here? +Move this chat here? held on tower; last saved turn 4s ago -1 continue here +1 move here 2 leave it there ``` @@ -94,7 +100,7 @@ Your words stay in the box. Nothing was sent, and no branch nobody asked for was An attended window keeps following your other devices while the chat is open, so a move is shown without returning to home first. Slash commands such as `/help` always work. -If you continue it, the other device's window stops taking new turns and says ` continued this chat. This copy is read-only and may be behind`. The page *Home* has the rest of that card. +If you continue it, the other device's window stops taking new turns and says ` moved this chat. This copy is read-only and may be behind`. The page *Home* has the rest of that card. ## Which folder does a continued chat use — repeated moves and long copy-folder names @@ -116,13 +122,13 @@ is needed for new work. An older chat's copy is kept in a folder called `.moving` beside the original, in codeaf's state folder for that project. The name is historical: nothing in it is a move in progress. It holds the live copies this build writes to, so deleting it deletes those chats. The folder carries a `README.txt` that says so. The originals beside it stay untouched for older codeaf builds. -## My typed message after continue here — is it kept, does it send by itself +## My typed message after move here — is it kept, does it send by itself before showing this question for a send, codeaf checks which computer holds the chat now. an older listing alone cannot raise it. if that check fails, nothing is sent and the whole message stays in the box, including pasted text and attachments. the chat says ` has not answered; your message is still in the box, press enter to send it`. press enter to check again. changing the draft while a check waits keeps the current words unsent; the chat says `draft changed before sending; press enter to send your current words`. a chat this window already holds, or one that has never been shared, sends without asking the service. an ordinary check for a shared copy waits up to five seconds. immediately after this window's own successful move, a message can wait up to 30 seconds for the chat to finish opening, then sends once. a window that lost the chat, or another window holding it, cannot give this window permission to send. -if Enter raised the continue card, a successful move restores those same words, pasted text and attachments and says `your message is still in the box; press enter to send it`. it waits for another enter. choosing `leave it there` or a failed move also keeps the whole draft. +if Enter raised the move card, a successful move restores those same words, pasted text and attachments and says `your message is still in the box; press enter to send it`. it waits for another enter. choosing `leave it there` or a failed move also keeps the whole draft. ## which draft comes back after continuing a chat @@ -138,15 +144,15 @@ Open `/task` and choose the finished task. Its saved worker conversation and ste Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. -On `Continue this chat here?`, `leave it there` closes the question without moving the chat. Your typed words stay in the box and nothing is sent. If the question opened because you tried to send from an older window, this answer is already selected. Choose `1 continue here` to bring the chat here before sending. +On `Move this chat here?`, `leave it there` closes the question without moving the chat. Your typed words stay in the box and nothing is sent. If the question opened because you tried to send from an older window, this answer is already selected. Choose `1 move here` to bring the chat here before sending. -## Esc on a continue card returns to my chat, and each card keeps its own draft +## Esc on a move card returns to my chat, and each card keeps its own draft -If Enter in a displaced chat raises the continue card, `esc` or `2 leave it there` returns to that same chat window with its full draft still in the box. If you opened the card from a Home row, leaving the card keeps you on Home. +If Enter in a displaced chat raises the move card, `esc` or `2 leave it there` returns to that same chat window with its full draft still in the box. If you opened the card from a Home row, leaving the card keeps you on Home. during an automatic continue, the first `esc` withdraws its opening and any waiting choice. the automatic chat is not opened: it finishes arriving and is let go, so it stays on this computer, free to continue from anywhere. a further `esc` navigates as usual while that finishes. if the abandoned move has not answered after two minutes, its request is cancelled before the waiting choice can begin. inspecting another chat's card and choosing `leave it there` or `esc` leaves the automatic arrival alone. -A continue card previews only that chat's unsent words, or nothing when no draft is available. Its project foot belongs to the selected chat. Words typed in another chat never appear on this card. Saved drafts belong to their chat even when a copied chat moves to a different project folder; opening another copy cannot adopt them. +A move card previews only that chat's unsent words, or nothing when no draft is available. Its project foot belongs to the selected chat. Words typed in another chat never appear on this card. Saved drafts belong to their chat even when a copied chat moves to a different project folder; opening another copy cannot adopt them. ## slow chat listing — waiting for a service, a timeout or an unreachable host @@ -154,33 +160,33 @@ at five seconds without a chat-list answer, Home says `waiting for ; still these are Home's listing sentences. a message left unsent by a failed send check gets its own explanation: ` has not answered; your message is still in the box, press enter to send it`. -## Continue a chat on its own computer while sync storage is off +## Continue a chat on its own computer while relay storage is off -This section describes the road used while sync storage is off when blind pass-through is off (`CODEAF_PASSTHROUGH=off`) or unavailable, for example when this computer has no other paired computer. With blind pass-through on, a chat moves between your computers live while both are running codeaf: see *Blind pass-through*. +This section describes the road used while relay storage is off when blind pass-through is off (`CODEAF_PASSTHROUGH=off`) or unavailable, for example when this computer has no other paired computer. With blind pass-through on, a chat moves between your computers live while both are running codeaf: see *Blind pass-through*. -Reading history already stored for your account needs no storage approval. With no local work to keep, `1 continue here` brings that recorded history here, even if this computer has no copy yet or its clean copy is older. +Reading history already stored for your account needs no storage approval. With no local work to keep, `1 move here` brings that recorded history here, even if this computer has no copy yet or its clean copy is older. -After a live `--at` session, come back to the original computer and choose `1 continue here`. If its local history contains the last shared turn and any later local turns, or no turn was shared yet, the chat continues in place. Every local turn stays, the continue card goes away, and you can send messages and use tools immediately. Nothing is uploaded while storage is off. Quit and reopen normally; after approval, opening the chat on this same computer publishes the preserved turns even if its earlier hold expired. +After a live `--at` session, come back to the original computer and choose `1 move here`. If its local history contains the last shared turn and any later local turns, or no turn was shared yet, the chat continues in place. Every local turn stays, the move card goes away, and you can send messages and use tools immediately. Nothing is uploaded while storage is off. Quit and reopen normally; after approval, opening the chat on this same computer publishes the preserved turns even if its earlier hold expired. -Keeping turns made here that another computer lacks waits for storage access only when they must be saved separately before replacing this copy. If those turns diverge from newer stored history, codeaf preserves them and says `cannot continue this chat here while sync storage is off because this computer is missing saved turns; your local turns stay here`. Your typed message stays in the box. Request access in Settings → Devices → sync storage before continuing this divergent copy. +Keeping turns made here that another computer lacks waits for storage access only when they must be saved separately before replacing this copy. If those turns diverge from newer stored history, codeaf preserves them and says `cannot move this chat here while relay storage is off because this computer is missing saved turns; your local turns stay here`. Your typed message stays in the box. Request access in Settings → Devices → relay storage before continuing this divergent copy. -## Tools stop when the chat moves away while sync storage is off — a running turn, its tools and saved turns +## Tools stop when the chat moves away while relay storage is off — a running turn, its tools and saved turns -This describes how tools are guarded while sync storage is off when blind pass-through is off or unavailable. With blind pass-through on, an ordinary chat is handled the way it is with sync storage on. +This describes how tools are guarded while relay storage is off when blind pass-through is off or unavailable. With blind pass-through on, an ordinary chat is handled the way it is with relay storage on. Before tools run in a shared chat while storage is off, codeaf checks who holds it. A reading is reused for at most 15 seconds with live updates, or two seconds without them. A change announced by the service refreshes it at once, even within those bounds. A failed reading is also reused for two seconds after it finishes. -When a reading finds another computer holding the chat, this window only shows the chat and refuses further tools, including commands and file edits. It stops saving new turns; saving work already accepted can finish. Choose `continue here` explicitly to resume writing. +When a reading finds another computer holding the chat, this window only shows the chat and refuses further tools, including commands and file edits. It stops saving new turns; saving work already accepted can finish. Choose `move here` explicitly to resume writing. An expired hold belonging to this computer or a free chat still allows tools. An unreachable service also allows local work; a chat never shared makes no ownership request. No uploads start while storage is off. -## Why does continue here say this chat was last held here — my only computer asks to continue +## Why does move here say this chat was last held here — my only computer asks to continue -A chat this computer held last can resume sending after its hold expires when nobody else holds it. While sync storage is off and blind pass-through is not carrying the chat, Enter sends without a question if the local history contains every shared turn, including when later turns stayed only here or nothing was shared yet. The conversation stays open and the storage-off sentence is not repeated after idle time. After approval, opening the chat here sends its preserved turns to your other computers. +A chat this computer held last can resume sending after its hold expires when nobody else holds it. While relay storage is off and blind pass-through is not carrying the chat, Enter sends without a question if the local history contains every shared turn, including when later turns stayed only here or nothing was shared yet. The conversation stays open and the storage-off sentence is not repeated after idle time. After approval, opening the chat here sends its preserved turns to your other computers. With storage on, differing saved turns still raise the question. Missing shared turns also require a choice or show the existing refusal while storage is off; local turns stay here. -The card still says `this chat was last held here; last saved turn 2h ago` when this window's own earlier move failed. Choose `continue here` to resume it. The landing says `Moved here` and never names this computer as somewhere the chat moved from. +The card still says `this chat was last held here; last saved turn 2h ago` when this window's own earlier move failed. Choose `move here` to resume it. The landing says `Moved here` and never names this computer as somewhere the chat moved from. If unpublished work needs to be kept separately, the number of kept turns counts conversation turns. Intermediate saves and tool records within one question and answer do not become extra turns. @@ -188,23 +194,23 @@ If unpublished work needs to be kept separately, the number of kept turns counts Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. -Home lists chats from your other devices. By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), an open idle chat keeps its hold and a released chat asks **Continue here**. With `idle handoff` on in paired computers, an idle chat lets go about 2 seconds after it goes idle once everything is on the sync service, and a released chat opens here directly: press enter on it to bring its latest saved copy here and open it directly (in the app, `agents.open` does the same on `can_open` rows). There is no Continue-here card for a released chat when `idle handoff` is on, and a free row shows no holder label. A lapsed hold on another computer keeps the card, including when its holder was working. +Home lists chats from your other devices. By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), an open idle chat keeps its hold and a released chat asks **Move here**. With `idle handoff` on in paired computers, an idle chat lets go about 2 seconds after it goes idle once everything is on the relay, and a released chat opens here directly: press enter on it to bring its latest saved copy here and open it directly (in the app, `agents.open` does the same on `can_open` rows). There is no Move-here card for a released chat when `idle handoff` is on, and a free row shows no holder label. A lapsed hold on another computer keeps the card, including when its holder was working. -A chat with a live hold on another device says `held on ` when it is open there with nothing running in it right now, and `working on ` while that device is in the middle of a turn; it changes back as soon as the turn ends. A sync service too old to carry that word shows `held on ` either way, so a hold alone does not establish that work is running there. When a computer stops answering without letting go (for example its lid closed), its row says ` offline`; offline alone does not make a live hold free. +A chat with a live hold on another device says `held on ` when it is open there with nothing running in it right now, and `working on ` while that device is in the middle of a turn; it changes back as soon as the turn ends. A relay too old to carry that word shows `held on ` either way, so a hold alone does not establish that work is running there. When a computer stops answering without letting go (for example its lid closed), its row says ` offline`; offline alone does not make a live hold free. -Opening a chat with a live hold still asks before moving it, with **Move here** or **Continue here** as your choice: the devices row offers **Move here** while it is running there and **Continue here** when it went off, and Enter on Home's row opens the `Continue this chat here?` card showing how fresh the copy is and how many turns may still be there (`esc` leaves it there). Watching never takes a live hold. +Opening a chat with a live hold still asks before moving it: the devices row offers **Move here** whether the chat is running there or went off, and Enter on Home's row opens the `Move this chat here?` card showing how fresh the copy is and how many turns may still be there (`esc` leaves it there). With remote control on and that computer online, Enter on a chat it is running opens the chat live instead, and the card is `alt+m` on Home (the page *Remote control* has the rest). Watching never takes a live hold. ## Continue on this machine — Continue where you left off, alt+c and alt+x -While hosted sync storage is off, a chat on a computer that is not running codeaf cannot be taken: `continue here` says ` has this chat and is not on right now; open codeaf there, then continue here`. See *Continue here says the computer that has this chat is not on*. +While hosted relay storage is off, a chat on a computer that is not running codeaf cannot be taken: `move here` says ` has this chat and is not on right now; open codeaf there, then move here`. See *Move here says the computer that has this chat is not on*. Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. If you open codeaf and a chat on another device was running or went off in the last 24 hours, and that device is offline now (its lid is closed) or has let go of the chat, home offers it first of all: ``` -Continue tower's latest chat here? -alt+c continue here · alt+x not now +Move tower's latest chat here? +alt+c move here · alt+x not now ``` - `alt+c` continues immediately. The card asks first only when there is a real choice, such as keeping unsaved local edits as a branch. @@ -215,7 +221,7 @@ The line follows the devices row: it stands while the device is offline or has l Home never offers this computer's own chat as work to continue from another computer, even when an older record says this computer went offline. -To bring work from a device that is online, use the devices row: `alt+m bring work here`. The page *Adding a device to your devices, approving it, and removing it* shows the row and the dots. +To bring work from a device that is online, use the devices row: `alt+m move here`. The page *Adding a device to your devices, approving it, and removing it* shows the row and the dots. ## What happens when the chat arrives — the banner Moved from tower, and what was not brought @@ -275,13 +281,13 @@ The file tools also map an absolute path under the original folder to the same r Taking a chat back into its original project restores that project in place. The agent is told about the return too; old paths from the other computer's copy now map back into the original project. -## I deleted the project folder a chat worked in — will it still continue here, or say could not be put in this folder +## I deleted the project folder a chat worked in — will it still move here, or say could not be put in this folder -Yes. When the folder a chat worked in on this computer was deleted, `continue here` and the automatic move at startup both open the chat. A folder that is not there holds no files to keep, so only the conversation is checked: the chat arrives the way a chat from another computer does, in a folder of its own under this computer's chats, with every file as the other computer left it, and the line `Moved from in . Everything as you left it.` The deleted folder is not made again and nothing is written to its old path. +Yes. When the folder a chat worked in on this computer was deleted, `move here` and the automatic move at startup both open the chat. A folder that is not there holds no files to keep, so only the conversation is checked: the chat arrives the way a chat from another computer does, in a folder of its own under this computer's chats, with every file as the other computer left it, and the line `Moved from in . Everything as you left it.` The deleted folder is not made again and nothing is written to its old path. If the conversation here holds turns that were never shared, the move asks first, as it does for any unsaved work, and keeps those turns as a separate copy of the chat before the files arrive; the deleted folder's files are not part of that copy. The engine log says `continuation: the chat's folder is gone, so there are no local files to keep; checking only the conversation` each time the check meets a deleted folder. -A path that exists but is not a folder, or one this computer may not look at, is not treated as deleted. The move stops there and says `could not check this computer's copy before continuing; your words are still in the box`. +A path that exists but is not a folder, or one this computer may not look at, is not treated as deleted. The move stops there and says `could not check this computer's copy before moving; your words are still in the box`. ## Why does the project label say copy from another machine @@ -301,84 +307,84 @@ codeaf's own capture policy follows Git's repository discovery when `GIT_CEILING If the workspace's own `.furrowpolicy` contains `gitignore`, the native capture engine still uses its separate ignore discovery. It can find an enclosing checkout beyond the ceiling and omit the workspace's files. That case needs an engine fix. -If an older build saved an empty chat and the workspace does not enable `gitignore` in its own `.furrowpolicy`, open the original chat in this build, send another message and close it before trying `continue here` again. +If an older build saved an empty chat and the workspace does not enable `gitignore` in its own `.furrowpolicy`, open the original chat in this build, send another message and close it before trying `move here` again. -## This chat is not syncing — the sync service is not answering, working offline +## This chat is not syncing — the relay is not answering, working offline If this computer holds the chat and renewals have failed for longer than one renewal period, one dim line says -`the sync service at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back`. +`the relay at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back`. It is said once per outage. When renewals succeed again, one line says `this chat is syncing again`. You can keep working here while offline. If another computer continued the -chat meanwhile, the existing ` continued this chat; this window now +chat meanwhile, the existing ` moved this chat; this window now only shows it` notice still applies. ## Reopen a kept copy after another computer takes the chat When unsent turns were kept as a separate copy, reopening that copy checks who holds the copy itself. Another computer may still hold the original chat. The previous window finishes saving and stops syncing before the reopened copy starts its own sync, so a late save cannot change which copy it opens. Taking that copy elsewhere still stops new tool work in its older window. -## Continue here does nothing — continue here did nothing, the engine store is busy, or a chat is already continuing here +## Move here does nothing — move here did nothing, the engine store is busy, or a chat is already moving here Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. -while a chat you explicitly chose is moving here, Home's bottom line says `opening conversation…` with the bytes received so far (`opening conversation… 24 KB`, updated every 500 ms; or `copying to this computer: …` when `CODEAF_MOVE_FILES_FIRST=1` is set, and `continuing here…` before byte progress begins). another explicit continue during that move says `a chat is already continuing here; wait for it to open` on the card. an automatic startup move instead lets your explicit choice go next; see “my choice while an automatic chat is arriving”. +while a chat you explicitly chose is moving here, Home's bottom line says `opening conversation…` with the bytes received so far (`opening conversation… 24 KB`, updated every 500 ms; or `copying to this computer: …` when `CODEAF_MOVE_FILES_FIRST=1` is set, and `moving here…` before byte progress begins). another explicit continue during that move says `a chat is already moving here; wait for it to open` on the card. an automatic startup move instead lets your explicit choice go next; see “my choice while an automatic chat is arriving”. -every failure stays where you are looking: on Home's card with `1 retry` and `2 leave it there`, or inside the open chat window. a fresh reading decides whether a different computer continued first. if the same computer picked the chat up again, the card asks again with ` picked this chat up again; press enter to continue it here`. The desktop's `agents.take` refusal says ` picked this chat up again`, keeping its `conflict` code and `holder_changed` detail. Nothing is taken by either refusal. +every failure stays where you are looking: on Home's card with `1 retry` and `2 leave it there`, or inside the open chat window. a fresh reading decides whether a different computer continued first. if the same computer picked the chat up again, the card asks again with ` picked this chat up again; press enter to move it here`. The desktop's `agents.take` refusal says ` picked this chat up again`, keeping its `conflict` code and `holder_changed` detail. Nothing is taken by either refusal. -## why continue here failed — retry or leave it there +## why move here failed — retry or leave it there a failed move keeps the draft and shows `1 retry` and `2 leave it there`. retry confirms the holder and turn of ownership now displayed on that card. -- `another device continued this chat first`: another device was faster. The row goes back to `held on `. Nothing changed. -- `the sync service is not answering`: this device cannot reach the service. Nothing can be moved until it can. -- ` has this chat and is not on right now; open codeaf there, then continue here`: sync storage is off and codeaf is not running on that computer. Open it there, then choose `retry`. Nothing changed. -- `could not continue this chat here because the engine store is busy` or `could not continue this chat here because the engine store is busy (held by codeaf chat, pid 4321)`: another `codeaf` process holds this computer's engine store writer. Close or finish that process, then choose `retry`. -- `could not check this computer's copy before continuing; your words are still in the box`: the look at what this computer holds for the chat, which comes before anything is moved, could not finish. Nothing was put in any folder and the chat stays where it was; the engine log has the reason after `continue chat `. A folder that was deleted is not a reason: see *I deleted the project folder a chat worked in*. -- `could not continue this chat here`: the move failed. The row stays where it was; choose `retry` or try again. -- A move does not fail because another chat on this computer is saving its secrets to the sync service at that moment. Its last step waits up to 30 seconds for that save to finish, then arrives. -- `could not continue this chat here because the sync service is not answering; your words are still in the box`: the service went away during the move. Nothing was sent and the chat stays where it was; send again once the other machines are reachable. +- `another device moved this chat first`: another device was faster. The row goes back to `held on `. Nothing changed. +- `the relay is not answering`: this device cannot reach the service. Nothing can be moved until it can. +- ` has this chat and is not on right now; open codeaf there, then move here`: relay storage is off and codeaf is not running on that computer. Open it there, then choose `retry`. Nothing changed. +- `could not move this chat here because the engine store is busy` or `could not move this chat here because the engine store is busy (held by codeaf chat, pid 4321)`: another `codeaf` process holds this computer's engine store writer. Close or finish that process, then choose `retry`. +- `could not check this computer's copy before moving; your words are still in the box`: the look at what this computer holds for the chat, which comes before anything is moved, could not finish. Nothing was put in any folder and the chat stays where it was; the engine log has the reason after `continue chat `. A folder that was deleted is not a reason: see *I deleted the project folder a chat worked in*. +- `could not move this chat here`: the move failed. The row stays where it was; choose `retry` or try again. +- A move does not fail because another chat on this computer is saving its secrets to the relay at that moment. Its last step waits up to 30 seconds for that save to finish, then arrives. +- `could not move this chat here because the relay is not answering; your words are still in the box`: the service went away during the move. Nothing was sent and the chat stays where it was; send again once the other machines are reachable. ## Why can't I take an open chat from another computer — older relays and --host -- `taking an open chat from another computer waits for a sync service update; all else works, so close it there and continue here` means the chat is open on another computer and the sync service is too old to take it from there safely. Everything else works, including continuing a chat the other computer has closed. Close the chat on that computer, then choose `continue here` again. -- Under `codeaf chat --host`, `continue here` is not offered and a chat the remote host already holds never shows as held elsewhere. With no way to continue set up, an off row has no `continue here`: enter says why. +- `taking an open chat from another computer waits for a relay update; all else works, so close it there and move it here` means the chat is open on another computer and the relay is too old to take it from there safely. Everything else works, including continuing a chat the other computer has closed. Close the chat on that computer, then choose `move here` again. +- Under `codeaf chat --host`, `move here` is not offered and a chat the remote host already holds never shows as held elsewhere. With no way to continue set up, an off row has no `move here`: enter says why. ## taking a chat back, and two computers continuing the same chat — which one opens Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. -A chat has one holder at a time. To take a chat back from the computer that took it, press enter on its row on that computer: choose `continue here` by default (`idle handoff` is off by default; when turned on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`, a released paired chat opens directly while a live hold or a lapsed hold on another computer still asks for `continue here`). Nothing has to be returned or switched off first. A computer with the chat open when another takes it says ` continued this chat. This copy is read-only and may be behind`, stops taking new turns, and keeps what it had not yet sent as a branch (` turns from : open separately / discard`). A tool call the model tries there answers with that same line. Taking the chat back leaves a `node_modules` or other install folder that computer already has alone. +A chat has one holder at a time. To take a chat back from the computer that took it, press enter on its row on that computer: choose `move here` by default (`idle handoff` is off by default; when turned on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`, a released paired chat opens directly while a live hold or a lapsed hold on another computer still asks for `move here`). Nothing has to be returned or switched off first. A computer with the chat open when another takes it says ` moved this chat. This copy is read-only and may be behind`, stops taking new turns, and keeps what it had not yet sent as a branch (` turns from : open separately / discard`). A tool call the model tries there answers with that same line. Taking the chat back leaves a `node_modules` or other install folder that computer already has alone. -The choice covers the holder and turn of ownership shown on the card. If another computer continues the chat before you confirm or while the copy is arriving, your choice cannot take it from that new holder. The slower one sees `another device continued this chat first` on the card with `1 retry` and `2 leave it there`; its local copy is not replaced, and its row goes back to `held on `. if the same holder picked it up again, the refreshed card says ` picked this chat up again; press enter to continue it here` and asks for a new confirmation instead. a complete chat already held here gets one silent recovery attempt; another disagreement keeps the retry card and draft. No turn is lost on either side: whatever the earlier holder had not sent is kept for you as the branch above. This build offers discard, which archives a branch, and opening the branch as a separate chat; merging it into the original chat is unavailable. Pressing `2` (`leave it there`) on the question, or `esc`, changes nothing and leaves the chat where it is. +The choice covers the holder and turn of ownership shown on the card. If another computer continues the chat before you confirm or while the copy is arriving, your choice cannot take it from that new holder. The slower one sees `another device moved this chat first` on the card with `1 retry` and `2 leave it there`; its local copy is not replaced, and its row goes back to `held on `. if the same holder picked it up again, the refreshed card says ` picked this chat up again; press enter to move it here` and asks for a new confirmation instead. a complete chat already held here gets one silent recovery attempt; another disagreement keeps the retry card and draft. No turn is lost on either side: whatever the earlier holder had not sent is kept for you as the branch above. This build offers discard, which archives a branch, and opening the branch as a separate chat; merging it into the original chat is unavailable. Pressing `2` (`leave it there`) on the question, or `esc`, changes nothing and leaves the chat where it is. ## Can tools run after taking a chat back and restarting? -After a successful take-back through `continue here`, tools run here again, +After a successful take-back through `move here`, tools run here again, including after a restart. Earlier retained turns remain available as a separate branch, and the original chat includes the other computer's saved work. ## This window only shows the chat — can I still send here Once this window learns that another computer holds the chat, Enter opens -**Continue this chat here?** and keeps your words unsent. This applies as soon -as the live update or the ` continued this chat; this window now only +**Move this chat here?** and keeps your words unsent. This applies as soon +as the live update or the ` moved this chat; this window now only shows it` notice arrives; it does not wait for the next background ownership check. Enter cannot start a reply, publish a turn or create a separate chat -from this displaced window. Open the latest chat from Home to bring it back before sending (choose `continue here` by default; with `idle handoff` on, a released paired chat opens directly while a live hold or a lapsed hold on another computer still asks for `continue here`). +from this displaced window. With remote control on, a window whose chat another computer moved opens a live view of the computer that has it now, marked `on · live`, instead of staying a read-only copy (the page *Remote control*). The computer that took it may still be opening the chat when this window first asks, so the window asks again a few times over the next half minute, and the read-only sentence stays until one of those asks gets through. Open the latest chat from Home to bring it back before sending (choose `move here` by default; with `idle handoff` on, a released paired chat opens directly while a live hold or a lapsed hold on another computer still asks for `move here`). A chat this computer still holds sends on one Enter without an extra request -to the sync service. A chat that has never been shared does too. +to the relay. A chat that has never been shared does too. ## Take my chat back after a crash, a killed process or a power loss If this computer was killed and another computer continued the chat, reopen -codeaf and open the chat from Home: choose **continue here** by default (`idle handoff` off), or with `idle handoff` on a released paired chat opens directly while a live hold or a lapsed hold on another computer still asks for **continue here**, as does the question raised by Enter in the old local copy. The move brings the latest saved chat here and +codeaf and open the chat from Home: choose **move here** by default (`idle handoff` off), or with `idle handoff` on a released paired chat opens directly while a live hold or a lapsed hold on another computer still asks for **move here**, as does the question raised by Enter in the old local copy. The move brings the latest saved chat here and says `Moved from `. An old saved hold cannot keep the chat here or make that copy send a message. The question uses the other computer and last -saved turn reported by the sync service. An offline holder is named as +saved turn reported by the relay. An offline holder is named as ` offline; last saved turn ago`. Turns and file edits that never reached the service are kept separately before @@ -389,7 +395,7 @@ need another upload before the move. Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. -Reopening an older copy does not replace newer history on your other devices, even if the other computer has closed the chat. By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), this window only shows its local copy until you choose `continue here`. On paired computers with `idle handoff` on, opening a released chat from Home brings the latest saved history here automatically before you can write, including when an older viewer tab is already open. An older local copy does not overwrite newer history. A live hold or a lapsed hold on another computer still asks for Continue here, including when that holder was working. +Reopening an older copy does not replace newer history on your other devices, even if the other computer has closed the chat. By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), this window only shows its local copy until you choose `move here`. On paired computers with `idle handoff` on, opening a released chat from Home brings the latest saved history here automatically before you can write, including when an older viewer tab is already open. An older local copy does not overwrite newer history. A live hold or a lapsed hold on another computer still asks for Move here, including when that holder was working. An already-open older window remains a reader after another computer continues the chat. Sending there refuses before recording your words. Open the latest chat from Home to resume it; if its hold is still live elsewhere (or `idle handoff` is off), the move remains your choice. @@ -411,9 +417,9 @@ Old unidentified calls use settled ledger rows as an ordered prefix. New live ro Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. -When you continue a chat here, codeaf fetches the conversation records and claims the hold first, so the chat opens and accepts typing in about a second without waiting for the workspace files to finish copying. While those conversation records are being swapped into place, pressing enter on its row says `this chat is arriving on this computer; it opens by itself in a moment`. Opening a second window during that brief swap is refused so no window reads the journal as it was before the move. +When you move a chat here, codeaf fetches the conversation records and claims the hold first, so the chat opens and accepts typing in about a second without waiting for the workspace files to finish copying. While those conversation records are being swapped into place, pressing enter on its row says `this chat is arriving on this computer; it opens by itself in a moment`. Opening a second window during that brief swap is refused so no window reads the journal as it was before the move. -When the holder stops answering (for example, its lid is shut), the row may read ` offline`. While its hold is live, Continue here still asks and the card says `last saved turn ago; up to turns may still be on `. Once the holder releases the hold, Continue here brings it here by default (`idle handoff` is off by default; when turned on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`, opening the paired released chat brings it here directly). A hold that merely lapses keeps the Continue-here card, including when its holder was working or its last working state is unknown. +When the holder stops answering (for example, its lid is shut), the row may read ` offline`. While its hold is live, Move here still asks and the card says `last saved turn ago; up to turns may still be on `. Once the holder releases the hold, Move here brings it here by default (`idle handoff` is off by default; when turned on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`, opening the paired released chat brings it here directly). A hold that merely lapses keeps the Move-here card, including when its holder was working or its last working state is unknown. Turns that never left that computer are not in the copy you get. If its window is still running when it reconnects, it keeps those turns as a branch. After a restart, opening the latest copy keeps unpublished local turns and workspace edits as a branch before replacing them. Open the branch separately or discard it. Merging into the original chat is unavailable. @@ -423,13 +429,13 @@ When you continue a chat from another computer, Home's bottom line shows `openin Workspace files keep arriving in the background after the chat opens. While they arrive, the status line says `files arriving` with the bytes copied so far (for example `files arriving · 40 of 112 MB` or `files arriving · 12 MB`, never `0 of 0`), and clears when the folder is in place. You can type and send messages while files are still arriving, and the model can answer in words immediately. Any tool or command that reads or writes the workspace or runs in it waits for the files to finish arriving (bounded by the 2-minute stall limit) rather than seeing a half-arrived folder. -Each object download is retried at least 3 times with backoff on transient errors before it counts as failed. If the background download still fails, the chat stays open, tools keep waiting rather than running on a partial tree, and the status line names the problem in plain words with a retry (`files couldn't arrive: · retry`). Retrying (`/retry` or the next tool call) keeps the objects already downloaded. The refusal holds in every window and process on this computer that works in that folder, each with the same reason, however long the failure is old: it does not run out on a timer, and it ends when a retry succeeds. If the window that was bringing the files closes first, the refusal stays, with the same reason and `the window that was fetching them has closed, so continue the chat here again to fetch them`, because the folder is only part of the chat's files and nothing should use or save it as if it were the whole. Opening the chat again (Home, then the chat; `/resume`; resuming it from the terminal; or `agents.open` in the app) fetches the files again without moving the chat, so a chat this computer holds has nothing else to press: this computer keeps its hold, nothing is set aside or saved from the partial folder, the open is not held up while the files come, the status line says `files arriving` again, and the refusal clears when the files have landed. An open never starts a second fetch beside a window that is still bringing the files, and with the sync service out of reach the chat opens as it was and the refusal stays. A chat that another computer holds now is not fetched by opening it and still refuses, with the same words; continue it here from Home (or `agents.take` in the app) to fetch it then. Set `CODEAF_MOVE_FILES_FIRST=1` to restore the old order that downloads and puts all workspace files in place before opening the chat and shows the `copying to this computer` counter on Home while they copy. +Each object download is retried at least 3 times with backoff on transient errors before it counts as failed. If the background download still fails, the chat stays open, tools keep waiting rather than running on a partial tree, and the status line names the problem in plain words with a retry (`files couldn't arrive: · retry`). Retrying (`/retry` or the next tool call) keeps the objects already downloaded. The refusal holds in every window and process on this computer that works in that folder, each with the same reason, however long the failure is old: it does not run out on a timer, and it ends when a retry succeeds. If the window that was bringing the files closes first, the refusal stays, with the same reason and `the window that was fetching them has closed, so move the chat here again to fetch them`, because the folder is only part of the chat's files and nothing should use or save it as if it were the whole. Opening the chat again (Home, then the chat; `/resume`; resuming it from the terminal; or `agents.open` in the app) fetches the files again without moving the chat, so a chat this computer holds has nothing else to press: this computer keeps its hold, nothing is set aside or saved from the partial folder, the open is not held up while the files come, the status line says `files arriving` again, and the refusal clears when the files have landed. An open never starts a second fetch beside a window that is still bringing the files, and with the relay out of reach the chat opens as it was and the refusal stays. A chat that another computer holds now is not fetched by opening it and still refuses, with the same words; move it here from Home (or `agents.take` in the app) to fetch it then. Set `CODEAF_MOVE_FILES_FIRST=1` to restore the old order that downloads and puts all workspace files in place before opening the chat and shows the `copying to this computer` counter on Home while they copy. ## Were my own changes in the folder kept or written over when the files arrived — unsaved edits here, could not be kept yet -When a chat opens before its files arrive, this computer's older copy of the folder may hold a change that was never shared: an edited file, a new file, or something inside `.git` such as a half-written commit message (`.git/COMMIT_EDITMSG`). Before the arriving files replace that folder, codeaf keeps the change as a separate copy of the chat on the sync service and says `your unsaved edits here were kept as turns from `. That sentence can come a few seconds after the chat opens, because the check for a change runs behind the opening when this computer has no saved record that the folder is untouched. The opening line `Moved from in . Everything as you left it.` is about the conversation and does not wait for it. Open or discard the kept turns with `→` then `k`, as described above. +When a chat opens before its files arrive, this computer's older copy of the folder may hold a change that was never shared: an edited file, a new file, or something inside `.git` such as a half-written commit message (`.git/COMMIT_EDITMSG`). Before the arriving files replace that folder, codeaf keeps the change as a separate copy of the chat on the relay and says `your unsaved edits here were kept as turns from `. That sentence can come a few seconds after the chat opens, because the check for a change runs behind the opening when this computer has no saved record that the folder is untouched. The opening line `Moved from in . Everything as you left it.` is about the conversation and does not wait for it. Open or discard the kept turns with `→` then `k`, as described above. -If the change cannot be kept, for example because sync cannot be reached, the files from the other computer are not put in place. The folder here stays exactly as it is, tools that use the folder keep waiting, and the chat says `your unsaved edits here could not be kept yet (), so the files here are left as they are`. The status line shows `files couldn't arrive: your unsaved edits here could not be kept yet () · retry`. Retrying tries to keep the change again, and once it is kept the files arrive. Nothing is replaced and nothing is said to be kept until the kept copy exists on the sync service. +If the change cannot be kept, for example because sync cannot be reached, the files from the other computer are not put in place. The folder here stays exactly as it is, tools that use the folder keep waiting, and the chat says `your unsaved edits here could not be kept yet (), so the files here are left as they are`. The status line shows `files couldn't arrive: your unsaved edits here could not be kept yet () · retry`. Retrying tries to keep the change again, and once it is kept the files arrive. Nothing is replaced and nothing is said to be kept until the kept copy exists on the relay. ## Can the chat on the other computer still open the job logs it mentions — logs, saved tool output, task journals and the task history after a move @@ -447,9 +453,9 @@ Two things are made again on the other computer and are not carried: the project Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. -Your repository's `.git`, including its history, branches and settings, moves with the chat to your own paired devices. A task's commits travel too, and its working-copy bookkeeping is rebuilt on arrival. A key in an old commit remains in that history: codeaf does not remove or rewrite it. Git history travels sealed end to end; the sync service sees only ciphertext, including when the history contains keys. +Your repository's `.git`, including its history, branches and settings, moves with the chat to your own paired devices. A task's commits travel too, and its working-copy bookkeeping is rebuilt on arrival. A key in an old commit remains in that history: codeaf does not remove or rewrite it. Git history travels sealed end to end; the relay sees only ciphertext, including when the history contains keys. -The current working files are checked separately. A `.env` or source file that the guard recognises as holding a key is left out of the chat's file capture and carried on its own: through the encrypted vault when sync storage is approved, and by blind pass-through with the chat while sync storage is off (*Do my .env files and secrets move to my other computer without sync storage*). If you committed that secret earlier, its historical Git copy still moves with the repository. An untracked `.env` with no committed copy arrives only by that separate road. +The current working files are checked separately. A `.env` or source file that the guard recognises as holding a key is left out of the chat's file capture and carried on its own: through the encrypted vault when relay storage is approved, and by blind pass-through with the chat while relay storage is off (*Do my .env files and secrets move to my other computer without relay storage*). If you committed that secret earlier, its historical Git copy still moves with the repository. An untracked `.env` with no committed copy arrives only by that separate road. ## How are secret files screened before saving or moving a chat — .env, ignored folders and changing files @@ -467,7 +473,7 @@ A vault that already held such a file from an earlier build drops that entry the Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. -The first screen draws while this computer publishes its device record, shares its saved keys and sends the first saved turn in the background. A slow sync service does not leave the terminal blank. New tool work waits for the initial ownership check; local startup saves are sent once that check finishes. +The first screen draws while this computer publishes its device record, shares its saved keys and sends the first saved turn in the background. A slow relay does not leave the terminal blank. New tool work waits for the initial ownership check; local startup saves are sent once that check finishes. ## Does every chat copy my whole project — disk space, shared saved files, older chats @@ -491,7 +497,7 @@ Quitting another chat does not invalidate a chat's earlier confirmed local save. A save wait lasts at most 30 seconds. After the screen closes, a pending sync save says `saving this chat to your other devices…`. After about three seconds, a confirmed local save adds `still saving — ctrl+c leaves it saved here`; without confirmation, it says `still saving on this computer — ctrl+c leaves the written turns here`. -If the turns are saved locally but not uploaded, the final sentence is `saved here; it reaches your other devices when the sync service at 127.0.0.1:8901 answers`, using your service’s host. If that pending upload was refused because storage is off, the successful receipt is `saved here; sync storage is off for this account, so it stays on this computer`. That is a successful exit. Ctrl+c during this wait leaves promptly with the same receipt when local saving is confirmed. Without confirmation, it says `saving on this computer has not finished; its written turns stay here` and exits unsuccessfully. Only a failed local write says `codeaf could not save this chat`; that failure may include the local recovery path. +If the turns are saved locally but not uploaded, the final sentence is `saved here; it reaches your other devices when the relay at 127.0.0.1:8901 answers`, using your service’s host. If that pending upload was refused because storage is off, the successful receipt is `saved here; relay storage is off for this account, so it stays on this computer`. That is a successful exit. Ctrl+c during this wait leaves promptly with the same receipt when local saving is confirmed. Without confirmation, it says `saving on this computer has not finished; its written turns stay here` and exits unsuccessfully. Only a failed local write says `codeaf could not save this chat`; that failure may include the local recovery path. If the last upload fails when you quit, for example because the connection dropped, this computer does not let the chat go. Your other computer keeps showing it as running here and does not open the older save by itself; the unsent turns stay on this computer until an upload succeeds. @@ -510,7 +516,7 @@ Device presence can arrive before its list of chats. If you press `alt+m` early, What a move costs depends on what this computer already has. - **Moving a chat back** to a computer that held it before downloads only what the other computer changed. In a big folder, the rest of the move stays a second or two, plus the download. -- **A chat this computer never held** copies its whole saved folder. It takes as long as sending that many bytes through your connection to the sync service. +- **A chat this computer never held** copies its whole saved folder. It takes as long as sending that many bytes through your connection to the server. - **Taking a chat from a computer that is off** also restores this computer's own copy of the folder. On a large folder that adds a few seconds. Before a move restores files into your folder, codeaf checks the files there for secrets. A file this running codeaf has already checked, and that has not changed since, is not read again. A file that changed is read again. After codeaf restarts, its first move in a folder reads every file once. It remembers at most 100,000 files. Files beyond that are read again on every move. @@ -521,7 +527,7 @@ a chat this computer has never held opens as soon as its conversation records an ## Does first start send anything — local identity before pairing -The first start may create a local identity for this computer. That file sends nothing: there is no sync traffic or network use until you pair or offer a pairing code. Reading the add-device instructions leaves it quiet. Offering a pairing code or running `codeaf pair` contacts the sync service for that pairing only: chats start syncing once you approve the other computer, and a code that is taken back, runs out, is answered no or is used up by a wrong code leaves this computer quiet. `CODEAF_SYNC_URL=off` blocks sync traffic even after pairing. +The first start may create a local identity for this computer. That file sends nothing: there is no sync traffic or network use until you pair or offer a pairing code. Reading the add-device instructions leaves it quiet. Offering a pairing code or running `codeaf pair` contacts the relay for that pairing only: chats start syncing once you approve the other computer, and a code that is taken back, runs out, is answered no or is used up by a wrong code leaves this computer quiet. `CODEAF_SYNC_URL=off` blocks sync traffic even after pairing. ## What survives a crash or power loss — durability, killed process, lost call records @@ -560,21 +566,21 @@ show no warning rather than guessing. A headless open does not consume the notic ## I quit on my laptop and opened my desktop — do I need alt+c -While hosted sync storage is off, `idle handoff` does not run, and a laptop where codeaf has quit cannot hand the chat over: the desktop can take it only while codeaf is running on the laptop (a terminal, the app or its background engine). See *Blind pass-through*. +While hosted relay storage is off, `idle handoff` does not run, and a laptop where codeaf has quit cannot hand the chat over: the desktop can take it only while codeaf is running on the laptop (a terminal, the app or its background engine). See *Blind pass-through*. -A clean quit lets go after the last save is durable, and when **Settings → General → idle handoff** (`CODEAF_IDLE_HANDOFF=1`, off by default) is turned on, an idle paired chat also lets go about 2 seconds after it goes idle once everything is on the sync service. Opening bare `codeaf` on your other paired computer within 24 hours continues the released chat automatically, with the usual `Moved from` banner and `not brought along:` lines. `esc` goes Home. A laptop that went to sleep while still holding the chat (for example mid-turn, before the save finished, while `idle handoff` is off, or on an older build) has not let go: while its hold is live, Home offers the chat and `alt+c` continues it, asking only if local work needs a choice; once the hold lapses, pressing Enter on its Home row still asks Continue here. +A clean quit lets go after the last save is durable, and when **Settings → General → idle handoff** (`CODEAF_IDLE_HANDOFF=1`, off by default) is turned on, an idle paired chat also lets go about 2 seconds after it goes idle once everything is on the relay. Opening bare `codeaf` on your other paired computer within 24 hours continues the released chat automatically, with the usual `Moved from` banner and `not brought along:` lines. `esc` goes Home. A laptop that went to sleep while still holding the chat (for example mid-turn, before the save finished, while `idle handoff` is off, or on an older build) has not let go: while its hold is live, Home offers the chat and `alt+c` continues it, asking only if local work needs a choice; once the hold lapses, pressing Enter on its Home row still asks Move here. If this computer is also coordinating, a clean terminal quit releases its idle chats and returns coordination to an anchor before stopping. With the anchors reachable, the other computer can continue immediately. Sleep, a crash or a lost connection still use the fallback described on the coordination and workers page. after the chat arrives, enter can wait up to 30 seconds for this window to finish opening the chat before sending once. if the check fails, it says ` has not answered; your message is still in the box, press enter to send it`. the window keeps following changes, including renamed computers and a later move to another computer. -A running chat on the other computer never moves automatically. Neither does a named chat, `--host`, `--at` or `--session`, a chat with unsaved local edits, or a launch while another local window already has a chat open. if the service cannot be reached, Home names its host and keeps trying. if another computer got there first, the refreshed continue card explains the change and keeps the local chat as it was. +A running chat on the other computer never moves automatically. Neither does a named chat, `--host`, `--at` or `--session`, a chat with unsaved local edits, or a launch while another local window already has a chat open. if the service cannot be reached, Home names its host and keeps trying. if another computer got there first, the refreshed move card explains the change and keeps the local chat as it was. ## my choice while an automatic chat is arriving — continue a different chat, join it or cancel bare startup still chooses the most recently released eligible chat and checks local safety first. input before that check answers cancels the automatic choice. -if its move is already running, confirming a different chat on Home or using `alt+c` chooses what opens next. Home says `continuing next; is still on its way here`, with the titles from the continue cards. the automatic move settles first and is let go with its files and kept work intact; it never opens over your choice. the next move uses exactly the computer and turn of ownership you confirmed. `esc` cancels the waiting choice and the automatic chat still settles and is let go. +if its move is already running, confirming a different chat on Home or using `alt+c` chooses what opens next. Home says `moving next; is still on its way here`, with the titles from the move cards. the automatic move settles first and is let go with its files and kept work intact; it never opens over your choice. the next move uses exactly the computer and turn of ownership you confirmed. `esc` cancels the waiting choice and the automatic chat still settles and is let go. confirming the automatic chat itself joins its move and opens it once. explicitly opening another local chat or starting a new one also prevents a late automatic arrival from replacing it. moving the cursor, opening Home or inspecting and declining another card does not choose a different chat. an explicit move already in progress still gives the usual busy sentence for another explicit pick. @@ -586,7 +592,7 @@ An older chat that worked in your home folder, or in a folder that holds it, is ## A save has not reached the other computer yet — upload failed or another device continued first -While hosted sync storage is off, nothing is uploaded; the other computer reads the saved chat straight from this one by blind pass-through while both are running codeaf. See *Blind pass-through*. +While hosted relay storage is off, nothing is uploaded; the other computer reads the saved chat straight from this one by blind pass-through while both are running codeaf. See *Blind pass-through*. A saved chat reaches your other computers only after its encrypted objects have been uploaded and its new saved head has been accepted. If an upload fails, the @@ -616,7 +622,7 @@ No. The worker saves its claim and an execution intent before invoking tools. A ## Why can an older computer list chats but not continue a chat that is still running? -Older builds can still list, save, publish and release chats through a compatible service. A service using quorum-backed coordination refuses an older request that tries to take a live chat without naming its observed holder and ownership number. It uses the existing refusal, `another device continued this chat first`; an old build does not necessarily show an extra update hint. Quit on the computer holding the chat before continuing it elsewhere, or update codeaf on the computer trying to continue. A released or expired chat can still be taken. A conditional choice never silently changes to a newer holder. An older codeaf also cannot take a chat that only lives on a computer (blind pass-through, see *Blind pass-through*): it ends `continue here` with its usual could-not-continue line instead of waiting. Update codeaf on the computer trying to continue. +Older builds can still list, save, publish and release chats through a compatible service. A service using quorum-backed coordination refuses an older request that tries to take a live chat without naming its observed holder and ownership number. It uses the existing refusal, `another device moved this chat first`; an old build does not necessarily show an extra update hint. Quit on the computer holding the chat before continuing it elsewhere, or update codeaf on the computer trying to continue. A released or expired chat can still be taken. A conditional choice never silently changes to a newer holder. An older codeaf also cannot take a chat that only lives on a computer (blind pass-through, see *Blind pass-through*): it ends `move here` with its usual could-not-continue line instead of waiting. Update codeaf on the computer trying to continue. ## Can an older build save a chat with large encrypted metadata? @@ -626,26 +632,26 @@ Yes. Directory requests from older builds keep the existing 1 MiB request limit, ## Opening a free chat from Home after restarting -By default (**Settings → General → idle handoff** is off), selecting a released remote chat on Home asks **Continue here** and local chats open locally. Turn on **idle handoff** in `/settings` (or set `CODEAF_IDLE_HANDOFF=1`) on paired computers so selecting a released chat on Home brings its latest saved history here with a new hold, without **Continue here**. This also works on the first open of this computer's local copy after a restart. +By default (**Settings → General → idle handoff** is off), selecting a released remote chat on Home asks **Move here** and local chats open locally. Turn on **idle handoff** in `/settings` (or set `CODEAF_IDLE_HANDOFF=1`) on paired computers so selecting a released chat on Home brings its latest saved history here with a new hold, without **Move here**. This also works on the first open of this computer's local copy after a restart. -With `idle handoff` on, Home uses its shared listing when it already answers. If this window has no open copy and the listing is missing the chat or still shows this computer's old live hold, Home checks its current hold for up to two seconds. If that check fails or times out, the locally saved chat opens as usual, without a connection refusal. A chat already open in this window needs no extra check. A listed free chat still refreshes an older viewer with its latest history. A live hold or a lapsed hold elsewhere keeps the existing **Continue here** card, including when its holder was working. Only explicitly released holds open directly on another computer when `idle handoff` is on. Unpaired, sync-off, single-device and default (`idle handoff` off) homes keep their local opening behavior. +With `idle handoff` on, Home uses its shared listing when it already answers. If this window has no open copy and the listing is missing the chat or still shows this computer's old live hold, Home checks its current hold for up to two seconds. If that check fails or times out, the locally saved chat opens as usual, without a connection refusal. A chat already open in this window needs no extra check. A listed free chat still refreshes an older viewer with its latest history. A live hold or a lapsed hold elsewhere keeps the existing **Move here** card, including when its holder was working. Only explicitly released holds open directly on another computer when `idle handoff` is on. Unpaired, sync-off, single-device and default (`idle handoff` off) homes keep their local opening behavior. -If the sync service is unreachable, Enter on a chat saved on this computer opens its local copy, including a listed free chat last held here. With `idle handoff` on, a free open's initial ownership read also waits at most two seconds: an unreachable service opens the local copy if one exists, or explains that the sync service is not answering for a remote-only chat. Successful transfers keep their normal move budget. Opening locally keeps the chat's usual offline send restrictions. +If the relay is unreachable, Enter on a chat saved on this computer opens its local copy, including a listed free chat last held here. With `idle handoff` on, a free open's initial ownership read also waits at most two seconds: an unreachable service opens the local copy if one exists, or explains that the relay is not answering for a remote-only chat. Successful transfers keep their normal move budget. Opening locally keeps the chat's usual offline send restrictions. -## Why did Enter show Continue here instead of sending my message +## Why did Enter show Move here instead of sending my message -Before sending, codeaf checks that this window still holds the chat. If another computer holds it, its latest saved turn is newer, or this window's earlier move failed, Enter opens **Continue this chat here?** or leaves the window showing the chat only. The words stay in the box. Open it from Home to bring the saved chat here, then press Enter to send (choose **continue here** by default; with `idle handoff` on, a released paired chat opens directly while a live hold or a lapsed hold on another computer still asks for **continue here**). +Before sending, codeaf checks that this window still holds the chat. If another computer holds it, its latest saved turn is newer, or this window's earlier move failed, Enter opens **Move this chat here?** or leaves the window showing the chat only. The words stay in the box. Open it from Home to bring the saved chat here, then press Enter to send (choose **move here** by default; with `idle handoff` on, a released paired chat opens directly while a live hold or a lapsed hold on another computer still asks for **move here**). Once this window says another computer continued the chat, its first Enter raises that question without running a turn or making a branch. A saved hold from an earlier process cannot bypass the question. A window whose writer still holds the chat sends with one Enter without asking the service first. -A new chat can send its first message normally. A hold that merely lapsed (not released by its window) is reopened conditionally on the next Enter when no other computer holds the chat, or continued with Continue here; a window that released its own idle hold (when `idle handoff` is on) takes it back in place on new work when the saved head is unchanged. Reopening the chat acquires a new ownership fence. While storage is off and blind pass-through is not carrying the chat, a free chat last held here resumes quietly without reopening if its local history contains every shared turn, even with newer turns saved only here. If the ownership check cannot reach your other computers, a chat this window already holds keeps working and its turns wait to be shared; any other message stays unsent. +A new chat can send its first message normally. A hold that merely lapsed (not released by its window) is reopened conditionally on the next Enter when no other computer holds the chat, or continued with Move here; a window that released its own idle hold (when `idle handoff` is on) takes it back in place on new work when the saved head is unchanged. Reopening the chat acquires a new ownership fence. While storage is off and blind pass-through is not carrying the chat, a free chat last held here resumes quietly without reopening if its local history contains every shared turn, even with newer turns saved only here. If the ownership check cannot reach your other computers, a chat this window already holds keeps working and its turns wait to be shared; any other message stays unsent. ## A move that failed partway — are my typed words safe, can the old copy still send -If something changes the chat's files while a move is putting them in place, codeaf stops the move and lets go of the chat. It says the move could not finish and that your words are still in the box. The window keeps showing the chat or returns to Home, and it cannot send on the old copy. Try **continue here** again. +If something changes the chat's files while a move is putting them in place, codeaf stops the move and lets go of the chat. It says the move could not finish and that your words are still in the box. The window keeps showing the chat or returns to Home, and it cannot send on the old copy. Try **move here** again. Every failed move keeps the captured draft, including its whitespace, caret, pasted text and attachments, even if the old session closed during the move. Losing a race, a connection failure or a refused move does the same. A failed move never sends those words by itself. @@ -668,14 +674,14 @@ Run `codeaf doctor --fix` to repair what is safe. It prints one line per repair: `codeaf doctor --fix` never touches another computer's live hold, never disturbs a live store writer (quit the program `busy` names, or wait for it, and continue again), and never removes a branch copy or `.taking` scratch folder that holds a turn not already in the main chat. -## The chat banner says the sync service is not answering — what is offline +## The chat banner says the relay is not answering — what is offline The chat banner names the selected host, for example: -`the sync service at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back`. +`the relay at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back`. When its address is unavailable, it says -`the sync service is not answering; this chat keeps working here and catches up when it is back`. +`the relay is not answering; this chat keeps working here and catches up when it is back`. Startup and renewal notices share one notice per outage. -The sync service may be unreachable while your other computers are still +The relay may be unreachable while your other computers are still working. The chat stays usable on this computer and catches up when the service answers. Home’s presence strip disappears when the service cannot provide fresh presence; it does not guess which computers are online. @@ -684,11 +690,11 @@ presence; it does not guess which computers are online. A current window understands the earlier outage and removed-computer notices too. It uses one outage line while local work continues, and points to `/pair` for recovery in a chat. A current engine keeps the earlier notice spelling for an older window, so that window's existing outage and removal handling still works. -## Why can't I continue new turns from my offline computer — sync storage is off, and blind pass-through needs both computers on +## Why can't I continue new turns from my offline computer — relay storage is off, and blind pass-through needs both computers on -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats do not wait: with blind pass-through a chat and its files move between your paired computers while both are running codeaf, so a chat on a computer that is off cannot be taken until codeaf runs there again (*Continue here says the computer that has this chat is not on*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. Existing saved content remains readable; turning storage off deletes nothing. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats do not wait: with blind pass-through a chat and its files move between your paired computers while both are running codeaf, so a chat on a computer that is off cannot be taken until codeaf runs there again (*Move here says the computer that has this chat is not on*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. Existing saved content remains readable; turning storage off deletes nothing. -While blind pass-through carries your chats, the notice about closed storage says `chats move between your computers by blind pass-through while both run codeaf; keys, memories, teams and preferences wait for sync storage (request access in Settings under Devices)`. When blind pass-through is off or unavailable (`CODEAF_PASSTHROUGH=off`, or no other paired computer), chats stay on their computer and the refusal is `sync storage is off for this account, so chats stay on this computer; request access in Settings under Devices`. Once approval is read in the background, waiting chats start within a minute without restarting. +While blind pass-through carries your chats, the notice about closed storage says `chats move between your computers by blind pass-through while both run codeaf; keys, memories, teams and preferences wait for relay storage (request access in Settings under Devices)`. When blind pass-through is off or unavailable (`CODEAF_PASSTHROUGH=off`, or no other paired computer), chats stay on their computer and the refusal is `relay storage is off for this account, so chats stay on this computer; request access in Settings under Devices`. Once approval is read in the background, waiting chats start within a minute without restarting. ## Changing thinking or model settings after idle release @@ -706,18 +712,18 @@ When `idle handoff` (`CODEAF_IDLE_HANDOFF=1`, off by default) is on, idle releas ## Opening a saved chat offline, asking again, and keeping unsent words -Opening a chat with no stopped reply to resume does not say `the reply stopped when this conversation moved — asking again` or refuse work through the resume door. This includes opening your released chat's local copy while the sync service is unreachable. +Opening a chat with no stopped reply to resume does not say `the reply stopped when this conversation moved — asking again` or refuse work through the resume door. This includes opening your released chat's local copy while the relay is unreachable. If an unanswered reply was stopped by moving the chat, it asks again once when this window can work. If ownership refuses that resume, the refusal appears once without the asking-again line, and the unanswered question is kept for a later resume. -A new send in the window that released its chat (when `idle handoff` is on) needs to take the hold back. If the ownership check cannot reach sync, it says `the sync service is not answering, so this chat cannot be taken back yet; your words are still in the box`. The draft stays in the box; the send records nothing and calls no model. When the service returns, press Enter again to send those words after taking a new hold. An uncertain take-back write keeps its separate retry sentence below. +A new send in the window that released its chat (when `idle handoff` is on) needs to take the hold back. If the ownership check cannot reach sync, it says `the relay is not answering, so this chat cannot be taken back yet; your words are still in the box`. The draft stays in the box; the send records nothing and calls no model. When the service returns, press Enter again to send those words after taking a new hold. An uncertain take-back write keeps its separate retry sentence below. Enter checks again even when Home previously read another computer's chats or still shows an outage. If this window's hold merely lapsed, Enter reopens the chat at a new fence and sends the kept draft without a card. The box stays intact until the send succeeds. Another holder still requires your continuation choice. A failed move from Home to a different chat also leaves this chat able to check again and conditionally reopen its unchanged own fence on the next Enter. -## Take-back timeout: retry a released chat when the sync service is slow +## Take-back timeout: retry a released chat when the relay is slow When `idle handoff` (`CODEAF_IDLE_HANDOFF=1`, off by default) is on, taking back your released chat is a bounded ownership write, with up to 15 seconds to finish. The terminal can show `waiting for ; still checking` while it waits. An already-held chat keeps its ordinary short ownership check and offline behavior. -If the answer is lost, codeaf says `couldn't confirm taking this chat back from the sync service; try again`. Your words stay unsent. Press Enter again to retry in the same window. The chat may be briefly unavailable: another hold on this computer does not prove which window acquired it. codeaf does not offer its own uncertain hold through “Continue this chat here?”. +If the answer is lost, codeaf says `couldn't confirm taking this chat back from the relay; try again`. Your words stay unsent. Press Enter again to retry in the same window. The chat may be briefly unavailable: another hold on this computer does not prove which window acquired it. codeaf does not offer its own uncertain hold through “Move this chat here?”. If no window adopted that uncertain hold, nobody renews it. It lapses within the ordinary 90-second hold, and a retry then takes a new hold before sending your words. A live hold belonging to another window or computer never grants this window permission to write. diff --git a/internal/manual/chat/conversations-and-teams.md b/internal/manual/chat/conversations-and-teams.md index 5ccf528e10..9765d4850d 100644 --- a/internal/manual/chat/conversations-and-teams.md +++ b/internal/manual/chat/conversations-and-teams.md @@ -455,7 +455,7 @@ profile or changes the requesting chat's model. ## Do my teams show on my other computer? -Team sharing is on by default for paired computers and needs sync storage approval on the hosted service (Settings → Devices → sync storage). Use +Team sharing is on by default for paired computers and needs relay storage approval on the hosted service (Settings → Devices → relay storage). Use **Settings → General → share teams**. Sharing includes teams, members, handles, the manager and team settings, plus recent Traffic as read-only history. Team changes show within a few seconds, even with no chat open. The Teams dropdown, Teams page @@ -467,11 +467,11 @@ stops sending and receiving teams and Traffic. What was already exchanged stays, including teams and encrypted copies in the vault. Unpaired computers are unaffected. The desktop shows another computer's crew grouped and read-only in its chats. -Opening a remote member from terminal Teams raises `Continue this chat here?` -on Home (`continue here` moves and opens it; `leave it there` changes nothing). -By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), selecting a released chat on Home also asks **Continue here**. With `idle handoff` on, selecting a released chat on terminal Home (`enter`), or opening a +Opening a remote member from terminal Teams raises `Move this chat here?` +on Home (`move here` moves and opens it; `leave it there` changes nothing). +By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), selecting a released chat on Home also asks **Move here**. With `idle handoff` on, selecting a released chat on terminal Home (`enter`), or opening a `can_open` row via `agents.open` in the app, opens it directly with no -Continue-here step; a live hold or a lapsed hold still asks, including when its holder +Move-here step; a live hold or a lapsed hold still asks, including when its holder was working. Unshared chats, or members under `--host` / `--at`, name the other computer (`the other computer` until known): open them there. Local members open like Home without an extra ownership lookup. @@ -479,12 +479,12 @@ open them there. Local members open like Home without an extra ownership lookup. A send to one member or manager known to be on another computer is refused until you bring that chat here. A room post or multi-member send reaches local members and names anyone skipped (`Not reached: @web (on desktop).`); if all are -elsewhere, nothing is written. Local messages still work when the sync service +elsewhere, nothing is written. Local messages still work when the relay is down, and may wait briefly while an earlier change finishes uploading. ## Will deleting a team on my laptop delete it on my desktop? -Team sharing is on by default for paired computers and needs sync storage approval on the hosted service (Settings → Devices → sync storage). With **Settings → General → +Team sharing is on by default for paired computers and needs relay storage approval on the hosted service (Settings → Devices → relay storage). With **Settings → General → share teams** enabled on both computers, a deleted team stays deleted. A desktop that was offline catches up when it reconnects. Renaming its old copy while offline does not bring the team back. Deleting a team does not delete its conversations. @@ -498,7 +498,7 @@ consistently, and a removed member cannot remain the manager. ## Does Traffic sync between computers? -On the hosted sync service this needs sync storage approval (Settings → Devices → sync storage). +On the hosted relay this needs relay storage approval (Settings → Devices → relay storage). Traffic sharing is on by default for paired computers through **Settings → General → share teams**. Turning it off on either computer stops sharing between them. @@ -515,8 +515,8 @@ its ordinary log rotation. A send only to chats known to be elsewhere is refused. A send with local recipients is written once and names those not reached. Bring a remote chat -here first (choose **continue here** by default, or with `idle handoff` on a released chat opens directly on Home or through -`agents.open` while a live hold or a lapsed hold asks for **continue here**, including when +here first (choose **move here** by default, or with `idle handoff` on a released chat opens directly on Home or through +`agents.open` while a live hold or a lapsed hold asks for **move here**, including when its holder was working) before sending to it. Under `--host` or `--at`, open it on its computer. Decision details, spending records and working copies do not travel with Traffic. A decision or escalation whose recipient is @@ -526,7 +526,7 @@ on the other computer's history. ## How do I turn on team sharing? -Team sharing waits for hosted sync storage approval (Settings → Devices → sync storage); pairing alone does not enable it. A self-hosted sync service with `--store` needs no request. +Team sharing waits for hosted relay storage approval (Settings → Devices → relay storage); pairing alone does not enable it. A self-hosted relay with `--store` needs no request. Team sharing is on by default for paired computers. If it was turned off, open **Settings → General → share teams** on that computer and choose **on** to resume. @@ -541,7 +541,7 @@ Turn **share teams** to **off** to stop all team sharing immediately. Teams alre ## Stop sharing teams with my other computer -Team sharing is on by default for paired computers and needs sync storage approval on the hosted service (Settings → Devices → sync storage). Open **Settings → General → +Team sharing is on by default for paired computers and needs relay storage approval on the hosted service (Settings → Devices → relay storage). Open **Settings → General → share teams** on either computer and choose **off**. Turning it off on either computer stops sharing teams, members, manager choices and settings, and recent Traffic between them immediately. That computer stops sending and receiving teams and Traffic. Teams already received @@ -556,7 +556,7 @@ arrive within a few seconds; recent Traffic can take about 2 minutes. ## First team sharing: backup, duplicate names and global managers -On the hosted sync service this needs sync storage approval (Settings → Devices → sync storage). +On the hosted relay this needs relay storage approval (Settings → Devices → relay storage). Paired computers exchange teams automatically while **Settings → General → share teams** is on, its default. An unpaired computer is unaffected. Before the @@ -578,7 +578,7 @@ the original teams. Review manager choices in Teams. ## Does a shared team's spending cap cover both computers? -On the hosted sync service this needs sync storage approval (Settings → Devices → sync storage). +On the hosted relay this needs relay storage approval (Settings → Devices → relay storage). A team's spending cap counts spending on each computer separately. Sharing the team and its cap does not combine the usage meters. A member continued on the diff --git a/internal/manual/chat/coordination-and-workers.md b/internal/manual/chat/coordination-and-workers.md index b31324c903..e68dd16bb8 100644 --- a/internal/manual/chat/coordination-and-workers.md +++ b/internal/manual/chat/coordination-and-workers.md @@ -11,19 +11,19 @@ There is no codeaf phone app yet, so a phone cannot lead yet. A phone browser's A phone would need a supported client, persistent storage, enrollment and a live connection before it could take this role. Those requirements are not a working phone capability today. Leadership coordinates metadata; it does not move a chat or run its tools. -## Cluster status did not answer in time — slow storage or sync service +## Cluster status did not answer in time — slow storage or relay `codeaf cluster status` has a five-second command ceiling, including local storage work. A computer already joined is read from the service without reopening its local member store. A deadline says -`the sync service at
did not answer in time — try again`. +`the relay at
did not answer in time — try again`. The address is the service used for this command, including the service saved during pairing or selected by `CODEAF_SYNC_URL`. Slow local storage can also use up that allowance; this sentence does not establish a network failure. A refused connection, missing route or failed name lookup instead says -`nothing is answering at http://127.0.0.1:8901 — if that is your own sync service, start it there with codeaf relay` for your own service, or `cannot reach codeaf.agentfield.ai — check this computer's internet connection` for the hosted service. +`nothing is answering at http://127.0.0.1:8901 — if that is your own relay, start it there with codeaf relay` for your own service, or `cannot reach codeaf.agentfield.ai — check this computer's internet connection` for the hosted service. ## Joined computers, learner capacity and an outdated build @@ -44,7 +44,7 @@ No: in this release, the coordinating computer cannot be chosen by hand. `codeaf ## Cluster status — coordinating, deciding and keeping copies -`codeaf cluster status` on the hosted relay, or a self-hosted `codeaf relay` with storage, reports the committed voters and current leader after a fresh majority read. A paired computer joins with persistent storage as a learner before status shows its node. Readiness requires its own durable application through the advertised join position. Status uses device names under `coordinating`, `deciding` and `keeping copies`. When the sync service supplies member labels and a member’s device is absent from your current devices, that member reads `a computer no longer in your devices`. An older sync service that supplies no labels instead shows `another computer`, or a group such as `2 other computers`; missing labels do not mean a device was removed. `--verbose` shows the numeric details for debugging. +`codeaf cluster status` on the hosted relay, or a self-hosted `codeaf relay` with storage, reports the committed voters and current leader after a fresh majority read. A paired computer joins with persistent storage as a learner before status shows its node. Readiness requires its own durable application through the advertised join position. Status uses device names under `coordinating`, `deciding` and `keeping copies`. When the relay supplies member labels and a member’s device is absent from your current devices, that member reads `a computer no longer in your devices`. An older relay that supplies no labels instead shows `another computer`, or a group such as `2 other computers`; missing labels do not mean a device was removed. `--verbose` shows the numeric details for debugging. With `--verbose`, Status names `coordinator`, `voting computers`, `this computer`, `learning computers`, `ready computers` and `finishing the change from`. These are debugging details; ordinary status uses device names. @@ -52,7 +52,7 @@ With `--verbose`, Status names `coordinator`, `voting computers`, `this computer In this release, the coordinating computer cannot be chosen by hand. There is no leadership success receipt or retry command to use. `codeaf cluster status` shows which computer coordinates. Tracked in issue #2559. Pairing does not transfer coordination or chat ownership; continue chats through the ordinary continue door. -Three voters tolerate one unavailable member. Losing a majority pauses coordination; saved chats remain. The terminal says `the sync service at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute`. The coordination API’s refusal is `this cluster cannot coordinate right now; reconnect enough of its voting computers and try again; your saved chats are still here`. +Three voters tolerate one unavailable member. Losing a majority pauses coordination; saved chats remain. The terminal says `the relay at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute`. The coordination API’s refusal is `this cluster cannot coordinate right now; reconnect enough of its voting computers and try again; your saved chats are still here`. ## Hosted relay while this computer leads @@ -72,11 +72,11 @@ This release does not offer a command to submit or retry a leadership request, i ## Clean quit on the leader — quitting the coordinating laptop, do the anchors take over at once -On the hosted relay and a self-hosted relay with storage, a clean terminal quit finishes releasing its idle chats, then hands coordination to an anchor before stopping. Another paired computer can continue those chats immediately (or, when **Settings → General → idle handoff** / `CODEAF_IDLE_HANDOFF=1` is turned on — off by default — open those released chats directly with no Continue-here step), without waiting for an election or a lease to expire. Work that is still running keeps going and releases its chat when it finishes. Returning coordination adds at most 5 seconds to quit; a computer that is not coordinating adds no requests or wait. If the anchors cannot take over within that bound, ordinary fallback applies. +On the hosted relay and a self-hosted relay with storage, a clean terminal quit finishes releasing its idle chats, then hands coordination to an anchor before stopping. Another paired computer can continue those chats immediately (or, when **Settings → General → idle handoff** / `CODEAF_IDLE_HANDOFF=1` is turned on — off by default — open those released chats directly with no Move-here step), without waiting for an election or a lease to expire. Work that is still running keeps going and releases its chat when it finishes. Returning coordination adds at most 5 seconds to quit; a computer that is not coordinating adds no requests or wait. If the anchors cannot take over within that bound, ordinary fallback applies. ## What happens if my leader goes away — my leading laptop went to sleep or the leader computer was turned off -When a personal coordinator sleeps, crashes, loses its connection or turns sync off, the two remaining anchor voters can elect a coordinator and restore the third anchor after it catches up. The missing computer need not approve its removal. A returning computer catches up as a learner and does not automatically regain leadership, including after a clean quit. In this release, the coordinating computer cannot be chosen by hand. Losing a majority pauses coordination and keeps saved chats. The terminal says `the sync service at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute`. The coordination API’s refusal is `this cluster cannot coordinate right now; reconnect enough of its voting computers and try again; your saved chats are still here`. +When a personal coordinator sleeps, crashes, loses its connection or turns sync off, the two remaining anchor voters can elect a coordinator and restore the third anchor after it catches up. The missing computer need not approve its removal. A returning computer catches up as a learner and does not automatically regain leadership, including after a clean quit. In this release, the coordinating computer cannot be chosen by hand. Losing a majority pauses coordination and keeps saved chats. The terminal says `the relay at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute`. The coordination API’s refusal is `this cluster cannot coordinate right now; reconnect enough of its voting computers and try again; your saved chats are still here`. Coordination ticks every 5 seconds. The provisioned anchors’ ranked election windows are 6–7 ticks (30–35 seconds), 8–9 ticks (40–45 seconds) and 10–11 ticks (50–55 seconds); other computers use 12–13 ticks (60–65 seconds). Healthy fallback targets about 65 seconds. Scheduling delays or a partition can take longer. Fully idle groups stop periodic ticks only after every voter has applied the same idle barrier; a new operation or a leading computer’s disconnection wakes coordination and needs a fresh majority response. @@ -84,7 +84,7 @@ If a majority cannot answer, the coordination API says `this cluster cannot coor ## Coordinator and anchor both unavailable, lost majority -While a personal computer leads, the voters are that computer and two anchors. Losing that computer and either voting anchor leaves no majority, even though the third anchor retains its learning copy. The response is `the sync service at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute`. codeaf preserves the existing cluster and saved work; it cannot make a writable minority or remove voters to manufacture a majority. +While a personal computer leads, the voters are that computer and two anchors. Losing that computer and either voting anchor leaves no majority, even though the third anchor retains its learning copy. The response is `the relay at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute`. codeaf preserves the existing cluster and saved work; it cannot make a writable minority or remove voters to manufacture a majority. ## Does an open connection keep my chat running on this computer? @@ -93,11 +93,11 @@ The sync connection carries presence hints and committed lease acknowledgments. ## Does syncing keep sending requests when nothing is happening? -A home that has never paired sends no sync traffic. `CODEAF_SYNC_URL=off` also blocks new sync requests from clients that were opened before the setting changed. Presence pings on an open view are hints; they do not write chat ownership. On the hosted relay and the native relay, an open idle home uses its learner’s applied vault pointer to notice shared memory and preference changes. Local edits are detected locally and pushed on the next state round when sync storage is on. A relay that reports storage off gets one stats request at startup and every ten minutes; unknown hosted addresses use that same closed default. An unanswered custom address gets one startup request. An answer without storage keeps storage on and stops probing; known storage on makes no permission requests. On a relay with a learner door, over ten idle minutes, caught-up open homes with storage on make zero HTTP requests, zero peer or forwarding frames and zero client attempts, including while one home leads and after it sleeps and the anchors resume. A caught-up idle home sends no recurring state polls or peer keepalives. +A home that has never paired sends no sync traffic. `CODEAF_SYNC_URL=off` also blocks new sync requests from clients that were opened before the setting changed. Presence pings on an open view are hints; they do not write chat ownership. On the hosted relay and the native relay, an open idle home uses its learner’s applied vault pointer to notice shared memory and preference changes. Local edits are detected locally and pushed on the next state round when relay storage is on. A relay that reports storage off gets one stats request at startup and every ten minutes; unknown hosted addresses use that same closed default. An unanswered custom address gets one startup request. An answer without storage keeps storage on and stops probing; known storage on makes no permission requests. On a relay with a learner door, over ten idle minutes, caught-up open homes with storage on make zero HTTP requests, zero peer or forwarding frames and zero client attempts, including while one home leads and after it sleeps and the anchors resume. A caught-up idle home sends no recurring state polls or peer keepalives. ## How does an idle home notice offline computers and wake coordination? -Home reads its roster and backstop from the local applied directory. Its separate relay watch supplies advisory online presence, pinging every 10 seconds. A computer whose last socket closes is marked offline after a 15-second reconnect grace period; a silent connection is marked offline within 30 seconds. Home can then offer its recent chat before the 90-second lease expires. Continuing a chat and all ownership decisions still use fresh majority reads. A committed change wakes peer delivery and the next state round pulls the changed vault. If an older hosted relay has no learner door, the home keeps its existing five-second state polling. On the consensus directory, a group with no work or held chats can stop its periodic coordination timer after an idle barrier has reached every voter. The first operation wakes coordination and must obtain a fresh majority response. A saved leader address cannot answer that operation by itself. Losing the majority leaves syncing unavailable and keeps local work intact. +Home reads its roster and backstop from the local applied directory. Its separate presence watch on the relay supplies advisory online presence, pinging every 10 seconds. A computer whose last socket closes is marked offline after a 15-second reconnect grace period; a silent connection is marked offline within 30 seconds. Home can then offer its recent chat before the 90-second lease expires. Continuing a chat and all ownership decisions still use fresh majority reads. A committed change wakes peer delivery and the next state round pulls the changed vault. If an older hosted relay has no learner door, the home keeps its existing five-second state polling. On the consensus directory, a group with no work or held chats can stop its periodic coordination timer after an idle barrier has reached every voter. The first operation wakes coordination and must obtain a fresh majority response. A saved leader address cannot answer that operation by itself. Losing the majority leaves syncing unavailable and keeps local work intact. ## Hosted idle presence sweeps and sleeping connections @@ -153,7 +153,7 @@ Reassignment changes the run revision and requires a new conditional claim. The ## Why can an older computer list chats but not continue a chat that is still running? -Older builds can still list, save, publish and release chats through a compatible relay. A relay using quorum-backed coordination refuses an older request that tries to take a live chat without naming its observed holder and ownership number. It uses the existing refusal, `another device continued this chat first`; an old build does not necessarily show an extra update hint. Quit on the computer holding the chat before continuing it elsewhere, or update codeaf on the computer trying to continue. A released or expired chat can still be taken. A conditional choice never silently changes to a newer holder. +Older builds can still list, save, publish and release chats through a compatible relay. A relay using quorum-backed coordination refuses an older request that tries to take a live chat without naming its observed holder and ownership number. It uses the existing refusal, `another device moved this chat first`; an old build does not necessarily show an extra update hint. Quit on the computer holding the chat before continuing it elsewhere, or update codeaf on the computer trying to continue. A released or expired chat can still be taken. A conditional choice never silently changes to a newer holder. ## Hosting a relay with persistent storage @@ -205,7 +205,7 @@ Initialization and bounded retry records have separate room, so reaching the content limit still permits reads, releases and unchanged-size updates and returns the existing capacity refusal for growth. Older clients keep pairing, listing, publishing, releasing and continuing a chat they observed. A very old -client that blindly forces a live chat receives `another device continued this chat first`. +client that blindly forces a live chat receives `another device moved this chat first`. Quit on the holder first, or update that client before continuing a live chat. Watch sockets show presence; older clients still send their normal heartbeats. @@ -220,6 +220,6 @@ Native and hosted watch connections carry committed receipts to clients that ask On a removed computer, `codeaf cluster status` fails with the same removal and pairing guidance as `codeaf devices`. This applies to the default relay and to your own relay. Pair that computer again with `codeaf pair` to restore access. A removed device is different from a cluster temporarily unable to coordinate. `codeaf cluster lead` is an unknown command in this release, even after pairing again. -## Why shared state waits for sync storage — approval and serving computers +## Why shared state waits for relay storage — approval and serving computers -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. Eligible serving homes start approval discovery after their first state round; quiet or removed homes do not start it. A stats refusal for a revoked or removed device stops polling. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. Eligible serving homes start approval discovery after their first state round; quiet or removed homes do not start it. A stats refusal for a revoked or removed device stops polling. diff --git a/internal/manual/chat/desktop-sync.md b/internal/manual/chat/desktop-sync.md index 0c905d0ce2..b45c763633 100644 --- a/internal/manual/chat/desktop-sync.md +++ b/internal/manual/chat/desktop-sync.md @@ -3,25 +3,31 @@ ## Why did this desktop chat stop taking messages after another computer continued it When another computer continues a chat, the desktop shows the engine's sentence: -` continued this chat. This copy is read-only and may be behind`. This computer stops +` moved this chat. This copy is read-only and may be behind`. This computer stops accepting new messages, corrections, queued messages and retries for that chat. Task and program starts, quick-task promotion, moving a reply to a task, task directions and asking for a new crew proposal also refuse the move. The same check protects remote submissions and queued follow-ups; a follow-up accepted before the move is refused before its turn can start. Existing action receipts remain readable and replaying one does not start its work again. +With remote control on and the other computer online, the desktop does not leave +you on that read-only copy: the same chat opens as a live view of the computer +that continued it, where you can read the running reply and type. The read-only +copy is what remains when remote control is off or that computer is off. Your unsent draft and staged attachments stay yours. Messages already queued stay in the queue; editing, reordering or removing them does not start a turn. The app pins `Continued on ` above the transcript with `This copy is read-only and may be behind.` Its tab, sidebar and header use a -computer indicator. Continue here replaces an inert composer; a composer that +computer indicator. Move here replaces an inert composer; a composer that can send to the other computer names that destination. Hidden drafts stay kept. With a compatible engine, the open view follows newly saved messages through -sync storage or live transfer, without moving the chat or restoring remote files. +hosted storage or live transfer, without moving the chat or restoring remote files. If the latest history is unavailable, you can still read the local copy. Remote history and previews read saved transcripts up to 24 MiB. For a larger transcript, -use Continue here to move the chat and read its full history. Unsealed -words and in-progress tokens are not streamed between computers. +use Move here to move the chat and read its full history. Unsealed +words and in-progress tokens are not streamed between computers, except in a +live view (*Open a chat running on another computer live in the desktop*), +which shows the reply as the other computer writes it. The desktop can still send that computer a message for the chat while it is open or working there; it waits in the chat's queue on that computer. See "Send a message to a chat working on another computer". @@ -64,7 +70,7 @@ continues to count it when it says it. ## Which desktop provider keys sync between paired computers -With sync storage enabled, saved keys for supported model providers can sync +With relay storage enabled, saved keys for supported model providers can sync through the encrypted vault. Connections that can point to different servers on different computers, such as custom endpoints and Ollama, keep their keys on the computer where you entered them. This includes an OpenRouter connection @@ -125,7 +131,7 @@ not say they are paired: it says `Pairing was not confirmed by . Check that computer to see whether it joined.` For chats of its own (not for a computer paired elsewhere), `codeaf pair --replace` in a terminal joins the other set instead: local chats stay here but stop syncing, shared memories -and settings clear, and local provider keys stay here. Use Continue here to move a shared chat (or, when **Settings → General → idle handoff** / `CODEAF_IDLE_HANDOFF=1` is turned on — off by default — a shared chat no computer holds advertises `can_open` and opens directly through `agents.open` with no Continue-here step; use **Move here** or **Continue here** when another computer still holds it). A failed +and settings clear, and local provider keys stay here. Use Move here to move a shared chat (or, when **Settings → General → idle handoff** / `CODEAF_IDLE_HANDOFF=1` is turned on — off by default — a shared chat no computer holds advertises `can_open` and opens directly through `agents.open` with no Move-here step; use **Move here** when another computer still holds it). A failed upload stays saved locally and is retried while codeaf is open or on the next start. Sync status says `Sharing this computer's chats.` during the pass and `Some chats could not be shared yet. They are still saved here; codeaf will try @@ -153,29 +159,59 @@ own record is still waiting to be shared. A separate presence failure leaves online status unknown; a readable roster is still shown. Changes arrive through engine events, and unchanged lists do not repeat them. -## Chats on your other computers and Continue here in the desktop +## Chats on your other computers and Move here in the desktop Chats from other computers appear under On your other computers, with the computer's name. An online dot appears only when the engine knows its presence. Finished movable chats saved before pairing are shared after pairing and when the paired app engine starts. This does not open the chat or start a new turn. -An open, idle chat another computer still holds says `open on ` (`held on ` in the terminal); this says where it is open, not that a reply is running. By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), an open idle chat keeps its hold; with `idle handoff` on in paired builds, an idle chat lets go about 2 seconds after going idle once saved to the sync service, so rows stay `open on ` only before release, while unsaved work keeps the hold, when `idle handoff` is off, or on older builds. While a reply runs, the engine advertises `working: true` (`working on `), including right after a move, and clears it once the reply finishes and its last saved turn reaches the sync service. Closing a chat does not make its computer offline; ` offline` appears only when that computer is known to be offline, and unknown presence omits both dot and offline line. The saved time is the newest shared saved turn's time in your local time, not upload time, and is omitted when unknown. The engine's takeover sentence adds holder or pending-work facts without repeating a date or age. After the sync service starts or restarts, computers it has not heard from have unknown presence (no offline line) for up to 75 seconds; an observed connection that lapses can still be marked offline. -With `idle handoff` on, a shared chat explicitly released by its holder advertises `can_open: true` and `agents.open` pulls and opens it directly with no Continue-here step (while `idle handoff` is off, `can_open` is not advertised and released chats use Continue here). A lapsed hold never advertises `can_open`, including when its holder was working or its last working state is unknown. Select a held or lapsed chat (or use a preview-only client, or when `idle handoff` is off) to see its title, saved time and engine sentence: **Move here** or **Continue here** moves it through the engine and opens the returned local chat, using the same continuation path as the terminal. +An open, idle chat another computer still holds says `open on ` (`held on ` in the terminal); this says where it is open, not that a reply is running. By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), an open idle chat keeps its hold; with `idle handoff` on in paired builds, an idle chat lets go about 2 seconds after going idle once saved to the relay, so rows stay `open on ` only before release, while unsaved work keeps the hold, when `idle handoff` is off, or on older builds. While a reply runs, the engine advertises `working: true` (`working on `), including right after a move, and clears it once the reply finishes and its last saved turn reaches the relay. Closing a chat does not make its computer offline; ` offline` appears only when that computer is known to be offline, and unknown presence omits both dot and offline line. The saved time is the newest shared saved turn's time in your local time, not upload time, and is omitted when unknown. The engine's takeover sentence adds holder or pending-work facts without repeating a date or age. After the relay starts or restarts, computers it has not heard from have unknown presence (no offline line) for up to 75 seconds; an observed connection that lapses can still be marked offline. +With `idle handoff` on, a shared chat explicitly released by its holder advertises `can_open: true` and `agents.open` pulls and opens it directly with no Move-here step (while `idle handoff` is off, `can_open` is not advertised and released chats use Move here). A lapsed hold never advertises `can_open`, including when its holder was working or its last working state is unknown. Select a held or lapsed chat (or use a preview-only client, or when `idle handoff` is off) to see its title, saved time and engine sentence: **Move here** moves it through the engine and opens the returned local chat, using the same continuation path as the terminal. -## Continuing a desktop chat here — fences, retries and local copies +## Moving a desktop chat here — fences, retries and local copies An already local chat that moved away keeps its place and becomes read-only. -Continue here is available when the engine says it can move. Continuing here +Move here is available when the engine says it can move. Moving a chat here stops new work on the other computer. If another computer moved it after the -preview was read, the engine says `another device continued this chat first`; -refresh the row and choose again. Only a Continue here that waited for a turn retries itself. Unsent drafts +preview was read, the engine says `another device moved this chat first`; +refresh the row and choose again. Only a Move here that waited for a turn retries itself. Unsent drafts and attachments remain yours. Changes arrive as engine events without desktop polling. An older chat that works in the home folder stays on that computer. -Continue here requires the holder and ownership fence shown when you chose it. +Move here requires the holder and ownership fence shown when you chose it. A changed fence, holder or saved turn needs a fresh choice. Completed turns are shared while the chat stays open, including after a move. +## Open a chat running on another computer live in the desktop — Open on , watch it, type into it, take the keyboard + +With **Remote control** on (the **Remote control** switch in Settings → Devices, off by default; *Turn remote control on or off in the desktop app*) the desktop can open a chat another of your computers is running as a live view. A chat row that is running on a computer that is online offers `Open on `; choosing it opens the chat like any other: its history, the reply as it streams, questions waiting for you, steer, queue and stop all work, and you type in the ordinary box (`Message `). The words go straight to the running chat on that computer. Nothing is kept on the service in between, so this works with storage off, and it is not the waiting message of *Send a message to a chat working on another computer*, which is only for a computer that is off. The chat stays on that computer; `Move here` brings it here. + +The chat's strip says where it stands: `live` (with `· direct` or `· relay` after it once the road is known, as `/status` says in the terminal), `reconnecting`, `offline` with when it was last seen, `idle`, or `watching`. A view with no one typing for ten minutes disconnects itself so an idle view costs nothing; sending anything, or opening the chat again, reconnects. Watching means that computer lets this one read but not type (` lets this computer watch, not type. Change that in /devices there.`), or its daily allowance of live traffic is used up (`watch only until 00:00 UTC (daily limit)`). Only one computer types at a time: `typing from now` says who has the keyboard, and taking it is the button beside it. A computer taken off your list is told so (`this computer was removed from your devices`). + +The model, approval posture and spending limit of a live view are set on the computer running the chat, not from here, and the desktop's own tools are not given to that chat. + +What a computer lets another one do is set on that computer, in Settings → Devices → each other computer: watch its chats, and type into them. A computer paired before remote control existed can watch but not type until you allow it; one paired since can do both, and you can turn either off. Chats a terminal holds can be opened live from the desktop, and a chat this desktop is running can be opened live from your other computers (*Offer a chat running on this desktop to another computer*). + +## Turn remote control on or off in the desktop app — the Remote control switch, where it is, why it says restart + +In the desktop app, open Settings → Devices: the **Remote control** switch is at the top, above Computers. It is off until you turn it on, and it is this computer's own setting, the same one the terminal's `/settings` → `Devices` row changes. If the app was started with `CODEAF_REMOTE_CONTROL` set, the switch shows that value and cannot be changed; it says `Remote control is set by CODEAF_REMOTE_CONTROL`. A desktop app older than remote control has no such switch. + +Turning it **on** offers the chats this desktop opens from then on to your other computers. A chat that was already open is not offered until you open it again. The `Open on ` buttons and each computer's watch and type switches appear after the app's engine restarts, so the switch says `Restart to open chats on your other computers.` with a **Restart** button; if an agent is working it asks first. + +Turning it **off** takes effect at once: the desktop stops offering chats, and another computer's view of one of them ends with ` closed this chat.`. The chat here keeps running and keeps everything that was typed. The `Open on` buttons go away after a restart (`Restart to take the Open on buttons away.`). + +## Offer a chat running on this desktop to another computer — remote control, who may open it, how long, when it ends + +With **Remote control** on (the **Remote control** switch in Settings → Devices, off by default), a chat this desktop is running can be opened live from your other computers, the way the desktop opens theirs: they see the history and the reply as it streams, and write in it only if this computer lets them. That is set the same way as the other direction, in Settings → Devices → that computer: whether it may watch your chats here, and whether it may write in them (a computer paired before remote control existed starts with watching only). The desktop's own window stays in the chat the whole time and keeps the chat's words; another computer is one more window on the same conversation, not a copy. + +A chat is offered while this desktop has it open. One a window has left idle is let go after its usual idle time, **unless another computer is watching it**, which keeps it open until they leave. Closing the chat here or quitting the desktop ends their view: they see ` closed this chat.`, and the chat reads from the saved copy from then on. A chat opened while remote control was off is not offered; turn it on, and chats opened afterwards are. + +A running factory stage is not offered. With remote control off, or when the desktop cannot open the door another computer would knock on (the state folder's path is too long for a socket, or its folder is read-only), nothing here applies and the chat says where it is held, as before. + +## Who is typing in a chat this desktop is running — Typing from another computer, Type here, take the keyboard back + +With remote control on, another of your computers (or a second window on this one) can take the keyboard of a chat this desktop is running, and only one window types at a time. The desktop's own box is then read only and the chat says `Typing from now.` (`another window` when it is a second window here) with a **Type here** button that takes the keyboard back. A message sent while the keyboard is theirs is refused with the sentence that says who has it. The keyboard comes back to the desktop when they let go or leave, and the chat keeps running either way. With remote control off nobody else is in the chat, so nothing is shown and **Type here** never appears. + ## A crew made on another computer in the desktop — grouped, read-only, message its manager A crew made on another paired computer shows in the desktop as one crew: its @@ -191,7 +227,7 @@ In this version a crew on another computer is read-only here: - You can read each member's chat and send a message to the crew's manager, which is queued on that computer and runs after its turn. - The crew is not in this computer's crews list, cannot be edited, closed or - started here, and cannot be continued here as a crew. Continue here still + started here, and cannot be moved here as a crew. Move here still moves one member's chat on its own, which leaves the crew on the other computer. @@ -206,7 +242,7 @@ writes to that computer instead of being read-only. The field says says where it goes: `To · after this turn` while a turn runs there, `To ` while the chat is only held open. When `idle handoff` (`CODEAF_IDLE_HANDOFF=1`, off by default) is on and an idle chat lets go of its hold, no computer holds it: opening it via `agents.open` pulls it here directly, and sending in the window that released it takes it back in place. Rest on the chip or press it to see which computer it is (` · your Linux computer`), what happens to a -message, and `Continue here instead`. The chat does not move. The +message, and `Move here instead`. The chat does not move. The message goes into the chat's queue on that computer, so it runs when the current turn ends, or at once if nothing is running. @@ -216,20 +252,19 @@ chat comes here its transcript shows what ran, and those lines go. The chat is the address, not the computer: if the chat moves before the message is taken, whichever computer holds it then takes it, which can be this one. So -continuing a chat here runs your messages still waiting for the other computer -on this computer, right after the move; the chat says so beside every Continue -here (`Continuing here runs your 2 waiting messages on this computer.`). A -waiting message cannot be taken back. +moving a chat here runs your messages still waiting for the other computer +on this computer, right after the move; the chat says so beside every Move here, with the count of waiting messages +that will run on this computer. A waiting message cannot be taken back. -To bring the chat here instead, choose Continue here. While a turn runs there +To bring the chat here instead, choose Move here. While a turn runs there it waits (`Comes here when this turn ends.`, with Cancel), then moves, retrying once if that computer saved again first. -## Why can't I message a chat on another computer — the composer is read-only while sync storage is off +## Why can't I message a chat on another computer — the composer is read-only while relay storage is off -While the account's hosted sync storage is off, the desktop does not offer `Message ` for a chat another computer holds, and `chats.send` is not in `hello`. A waiting message is sealed text kept in this computer's record on the sync service until the holder takes it, and the service keeps nothing of the kind until storage is approved. A send that arrives anyway is refused with `Sync storage is off for this account, so a message can't wait for another computer. Bring the chat here to write to it.` and leaves nothing on the service. +While the account's hosted relay storage is off, the desktop does not offer a *waiting* `Message ` for a chat another computer holds, and `chats.send` is not in `hello`. A chat that computer is running and that you opened live is different: with remote control on and the computer online, you type into it directly and storage is not involved (*Open a chat running on another computer live*). The rest of this section is about a computer that is off, or a chat opened without remote control. A waiting message is sealed text kept in this computer's record on the service until the holder takes it, and the service keeps nothing of the kind until storage is approved. A send that arrives anyway is refused with `Relay storage is off for this account, so a message can't wait for another computer. Move the chat here to write to it.` and leaves nothing on the service. -Choose Continue here to write to the chat: blind pass-through moves it while both computers run codeaf. Approving sync storage brings the message box back on the next connection, and a self-hosted sync service always had it. Messages already waiting when storage was switched off can still be taken off the service. +Choose Move here to write to the chat: blind pass-through moves it while both computers run codeaf. Approving relay storage brings the message box back on the next connection, and a self-hosted relay always had it. Messages already waiting when storage was switched off can still be taken off the service. ## A message to another computer is not delivered, the computer is offline, or it didn't send @@ -237,7 +272,7 @@ These are messages written here to a chat that another of your computers holds. If the other computer goes offline before it takes a message, the message's line reads `Not delivered yet · is offline`, and the chat says -`Your 2 messages waiting for go when it's back online, or run here if you continue here.` +`Your 2 messages waiting for go when it's back online, or run here if you move here.` The text is sealed with your identity's key, so the relay cannot read it. Limits and refusals: @@ -245,19 +280,19 @@ Limits and refusals: - At most eight messages from this computer wait at once, counted across every chat and every other computer, not per chat: `Eight messages sent from this computer, in this chat or others, haven't been delivered yet. Send this one once some of them are.` - When this computer cannot reach your relay, nothing is sent and the words stay in the box: `This computer can't reach your relay right now, so the message didn't go. Send it again once it's back.` The box says `Can't reach your relay · messages to send once it answers` while that lasts. - A message is at most 2000 characters: `Messages to another computer are limited to 2000 characters.` -- A sync service that does not carry messages says `This sync service can't carry a message to another computer yet. Bring the chat here to write to it.` +- A relay that does not carry messages says `This relay can't carry a message to another computer yet. Move the chat here to write to it.` - Only an app engine (the desktop app, or `codeaf app`) on the holding computer takes messages. A terminal chat there does not; the message waits. -- A chat whose holding computer is offline with a live hold or a lapsed hold stays read-only until you continue it here, including when its holder was working. With `idle handoff` on (`CODEAF_IDLE_HANDOFF=1`, off by default), an explicitly released chat opens here directly through `agents.open` on `can_open` rows, and new work in the window that released its own idle hold takes it back in place (with `idle handoff` off, a handed-over chat's next message moves it here via Continue here). +- A chat whose holding computer is offline with a live hold or a lapsed hold stays read-only until you move it here, including when its holder was working. With `idle handoff` on (`CODEAF_IDLE_HANDOFF=1`, off by default), an explicitly released chat opens here directly through `agents.open` on `can_open` rows, and new work in the window that released its own idle hold takes it back in place (with `idle handoff` off, a handed-over chat's next message moves it here via Move here). -## Does an idle desktop chat keep its hold on the sync service +## Does an idle desktop chat keep its hold on the relay By default (**Settings → General → idle handoff** is off), a chat opened for viewing keeps its conversation and sync-service hold until it is explicitly closed, including while its tab is hidden; heartbeats renew the same hold without releasing it or moving its fence, and reading the chat does not cause ownership changes or repeat unchanged chat rows. -When you turn **idle handoff** on in `/settings` or with `CODEAF_IDLE_HANDOFF=1` with two or more paired computers (and sync storage on), an idle chat lets go of its hold about 2 seconds after it goes idle once its journal, working files, shared memory and settings are on the sync service, including when its tab stays open. The conversation remains open as a reader. Running turns, queued or steering work, running tasks or jobs, deferred writes and failed uploads retain the hold. Rebuildable files keep their existing transfer exclusions. +When you turn **idle handoff** on in `/settings` or with `CODEAF_IDLE_HANDOFF=1` with two or more paired computers (and relay storage on), an idle chat lets go of its hold about 2 seconds after it goes idle once its journal, working files, shared memory and settings are on the relay, including when its tab stays open. The conversation remains open as a reader. Running turns, queued or steering work, running tasks or jobs, deferred writes and failed uploads retain the hold. Rebuildable files keep their existing transfer exclusions. New work in the window that released its idle hold takes the unchanged chat back in place, with no prompt, before recording it or calling a model. If another computer took it, the existing moved notice and held-elsewhere refusal name that computer. A hold that merely lapsed (not released by its window) admits nothing until you reopen or continue it. A released window stays read-only when ownership cannot be confirmed. Unpaired, sync-off, single-device and default (`idle handoff` off) homes keep their existing hold and renewal behavior. -With `idle handoff` on, through `agents.open` and `can_open` rows, the engine opens an explicitly released shared chat on another paired computer directly with no Continue-here step. A lapsed hold keeps Continue here, including when its holder was working or its last working state is unknown. App versions that only preview shared chats (or homes with `idle handoff` off) still offer Continue here in that preview. A chat another computer still holds (`held on ` / `working on `, including idle chats when `idle handoff` is off or on older builds) continues to ask with **Move here** or **Continue here** as your choice. +With `idle handoff` on, through `agents.open` and `can_open` rows, the engine opens an explicitly released shared chat on another paired computer directly with no Move-here step. A lapsed hold keeps Move here, including when its holder was working or its last working state is unknown. App versions that only preview shared chats (or homes with `idle handoff` off) still offer Move here in that preview. A chat another computer still holds (`held on ` / `working on `, including idle chats when `idle handoff` is off or on older builds) continues to ask with **Move here** as your choice. ## Background desktop conversations release after ten idle minutes @@ -265,10 +300,10 @@ A conversation opened only for background work is let go after ten idle minutes; the sweep checks every 30 seconds. It stays released until work needs it again. Sending, queueing or retrying opens it through the normal ownership check. Sending into your own released chat opens it again when its hold is still free; -its own idle release does not require Continue here. +its own idle release does not require Move here. Steering still needs a running turn. A task or job can also open it. Running turns, unanswered questions, held crew members and kept services retain their -conversations. If another computer continues a chat, the existing Continue here +conversations. If another computer moves a chat, the existing Move here and kept-work rules still apply. Stopped processes, finished tasks and settled jobs do not reopen a background @@ -290,7 +325,7 @@ computer. Unpublished turns retry automatically with waits capped at 60 seconds, another send, quit or restart. Once an ownership check finds the hold expired, an idle window stops admitting work. In an open terminal chat, the next Enter conditionally reopens it at a new fence and sends the kept draft without a -Continue here card. A desktop can use Continue here to acquire a new hold. +Move here card. A desktop can use Move here to acquire a new hold. Reopening a chat also acquires a new ownership fence. If this computer's renewal or the relay's renewal at restart reaches the unchanged hold before an ownership check observes expiry, the open chat keeps its fence and uploads its local turns. @@ -299,9 +334,9 @@ A turn that is already running when the hold is observed to have expired attempt If another computer continued the chat meanwhile, this window becomes read-only and names that computer. Work saved here during the outage is kept through the -usual kept-work path. Use Continue here to bring the current shared chat back. +usual kept-work path. Use Move here to bring the current shared chat back. -## Continue here when this computer cannot use the chat's model +## Move here when this computer cannot use the chat's model A chat saved on another computer can name a provider that is not set up here. When it opens here, codeaf checks the same local provider readiness used for @@ -313,23 +348,23 @@ Every continuation uses the saved chat's latest main and fallback choices, including when this computer already has an older copy. A usable saved model stays selected without a change notice. An unavailable main model gets one specific explanation; a separate fallback change may have its own line. -Continue here completes even when the default is also unavailable: the chat is +Move here completes even when the default is also unavailable: the chat is here, and its row opens the returned local agent. Its first send fails locally with a setup sentence, such as `This chat used llama3.2 (Ollama), which isn't set up on this computer. Set up a model in Settings, then send again.` That reason appears once in the agent view, and no provider call is made for the turn. Set a usable default in Settings, then send again. The next send uses that default and explains the change once; taking the chat again is unnecessary. -## If Continue here fails while moving a chat +## If Move here fails while moving a chat If moving the chat fails, the app says `This chat could not be moved to this computer.` Technical causes are kept in the error details. A plain model setup reason is carried in the visible message. If installation failed after acquisition, the chat is released. -The computer without the installed chat can choose Continue here (or, with `idle handoff` on, open the now-free row directly through `agents.open` / `can_open`), and the row names the +The computer without the installed chat can choose Move here (or, with `idle handoff` on, open the now-free row directly through `agents.open` / `can_open`), and the row names the last holder without claiming it is open there. A window that was displaced by that move attempt says -`This chat is available to continue here.` Because another computer's move displaced it rather than its own idle release, it admits nothing until you reopen or continue it here. -If another computer saved newer work, reopening or Continue here restores that work. +`This chat is available to move here.` Because another computer's move displaced it rather than its own idle release, it admits nothing until you reopen or move it here. +If another computer saved newer work, reopening or Move here restores that work. ## Shared settings after pairing — model, effort and spending limits @@ -354,9 +389,9 @@ A removal check returns a local vault read error rather than stopping the background sync worker. Background sync can retry on a later round. This does not repair a damaged vault or change the saved keys shared between computers. -## Continue here while a background job runs on the other computer +## Move here while a background job runs on the other computer -Continue here waits until that computer's foreground turn, background jobs and +Move here waits until that computer's foreground turn, background jobs and resulting replies are finished and saved. The notice says `Comes here after its running work and replies are saved.` Cancel stops waiting. Job completion and its owed reply stay on the original computer until that diff --git a/internal/manual/chat/factory-agentfield.md b/internal/manual/chat/factory-agentfield.md index 86914d63cc..ac6f2cf0ae 100644 --- a/internal/manual/chat/factory-agentfield.md +++ b/internal/manual/chat/factory-agentfield.md @@ -434,7 +434,7 @@ list, over these fields. A step that ran the codeaf harness has a chat like any step this factory runs: open it from the job's rail and it shows the same entries — words, thinking, -tool cards, diffs — streamed as the node works, because the node relays the +tool cards, diffs — streamed as the node works, because the node passes on the run's own conversation record line by line and the factory keeps it as an ordinary conversation on this machine. The factory is the record: the control plane holds a line only until the factory has kept it, and a factory that was diff --git a/internal/manual/chat/factory-stage-conversations.md b/internal/manual/chat/factory-stage-conversations.md index 16b1562872..d304db3abd 100644 --- a/internal/manual/chat/factory-stage-conversations.md +++ b/internal/manual/chat/factory-stage-conversations.md @@ -836,12 +836,12 @@ Each Follow PR round posts a brief ordinary assistant message naming its observe trigger: failing CI checks, review feedback, conflicts, or the final readiness review. The worker is asked to give one or two sentences when its investigation, repair approach or verification changes, roughly once a minute during lengthy -work. Complete model messages are relayed at journal boundaries; reasoning, tool -output, abandoned streams and partial replies are not relayed. +work. Complete model messages are passed on at journal boundaries; reasoning, tool +output, abandoned streams and partial replies are not passed on. The same job conversation receives these messages below the running Follow PR frame, without another card or requiring the person to open the worker chat. -Only the first paragraph is relayed, capped at the existing 400-character stage +Only the first paragraph is passed on, capped at the existing 400-character stage summary size; the complete text remains in the worker chat. Duplicate updates are suppressed, and model updates are at least 30 seconds apart per round. This adds no periodic model calls and does not promise a timed heartbeat when a model diff --git a/internal/manual/chat/factory.md b/internal/manual/chat/factory.md index 3c6da9d8ec..aa2bdfcc83 100644 --- a/internal/manual/chat/factory.md +++ b/internal/manual/chat/factory.md @@ -105,7 +105,7 @@ Existing saved jobs keep their identity and work, without a migration. Every job from outside GitHub carries a trust, the same three a GitHub author has: `owner`, `collaborator` or `stranger`. It is set by whoever sends the work: -- `"trust"` in the desktop's `factory.intake_add`. Left out, it is `owner`, because only the person at the factory's own machine files work there. Work relaying other people's words should be sent as `collaborator` or `stranger`. +- `"trust"` in the desktop's `factory.intake_add`. Left out, it is `owner`, because only the person at the factory's own machine files work there. Work that passes on other people's words should be sent as `collaborator` or `stranger`. - AgentField work is held to the connection's trust ceiling, `collaborator` by default (see "AgentField and the factory", `factory-agentfield`). - Jira sets it itself: a reporter with a seat on the site, an automation, or a reporter this account cannot see is a `collaborator`; a service-desk customer who raised the ticket from a portal is a `stranger`. @@ -494,7 +494,7 @@ The factory checks this itself, in Manual and in Auto. A press on a turn you did ## tell a job's main agent through the Factory manager — pass my words to a job, ask the job's manager to rebase from the Factory manager -"Tell #12 to rebase on main": the Factory manager passes your words to that job's main agent (its manager), which gets one turn of its own conversation and answers, and the Factory manager relays the answer. The note the main agent reads begins "The person told the Factory manager, for you:". The turn is charged to the job's budget and is stopped after 3 minutes; what the main agent did before that stands. +"Tell #12 to rebase on main": the Factory manager passes your words to that job's main agent (its manager), which gets one turn of its own conversation and answers, and the Factory manager passes the answer on. The note the main agent reads begins "The person told the Factory manager, for you:". The turn is charged to the job's budget and is stopped after 3 minutes; what the main agent did before that stands. It is refused, and nothing is passed on, when the message was not yours, when the job has no main agent conversation yet (one is made when the job starts or when you open the job's chat), when the job is finished or you stopped it, and when its budget is spent. A main agent in the middle of a turn of its own is not interrupted: the words are not passed on, and you ask again. diff --git a/internal/manual/chat/getting-started.md b/internal/manual/chat/getting-started.md index 27300b5a0b..ea93609475 100644 --- a/internal/manual/chat/getting-started.md +++ b/internal/manual/chat/getting-started.md @@ -52,7 +52,7 @@ screen. Its heading is `Basic settings`, one line, with the keys line directly u ## I already use codeaf on a second computer — the code field on the first screen -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. @@ -65,7 +65,7 @@ have a code from another device? use your own relay: codeaf pair --via ``` -On the computer that has your chats, type `/pair` to show a code like `42-715-302`. Type that code in the field. Compare the three words on both screens. The other computer asks `y / n`. On `y`, this computer has your identity; chats copy here when sync storage is enabled, and move by blind pass-through while both computers are running codeaf when it is off. Read *Pairing your chats with a second computer* for the rest. +On the computer that has your chats, type `/pair` to show a code like `42-715-302`. Type that code in the field. Compare the three words on both screens. The other computer asks `y / n`. On `y`, this computer has your identity; chats copy here when relay storage is enabled, and move by blind pass-through while both computers are running codeaf when it is off. Read *Pairing your chats with a second computer* for the rest. ## Skipping setup and reading its header diff --git a/internal/manual/chat/home.md b/internal/manual/chat/home.md index e8245d13e2..515d6e3075 100644 --- a/internal/manual/chat/home.md +++ b/internal/manual/chat/home.md @@ -307,7 +307,7 @@ happened. The row says where the chat is only where that tells you something: ## Why a chat says held on build-box or build-box offline -For a chat on another paired computer, read the words apart: `working on build-box` says a turn is running on that computer right now, `held on build-box` says that computer still holds the chat with nothing running right now (by default while `idle handoff` is off, before idle release when `idle handoff` is on, or while an older build is idle), and `build-box offline` says that computer has not answered for 25 seconds (it is switched off, asleep, frozen or offline; the word appears within 30 seconds, and goes at once when it answers again) and has not let the chat go, so the chat's last saved turns are what you would get. The name is only the device's. A live hold on a computer that says `working on`, `held on` or `offline` still asks before **Move here** / **Continue here**; the card says how many turns may still be there. Offline alone does not make the chat free. By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), a released chat asks **Continue here**; on paired computers with `idle handoff` on, a released chat opens here directly with its latest saved copy and no Continue-here card, including when its older viewer tab is already open. A lapsed hold on another computer still asks, including when its holder was working. A count of one reads `1 turn`, never `1 turns`. The device is the name you gave that machine. A chat whose name will not open shows +For a chat on another paired computer, read the words apart: `working on build-box` says a turn is running on that computer right now, `held on build-box` says that computer still holds the chat with nothing running right now (by default while `idle handoff` is off, before idle release when `idle handoff` is on, or while an older build is idle), and `build-box offline` says that computer has not answered for 25 seconds (it is switched off, asleep, frozen or offline; the word appears within 30 seconds, and goes at once when it answers again) and has not let the chat go, so the chat's last saved turns are what you would get. The name is only the device's. A live hold on a computer that says `working on`, `held on` or `offline` still asks before **Move here**; the card says how many turns may still be there. (With remote control on, enter on a `working on` or `held on` row of an online computer opens the chat live instead, and **Move here** is `alt+m`.) Offline alone does not make the chat free. By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), a released chat asks **Move here**; on paired computers with `idle handoff` on, a released chat opens here directly with its latest saved copy and no Move-here card, including when its older viewer tab is already open. A lapsed hold on another computer still asks, including when its holder was working. A count of one reads `1 turn`, never `1 turns`. The device is the name you gave that machine. A chat whose name will not open shows `untitled`, and a machine whose name will not open shows the first eight characters of its id. On a narrow frame a branch's sentence shortens to ` turns · `, and where even that will not fit the sentence gives way whole before the chat's name is cut, so a @@ -335,44 +335,44 @@ a read still waiting at five seconds keeps the last list and says `waiting for < extra is drawn and the panel is exactly the local list. `codeaf cell list --all` prints the same rows in a terminal (see "The cell verbs" in running-from-the-terminal). -## Continue a chat here that another machine left — "tower offline", takeover, "continue here", the chat is running on another computer +## Move a chat here that another machine left — "tower offline", takeover, "move here", the chat is running on another computer -While hosted sync storage is off, a chat on a computer where codeaf is not running cannot be taken until codeaf runs there again; see *Continue here says the computer that has this chat is not on*. +While hosted relay storage is off, a chat on a computer where codeaf is not running cannot be taken until codeaf runs there again; see *Move here says the computer that has this chat is not on*. Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. Older chats move through an independent copy. Once paired, codeaf prepares chats active in the last 30 days in the background, one at a time; opening another older chat prepares its copy then. This build shows and writes to the copy. The original files stay untouched and remain usable in older codeaf builds. -By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), selecting a released remote chat asks **Continue this chat here?**, while on paired computers with `idle handoff` on a released chat opens directly with its latest saved copy. If the row has a live hold or a lapsed hold on another computer (or is released while `idle handoff` is off), whether it says `working on `, `held on ` or ` offline`, press enter and Home asks **Continue this chat here?** -with the cursor on `continue here`, because pressing enter on the row already said you want it; `esc` or `2` leaves it there. +By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), selecting a released remote chat asks **Move this chat here?**, while on paired computers with `idle handoff` on a released chat opens directly with its latest saved copy. If the row has a live hold or a lapsed hold on another computer (or is released while `idle handoff` is off), whether it says `working on `, `held on ` or ` offline`, press enter and Home asks **Move this chat here?** +with the cursor on `move here`, because pressing enter on the row already said you want it; `esc` or `2` leaves it there. With remote control on, a chat another computer is running and that computer is online opens live on enter instead (the page *Remote control*), and the card comes with `alt+m` or `alt+c`. The card says how fresh the copy is: `last saved turn ago; up to turns may still be on `. The `up to` clause is left out when nothing is waiting there. On a `held on ` row the card starts with that: `held on ; last saved turn ago`. When that device is not online, the card leaves `held on` out and says `last saved turn ago`. Press enter to continue: the chat is fetched, this machine takes it over at once and it opens. You do not wait for the other machine to go quiet: a chat that is running there stops taking new turns there the moment you take it, and its window says -` continued this chat. This copy is read-only and may be behind`. Anything it had not yet sent +` moved this chat. This copy is read-only and may be behind`. Anything it had not yet sent is kept as a branch, ` turns from : open separately / discard`; opening it continues it separately, and discard archives it. On a narrow frame the same question takes the whole screen, with the sentence wrapped. -## Continue here with unsaved edits, another device continuing first, or an unreachable computer +## Move here with unsaved edits, another device continuing first, or an unreachable computer When continuing a chat from another paired computer: - If you had unsaved edits to that chat here, they are not overwritten. They are kept as a branch and the chat says `your unsaved edits here were kept as turns from `. -- If another machine took an `offline` chat first, the row goes back to `held on ` with a card saying `another device continued this chat first`, `1 retry` and `2 leave it there`. if the same computer picked it up again, the card instead says ` picked this chat up again; press enter to continue it here` and asks for fresh confirmation. +- If another machine took an `offline` chat first, the row goes back to `held on ` with a card saying `another device moved this chat first`, `1 retry` and `2 leave it there`. if the same computer picked it up again, the card instead says ` picked this chat up again; press enter to move it here` and asks for fresh confirmation. - if the service cannot be reached, enter names its host and says it is still trying, and asks nothing: no chat can be taken without them. -- With no way to continue set up, an offline row has no `continue here`: enter says its sentence. +- With no way to continue set up, an offline row has no `move here`: enter says its sentence. -## Is my project folder changed when I continue a chat here — what comes with a continued chat, the files, binary files, file modes, the executable bit, the .env, where the copy lives, no git needed +## Is my project folder changed when I move a chat here — what comes with a continued chat, the files, binary files, file modes, the executable bit, the .env, where the copy lives, no git needed Continuing a chat brings all of it: the whole conversation, and every file the chat worked on, byte for byte: text and binary files, files that were never in a git repository, the executable bit, links. Git history, branches and settings travel too, sealed to your paired devices even when an old commit holds a key. A working file the guard withholds travels on its -own road instead: the vault when sync storage is approved, and the chat's own blind pass-through +own road instead: the vault when relay storage is approved, and the chat's own blind pass-through when it is off. Rebuildable install folders such as `node_modules` stay out of the workspace copy and are listed on the arrival card (see "What a moved chat left behind"). Nothing is fetched from git and no git login or remote is needed on the machine that continues; everything comes from your relay. The copy lives in a folder of @@ -385,9 +385,9 @@ the other machine's work. ## Do secret files and .env come with a continued chat **Secret working files travel on their own road, never in the chat's file capture.** A `.env`, at any depth, and any other working file the guard recognises as holding a -secret is kept out of the chat's file capture. With sync storage approved it is kept whole in your key vault instead, and the vault -travels with your chats. With sync storage off, the same files move with the chat by blind pass-through while both computers run codeaf -(*Do my .env files and secrets move to my other computer without sync storage*, in *Continuing a chat that one of your machines holds*). +secret is kept out of the chat's file capture. With relay storage approved it is kept whole in your key vault instead, and the vault +travels with your chats. With relay storage off, the same files move with the chat by blind pass-through while both computers run codeaf +(*Do my .env files and secrets move to my other computer without relay storage*, in *Continuing a chat that one of your machines holds*). When you continue, each of those files is put back at the same path in the chat's work folder, with the same bytes and the same permissions: comments, order and quoting are as you wrote them. Each file is carried on its own, so two machines that edited @@ -397,7 +397,7 @@ by blind pass-through it is never removed. With no identity on this machine, no ## Do saved provider keys and credentials follow me to another computer -On the hosted sync service, saved keys wait for sync storage approval (Settings → Devices → sync storage). +On the hosted relay, saved keys wait for relay storage approval (Settings → Devices → relay storage). Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. @@ -417,13 +417,13 @@ is kept beside it as `credentials.json.damaged`. ## Do budgets, settings and model choices move between computers -On the hosted sync service, shared settings wait for sync storage approval (Settings → Devices → sync storage). +On the hosted relay, shared settings wait for relay storage approval (Settings → Devices → relay storage). Your stored model picks, display and approval defaults, and spending-limit values follow your paired computers through the encrypted vault. Each setting merges independently; the later edit wins. Spending counted against a limit stays **per computer**, so a daily limit is not a combined fleet allowance. Local paths, caches, service addresses, automations and operator environment pins stay on their computer. Person and project memories also follow within a sync round, including lines edited by hand and memories from older chats. Concurrent edits of different lines survive; the later edit of the same line wins. Machine-scoped memories stay local. -## Unsaved local edits when continuing a chat here — the kept branch +## Unsaved local edits when moving a chat here — the kept branch If you continue a chat on a machine that already has it, the chat as it was left replaces what is there. Anything you had changed and never saved is kept first, as a branch, saying `your unsaved edits here were kept as turns from `; nothing is thrown away. If another machine takes the @@ -433,7 +433,7 @@ chat while you are still fetching it, this machine keeps exactly what it had. Yes. When you continue a chat on your own paired device, the repository's `.git` travels as it is, including its history, branches, settings and any keys in old commits. Task commits travel too. Git history is sealed end to end between your devices; the relay sees only ciphertext. codeaf does not screen, remove or rewrite committed secrets. -The working-tree guard is separate: a `.env` or source file it recognises as holding a secret is excluded from the chat's file capture and sent on its own road, sealed: the encrypted vault, or blind pass-through while sync storage is off. The scanner reads the whole file, including keys past its first MiB. If the secret was committed, its Git copy still travels with the history. An untracked secret file with no committed copy arrives only by that separate road. +The working-tree guard is separate: a `.env` or source file it recognises as holding a secret is excluded from the chat's file capture and sent on its own road, sealed: the encrypted vault, or blind pass-through while relay storage is off. The scanner reads the whole file, including keys past its first MiB. If the secret was committed, its Git copy still travels with the history. An untracked secret file with no committed copy arrives only by that separate road. ## What a move carries and what it leaves behind — job logs, task history, kept branches, do spend and usage numbers sync between computers, memory, withheld folders @@ -450,7 +450,7 @@ A chat that moves to another computer brings, from the relay and sealed on the w The project's task history (the list of finished tasks) and the git bookkeeping inside a task's working copy are not carried: they are made again on the other computer from the chat's own record. -It leaves behind, and lists on the card under `not brought along:`: install folders a lockfile rebuilds (`node_modules`, `.venv`, `target`, `vendor`, `Pods`), files this computer cannot read, and one of two names that differ only in letter case or accent. A read-only folder arrives read-only. A secret file (`.env`) is not in the chat's files: it travels on its own, in the key vault or by blind pass-through while sync storage is off. Stored limit values, model picks and personal memory follow separately through the encrypted vault. Spending against limits remains per computer; machine-scoped memory and local paths stay local. +It leaves behind, and lists on the card under `not brought along:`: install folders a lockfile rebuilds (`node_modules`, `.venv`, `target`, `vendor`, `Pods`), files this computer cannot read, and one of two names that differ only in letter case or accent. A read-only folder arrives read-only. A secret file (`.env`) is not in the chat's files: it travels on its own, in the key vault or by blind pass-through while relay storage is off. Stored limit values, model picks and personal memory follow separately through the encrypted vault. Spending against limits remains per computer; machine-scoped memory and local paths stay local. ## Does dist or other gitignored output move — ignored files and secret files @@ -546,13 +546,13 @@ while the row has copies and this build can open or discard them, and `k` does n With several copies each press shows the next copy's card, ending `(copy 2 of 3)`, and after the last it starts again; the note's count is the number of cards. A copy whose every turn is already in the chat still offers `2 discard`, and its card ends `already in this chat, so discarding loses nothing`. A chat another computer holds -shows its copies as the count only: continue it here first, and the key is on its row. +shows its copies as the count only: move it here first, and the key is on its row. ## Why do I see the same chat twice on Home — the same chat twice on Home, one row per chat id and collapsed branch copies -Home keys every conversation row by the chat's id rather than its transcript path, both directly on this computer and over `codeaf chat --host`. A chat known both locally on disk and through sync appears once on Home instead of twice. Under `codeaf chat --host`, `continue here` is not offered and a chat the remote host already holds never appears a second time as held elsewhere. +Home keys every conversation row by the chat's id rather than its transcript path, both directly on this computer and over `codeaf chat --host`. A chat known both locally on disk and through sync appears once on Home instead of twice. Under `codeaf chat --host`, `move here` is not offered and a chat the remote host already holds never appears a second time as held elsewhere. -When a chat also has kept branch copies, Home collapses those copies into the main chat's row instead of listing separate duplicate rows for the same chat. The row and its continue card count the copies, say what a copy is, and state whether discarding loses anything. To open or discard a copy, press `→` on the chat's row and then `k` (*Open separately or discard the turns of a branch*): +When a chat also has kept branch copies, Home collapses those copies into the main chat's row instead of listing separate duplicate rows for the same chat. The row and its move card count the copies, say what a copy is, and state whether discarding loses anything. To open or discard a copy, press `→` on the chat's row and then `k` (*Open separately or discard the turns of a branch*): - `1 copy (unsent turns set aside; already in this chat, so discarding loses nothing)` — or `1 copy · unsent, loses nothing` in a narrow column — when every turn in the copy is already in the main chat. - `2 copies (unsent turns set aside; discarding archives 3 turns not in this chat)` — or `2 copies · unsent, 3 turns not here` in a narrow column — when a copy holds turns that are not in the main chat. @@ -671,7 +671,8 @@ use `alt+p`. To start a chat from a conversation row's folder, use `ctrl+t`. A row is the folder's path, how many conversations are in it and how many are running, and where its repository stands — the branch and the dirty count as one clause. **This window's folder is always the first row**, even before anyone has spoken in it, which is why the -panel is never empty. **Paths are absolute and truncate on the right**: `/tmp/landing-test` +panel is never empty. A live view of a chat on another computer does not change it: that chat's +folder is on the other computer (*Home's project after a live view*). **Paths are absolute and truncate on the right**: `/tmp/landing-test` stays `/tmp/landing-test` while it fits, and a longer path becomes `/tmp/landing-te…` when space runs out. Only paths inside your home directory use `~/`; home itself is `~`. A similarly named sibling directory does not get that abbreviation. Counts and repository @@ -2751,17 +2752,17 @@ from a previous visit cannot replace the current visit's selection or draft. ## I quit on my laptop and opened my desktop — straight back into the chat -While hosted sync storage is off, `idle handoff` does not run, and a laptop where codeaf has quit cannot hand the chat over: the desktop can take it only while codeaf is running on the laptop. See *Blind pass-through*. +While hosted relay storage is off, `idle handoff` does not run, and a laptop where codeaf has quit cannot hand the chat over: the desktop can take it only while codeaf is running on the laptop. See *Blind pass-through*. -After a clean quit lets a paired computer's chat go (or, when **Settings → General → idle handoff** / `CODEAF_IDLE_HANDOFF=1` is turned on — off by default — about 2 seconds after an idle paired chat goes idle once saved to the sync service), bare `codeaf` on another paired computer continues that released chat automatically within 24 hours, and with `idle handoff` on Enter on Home opens a released chat directly (with `idle handoff` off, Home rows ask **Continue here**). A lapsed hold on another computer still asks Continue here, including when its holder was working. You arrive with the `Moved from` banner and the usual `not brought along:` facts; `esc` goes Home. +After a clean quit lets a paired computer's chat go (or, when **Settings → General → idle handoff** / `CODEAF_IDLE_HANDOFF=1` is turned on — off by default — about 2 seconds after an idle paired chat goes idle once saved to the relay), bare `codeaf` on another paired computer continues that released chat automatically within 24 hours, and with `idle handoff` on Enter on Home opens a released chat directly (with `idle handoff` off, Home rows ask **Move here**). A lapsed hold on another computer still asks Move here, including when its holder was working. You arrive with the `Moved from` banner and the usual `not brought along:` facts; `esc` goes Home. -If the laptop went to sleep or lost its connection while still holding the chat, Home offers its latest chat while the hold is live and `alt+c` continues immediately (once the hold lapses, Enter on its Home row still asks Continue here). When local unsaved edits need to be kept as a branch, the continuation card asks first. Nothing moves automatically while the other computer is running that chat, for a named chat or `--host`/`--at`/`--session`, when another local window holds a chat, or when local unsaved edits need a choice. If the move fails, Home stays open and says why. +If the laptop went to sleep or lost its connection while still holding the chat, Home offers its latest chat while the hold is live and `alt+c` continues immediately (once the hold lapses, Enter on its Home row still asks Move here). When local unsaved edits need to be kept as a branch, the continuation card asks first. Nothing moves automatically while the other computer is running that chat, for a named chat or `--host`/`--at`/`--session`, when another local window holds a chat, or when local unsaved edits need a choice. If the move fails, Home stays open and says why. ## my chosen chat opens while a startup chat is still arriving -if bare startup is already continuing a released chat, confirming a different Home row or using `alt+c` chooses the chat that opens next. Home says `continuing next; is still on its way here`, using the same chat titles as the cards. the automatic move settles and is let go before your confirmed move begins. its files and kept work remain intact, and it never opens over your selection. `esc` cancels the waiting choice; the automatic chat still settles and is let go. +if bare startup is already continuing a released chat, confirming a different Home row or using `alt+c` chooses the chat that opens next. Home says `moving next; is still on its way here`, using the same chat titles as the cards. the automatic move settles and is let go before your confirmed move begins. its files and kept work remain intact, and it never opens over your selection. `esc` cancels the waiting choice; the automatic chat still settles and is let go. -confirming the arriving chat itself joins the existing move. opening another local chat or starting a new chat also takes precedence over the automatic arrival. moving the cursor, opening Home or inspecting and declining another card does not choose a different chat. input before the startup safety check answers still cancels that automatic choice. a move you explicitly started retains the busy sentence `a chat is already continuing here; wait for it to open` for another explicit pick. +confirming the arriving chat itself joins the existing move. opening another local chat or starting a new chat also takes precedence over the automatic arrival. moving the cursor, opening Home or inspecting and declining another card does not choose a different chat. input before the startup safety check answers still cancels that automatic choice. a move you explicitly started retains the busy sentence `a chat is already moving here; wait for it to open` for another explicit pick. ## Empty untitled chats from your other devices — rows before the first saved turn @@ -2769,10 +2770,10 @@ An empty new chat on one of your other devices stays off Home until it has a sav ## Sync off and my chats are gone — CODEAF_SYNC_URL=off keeps every chat on this computer -Turning sync off with `CODEAF_SYNC_URL=off` (or leaving sync off before pairing) means "do not talk to the sync service", never "forget my chats". Home still lists every chat on this computer — chats this version saved and chats from older versions alike — each once, and each opens and can be written. +Turning sync off with `CODEAF_SYNC_URL=off` (or leaving sync off before pairing) means "do not talk to the relay", never "forget my chats". Home still lists every chat on this computer — chats this version saved and chats from older versions alike — each once, and each opens and can be written. -When an older chat was already copied into this version's store, Home lists and opens that copy even while sync is off, and the untouched original stays on disk beside it. Saved sync hold receipts from an earlier session stay dormant while sync is off, so sending a message in any local chat works without asking the sync service. +When an older chat was already copied into this version's store, Home lists and opens that copy even while sync is off, and the untouched original stays on disk beside it. Saved sync hold receipts from an earlier session stay dormant while sync is off, so sending a message in any local chat works without asking the relay. -## Why are chats and files still on this computer after pairing — sync storage +## Why are chats and files still on this computer after pairing — relay storage -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. Home can list paired devices while uploads wait; an offline computer cannot supply new turns that never reached the service. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. Home can list paired devices while uploads wait; an offline computer cannot supply new turns that never reached the service. diff --git a/internal/manual/chat/keys.md b/internal/manual/chat/keys.md index a5300cbb6b..7df7836a9c 100644 --- a/internal/manual/chat/keys.md +++ b/internal/manual/chat/keys.md @@ -46,7 +46,7 @@ sentence that surprises you can be traced. A window that only shows a chat another computer holds has no turns of its own to save, so quitting it says nothing of the kind, even if an earlier save attempt on this window failed. On the next start, retained turns are published if this computer still holds the chat. -If another computer has continued it, choose continue here from Home (or, with `idle handoff` on, open it from Home once no computer holds it) to see its newest history; +If another computer has moved it, choose move here from Home (or, with `idle handoff` on, open it from Home once no computer holds it) to see its newest history; local accounting alone does not create a separate chat. A computer removed from your paired devices keeps saving this chat locally. @@ -56,10 +56,10 @@ already explains that the chat stays on this computer until you pair it again. ## The line the terminal prints after you quit, when another device took the chat over If codeaf learns while closing that another device took the chat, the restored -terminal says ` continued this chat. This copy is read-only and may be behind` +terminal says ` moved this chat. This copy is read-only and may be behind` once. It keeps this notice even when the full-screen chat has already closed. -## Quitting while the sync service is slow — waiting for a final save +## Quitting while the relay is slow — waiting for a final save A removed computer quits quietly; it no longer says it is saving to your other devices. @@ -67,16 +67,16 @@ The screen closes after at most one second while a slow close finishes. The launcher keeps its connection open for the final publish and release before it exits. A successful quit with nothing waiting stays quiet. While a sync save waits, the restored terminal says `saving this chat to your other devices…`. After about three seconds, a confirmed local save adds `still saving — ctrl+c leaves it saved here`; without that confirmation, it says `still saving on this computer — ctrl+c leaves the written turns here`. -The launcher waits up to 30 seconds for the final saving reply. If only upload is outstanding, the successful receipt is `saved here; it reaches your other devices when the sync service at 127.0.0.1:8901 answers`, using your service's host. If that pending upload was refused because storage is off, the successful receipt is `saved here; sync storage is off for this account, so it stays on this computer`. Ctrl+c during this restored-terminal wait exits promptly with the same receipt when local saving is confirmed. Without confirmation, it says `saving on this computer has not finished; its written turns stay here` and exits unsuccessfully. Only a failed local write says `codeaf could not save this chat`. +The launcher waits up to 30 seconds for the final saving reply. If only upload is outstanding, the successful receipt is `saved here; it reaches your other devices when the relay at 127.0.0.1:8901 answers`, using your service's host. If that pending upload was refused because storage is off, the successful receipt is `saved here; relay storage is off for this account, so it stays on this computer`. Ctrl+c during this restored-terminal wait exits promptly with the same receipt when local saving is confirmed. Without confirmation, it says `saving on this computer has not finished; its written turns stay here` and exits unsuccessfully. Only a failed local write says `codeaf could not save this chat`. ## One Enter sends — checking which computer holds this chat A chat held here, or one never shared, sends with one Enter using its local -hold. Sending does not wait for the sync service to answer. An established +hold. Sending does not wait for the relay to answer. An established outage does not add another network wait to every send. A copy with no current hold gets one fresh check, bounded to five seconds. -It sends, offers `Continue this chat here?`, or explains why the words remain +It sends, offers `Move this chat here?`, or explains why the words remain unsent. If you change chats meanwhile, it says `chat changed before sending; your words are still unsent`. If you edit the draft meanwhile, it says @@ -774,7 +774,7 @@ cannot send it delivers plain enter on many keyboards, or a newline on some. | `ctrl+w` | **Close this tab** — the same thing the `✕` on it does. Selects the last-used remaining tab, or Home if none remain. Drafts are kept, and the conversation keeps running; a tab with work in it asks `keep running` / `stop work` / `cancel` first | | `alt+t` (`opt+t`) | Give the keyboard to the task roster. Press again or `esc` to take it back | | `alt+l` (`opt+l`) | Close the column on the right, or bring it back, in every chat: the same column holds the Tasks and, in a chat in a team, the Traffic. The key is named at the right of the column's header. Under 100 columns it lays the column over the body, and a second press takes it off. Remembered for the next session | -| `alt+m` | In a team that has a manager: go to the manager. Over `--host` against an older codeaf on the far machine it says managers are not available there | +| `alt+m` | In a team that has a manager: go to the manager. Over `--host` against an older codeaf on the far machine it says managers are not available there. In a chat opened live from another of your computers (the page *Remote control*): move that chat here; it asks `Move this chat here?` first | | `ctrl+g` | A foreground command that can be kept takes the key first. Otherwise it does what `alt+l` does: close the column, or bring it back; the column stands even with no tasks in it. Remembered for the next session | | `ctrl+e` | Empty box: open or close the running conversation’s compact steps first; otherwise the newest `▸ worked` chip onto its outline of captions — the latest completed turn's out here, the newest completed work inside a task's page — or the most recent thinking block when there is no chip. A caption is a short status line per step; its tool rows are one expand further. Otherwise: go to end of line | | `pgup` / `pgdown` | Scroll one page — the height of the view minus one, never less than one row | @@ -1265,9 +1265,9 @@ that has moved on. There is nothing to press; it is automatic. - CR and CRLF in a restored draft are normalised to LF. - No draft is kept at all if codeaf was started without a draft file. -## Continue here keeps my typed message, pasted text and attachments +## Move here keeps my typed message, pasted text and attachments -If sending from an older window opens `Continue this chat here?`, choosing `continue here` puts your exact draft in the arrived chat's message box, including spaces, newlines, pasted text and attachments. This also works when the chat reopens in a different folder. It stays unsent until you press enter again. Choosing `leave it there`, or a move that fails, keeps the draft too. +If sending from an older window opens `Move this chat here?`, choosing `move here` puts your exact draft in the arrived chat's message box, including spaces, newlines, pasted text and attachments. This also works when the chat reopens in a different folder. It stays unsent until you press enter again. Choosing `leave it there`, or a move that fails, keeps the draft too. ## What a crash does to your draft — what is saved, what comes back, what it will not send diff --git a/internal/manual/chat/lock-out-a-lost-computer.md b/internal/manual/chat/lock-out-a-lost-computer.md index 4221b2b6fc..aac02c0058 100644 --- a/internal/manual/chat/lock-out-a-lost-computer.md +++ b/internal/manual/chat/lock-out-a-lost-computer.md @@ -4,7 +4,7 @@ Stopping a computer with `codeaf devices revoke ` cuts it off from the relay. It does not undo what it holds. That computer has your whole identity. It can read everything it already has, and it can make itself a new device. -`codeaf identity rotate` is the real fix. It makes a replacement identity and moves your saved keys to it. With hosted sync storage off, rotation still finishes without uploading chats or resealed keys: chats stay on the computers that hold them. Previously stored frames remain under the old identity until grace-period erasure. The old identity is shut. The lost computer holds the old one, so it can read nothing of what you do from then on. +`codeaf identity rotate` is the real fix. It makes a replacement identity and moves your saved keys to it. With hosted relay storage off, rotation still finishes without uploading chats or resealed keys: chats stay on the computers that hold them. Previously stored frames remain under the old identity until grace-period erasure. The old identity is shut. The lost computer holds the old one, so it can read nothing of what you do from then on. Run it on a computer you keep, as soon as you know a computer is lost: @@ -91,9 +91,9 @@ A way to prove your identity with a written recovery phrase is not built. ## What rotation costs — uploads with storage on, local copies with storage off -Hosted sync storage is off by default while privacy terms are being finished; request access in Settings → Devices → sync storage → enter to enable uploads. Pairing and live `--at` work while storage is off; your own sync service with `--store` needs no request. +Hosted relay storage is off by default while privacy terms are being finished; request access in Settings → Devices → relay storage → enter to enable uploads. Pairing and live `--at` work while storage is off; your own relay with `--store` needs no request. -With hosted storage off, rotation completes with no store writes. Chats remain on your computers; any already-stored frames are left to the old identity’s grace-period erasure. With storage on, a rotation uploads everything your chats hold, once, because the new identity starts empty. The plan it shows before you answer gives the number. A chat of 200 MB goes up as 200 MB. The transfer takes your network bandwidth and uses sync storage; the old and new copies count towards its limits during the grace period. There is no fixed price or duration promised by the command. +With hosted storage off, rotation completes with no store writes. Chats remain on your computers; any already-stored frames are left to the old identity’s grace-period erasure. With storage on, a rotation uploads everything your chats hold, once, because the new identity starts empty. The plan it shows before you answer gives the number. A chat of 200 MB goes up as 200 MB. The transfer takes your network bandwidth and uses relay storage; the old and new copies count towards its limits during the grace period. There is no fixed price or duration promised by the command. While the old identity is kept for the grace period, the relay holds both copies. diff --git a/internal/manual/chat/losing-every-device.md b/internal/manual/chat/losing-every-device.md index 6dd84e5a20..955f84d847 100644 --- a/internal/manual/chat/losing-every-device.md +++ b/internal/manual/chat/losing-every-device.md @@ -13,10 +13,10 @@ Only two things can save you before that day: ## Can I change my identity — identity rotate -If one trusted computer remains, **`codeaf identity rotate` works now**. It makes a replacement identity and reseals saved keys locally. With hosted sync storage off, it finishes with no resealing uploads and chats stay on your computers; with storage on, it reseals and uploads chats and saved keys. It retires the relay's old copy after the grace period. Pair the computers you keep again from that replacement. Read *Locking out a lost computer for good* for the steps and limits. +If one trusted computer remains, **`codeaf identity rotate` works now**. It makes a replacement identity and reseals saved keys locally. With hosted relay storage off, it finishes with no resealing uploads and chats stay on your computers; with storage on, it reseals and uploads chats and saved keys. It retires the relay's old copy after the grace period. Pair the computers you keep again from that replacement. Read *Locking out a lost computer for good* for the steps and limits. Rotation needs the old identity on a surviving computer. It cannot recover an identity when every copy, including any exported identity file and its passphrase, is lost. Revoking or rotating cannot take back chats and keys already downloaded by a lost computer; change exposed provider keys at their providers. -## Why pairing alone is not a backup — sync storage and completed uploads +## Why pairing alone is not a backup — relay storage and completed uploads -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. A chat that moved live is kept only on the computers that hold it; the sync service keeps no copy, so blind pass-through is not a backup. Approval cannot recover turns that never left a lost computer. Keep a surviving computer with the content, or an exported identity and an accessible encrypted copy. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. A chat that moved live is kept only on the computers that hold it; the relay keeps no copy, so blind pass-through is not a backup. Approval cannot recover turns that never left a lost computer. Keep a surviving computer with the content, or an exported identity and an accessible encrypted copy. diff --git a/internal/manual/chat/models-and-cost.md b/internal/manual/chat/models-and-cost.md index a62f06c5ac..47a4234808 100644 --- a/internal/manual/chat/models-and-cost.md +++ b/internal/manual/chat/models-and-cost.md @@ -4822,7 +4822,7 @@ a chain ends after ten requests rather than waiting forever. ## Do my crew settings follow me to my other computer? -Shared settings wait for hosted sync storage approval (Settings → Devices → sync storage). A self-hosted sync service with `--store` needs no request. +Shared settings wait for hosted relay storage approval (Settings → Devices → relay storage). A self-hosted relay with `--store` needs no request. After pairing, crew seat model pins, allowed-model choices, the crew daily cap, per-task cap and free-route choice follow synced preferences within a few seconds, diff --git a/internal/manual/chat/naming-a-device.md b/internal/manual/chat/naming-a-device.md index a2d30063f2..4892d11372 100644 --- a/internal/manual/chat/naming-a-device.md +++ b/internal/manual/chat/naming-a-device.md @@ -6,7 +6,7 @@ Moving chats and pairing are available by default on Linux, macOS and native Win Older chats move through an independent copy. Once paired, codeaf prepares chats active in the last 30 days in the background, one at a time; opening another older chat prepares its copy then. This build shows and writes to the copy. The original files stay untouched and remain usable in older codeaf builds. -Every screen that names a device uses one name for it: the home rows (`working on tower`, `held on tower`, `tower offline`), `Continue tower's latest chat here?`, the approve screen, `tower is now paired. Your chats can continue there.`, `/devices`, `/settings` → `Devices`, and the line after a move, `Moved from tower in 4s`. A device is called by its host name, the word your operating system already uses for it, until you give it a name. A name is only a label. It is not a key and it signs nothing, and renaming a device changes nothing about what it can reach. +Every screen that names a device uses one name for it: the home rows (`working on tower`, `held on tower`, `tower offline`), `Move tower's latest chat here?`, the approve screen, `tower is now paired. tower can also see and control your chats here. Change that in /devices.`, `/devices`, `/settings` → `Devices`, and the line after a move, `Moved from tower in 4s`. A device is called by its host name, the word your operating system already uses for it, until you give it a name. A name is only a label. It is not a key and it signs nothing, and renaming a device changes nothing about what it can reach. Because you never named this device, it kept the default. Name it and every other device shows the new name. @@ -46,7 +46,7 @@ After a rename it says: This computer is now called atlas on all your devices. ``` -Your other devices show the new name the next time they list devices or draw a home row. If the sync service cannot be reached at that moment, the device keeps the name and says: +Your other devices show the new name the next time they list devices or draw a home row. If the relay cannot be reached at that moment, the device keeps the name and says: ``` This computer is now called atlas. Your other devices will show it after this one next connects. diff --git a/internal/manual/chat/reaching-this-machine-without-ssh.md b/internal/manual/chat/reaching-this-machine-without-ssh.md index 5d21cbf6f9..2abd8bfc04 100644 --- a/internal/manual/chat/reaching-this-machine-without-ssh.md +++ b/internal/manual/chat/reaching-this-machine-without-ssh.md @@ -15,6 +15,8 @@ You learn one thing: **a code shown on a screen you own, typed on the other comp **One code never gives both.** A code for your chats does not give a shell on any machine. A code for a machine does not give your chats. +Pairing your chats adds a third thing, once remote control is on: your paired computers can open live the chats the others are running, and type into them if you allow it. It is neither of the two grants above. It starts no chat and runs nothing on a machine you did not already run a chat on, and `codeaf serve` and `--at` are unchanged. When the two computers can reach each other, a live view travels straight between them instead of through the server in between. The page *Remote control* compares the three. + Both codes are good for 10 minutes and take 1 attempt. For both, the two screens show the same three words, and a person answers `y / n` on the machine being opened. The page *Pairing your chats with a second computer* has the chats door. ## Reaching a machine behind a router or a firewall @@ -112,14 +114,14 @@ If the relay turns registrations away — it allows 10 registrations a minute fr address — `codeaf serve` backs off the same way and says once: ``` -the sync service is turning registrations away right now — waiting before trying again +the relay is turning registrations away right now — waiting before trying again ``` -A relay that answers but cannot connect machines, such as an older sync service, stops +A relay that answers but cannot connect machines, such as an older relay, stops it with: ``` -the sync service at https://service.example.com syncs chats but does not connect machines — run your own with `codeaf relay` and set CODEAF_RELAY to it +the relay at https://service.example.com syncs chats but does not connect machines — run your own with `codeaf relay` and set CODEAF_RELAY to it ``` A relay that cannot be reached when it starts stops it with the sentence in *When --at @@ -127,7 +129,7 @@ will not open*. With sync turned off (`CODEAF_SYNC_URL=off`) and no `CODEAF_RELA is no relay at all: ``` -no sync service is set up on this machine, so there is nowhere to be reachable from — set CODEAF_RELAY to your sync service +no relay is set up on this machine, so there is nowhere to be reachable from — set CODEAF_RELAY to your relay ``` Ctrl+c ends it, and the machine gives its name back on the way out: @@ -413,25 +415,25 @@ There are five different reasons, and each says which one it is, in one sentence **No relay is set up on this machine** (sync is off and `CODEAF_RELAY` is empty): ``` -no sync service is set up on this machine, so --at has nowhere to look for otter-lamp-42 — set CODEAF_RELAY to a sync service, or reach that machine with --host over ssh +no relay is set up on this machine, so --at has nowhere to look for otter-lamp-42 — set CODEAF_RELAY to a relay, or reach that machine with --host over ssh ``` **The relay is set up and not answering:** ``` -nothing is answering at https://service.example.com — if that is your own sync service, start it there with codeaf relay +nothing is answering at https://service.example.com — if that is your own relay, start it there with codeaf relay ``` **The relay answers but cannot connect machines:** ``` -the sync service at https://service.example.com syncs chats but does not connect machines — run your own with `codeaf relay` and set CODEAF_RELAY to it, or reach that machine with --host over ssh +the relay at https://service.example.com syncs chats but does not connect machines — run your own with `codeaf relay` and set CODEAF_RELAY to it, or reach that machine with --host over ssh ``` **The relay is fine and that machine is not connected to it:** ``` -otter-lamp-42 is not connected to the sync service right now — run `codeaf serve` on that machine +otter-lamp-42 is not connected to the relay right now — run `codeaf serve` on that machine ``` **This device has never been let in:** @@ -443,10 +445,10 @@ this device is not paired with otter-lamp-42 — run `codeaf serve` on that mach Two more you may meet. A machine that does not answer the handshake at all: `otter-lamp-42 did not answer this device's handshake, so nothing was sent — if that machine was rebuilt it has a new key and this device has to pair with it again`. And a relay that is turning connections away: -`the sync service is turning connections away right now — try again in a minute` — it allows +`the relay is turning connections away right now — try again in a minute` — it allows 30 connections a minute from one address. If a proxy or wrong path at the relay address refuses the upgrade, it names the full address it tried: -`the sync service at https://service.example.com/wrong-prefix refused this connection (404) — check the address it was given`. +`the relay at https://service.example.com/wrong-prefix refused this connection (404) — check the address it was given`. ## The pairing code was right but approval failed — paired then device stopped, writing access on the serving computer @@ -585,6 +587,6 @@ connection errors, reconnecting notices and timeout messages. Its typed rendezvous name still selects the machine to connect to. If an older engine has not supplied a chosen name, the window uses the requested name. -## Does live --at access need sync storage approval? +## Does live --at access need relay storage approval? -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. Live access works on the other computer while it stays on; storage approval is needed to copy saved chats so they can open elsewhere when it is off. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. Live access works on the other computer while it stays on; storage approval is needed to copy saved chats so they can open elsewhere when it is off. diff --git a/internal/manual/chat/relay-hosted-or-your-own.md b/internal/manual/chat/relay-hosted-or-your-own.md index 365d3d4fa8..f939c7296d 100644 --- a/internal/manual/chat/relay-hosted-or-your-own.md +++ b/internal/manual/chat/relay-hosted-or-your-own.md @@ -8,7 +8,7 @@ Older chats move through an independent copy. Once paired, codeaf prepares chats A relay is the small service your computers sync through. There are two kinds. Both speak the same wire. -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. - **A hosted relay** is run for you on a cloud account. You do nothing to run it. You give the chat its address. - **Your own relay** is the program `codeaf relay`. You run it on a computer you control. @@ -17,7 +17,7 @@ Either way the relay sees only ciphertext and the short list on "What can the re ## Where sync goes by default — stable, staging and dev relay addresses -Unset, each release channel selects its own hosted relay: stable releases and release candidates use `https://codeaf.agentfield.ai/fabric`, staging builds use `https://caf-fabric-staging.instrument-santosh.workers.dev`, and dev builds and local builds from source use `https://caf-fabric-dev.instrument-santosh.workers.dev`. Channels do not sync with each other: computers must run the same channel (or set the same `CODEAF_SYNC_URL`) to pair and share chats. A build whose `HostedRelayURL` is empty has no default, and then nothing is copied and pairing says `no sync service is set, so there is nowhere to pair through: set CODEAF_SYNC_URL to its address, or pass --via
`. A new home sends no relay requests before completing a pairing or offering a code or link. Reading the add-device instructions does not start sync. Older identities without the quiet marker retain their earlier behavior: see "Is my code sent anywhere before I pair" on the page *Pairing your chats with a second computer*. To use your own relay instead, set `CODEAF_SYNC_URL` as below. Turn sync off with `CODEAF_SYNC_URL=off`; pairing cannot override that with `--via`. +Unset, each release channel selects its own hosted relay: stable releases and release candidates use `https://codeaf.agentfield.ai/fabric`, staging builds use `https://caf-fabric-staging.instrument-santosh.workers.dev`, and dev builds and local builds from source use `https://caf-fabric-dev.instrument-santosh.workers.dev`. Channels do not sync with each other: computers must run the same channel (or set the same `CODEAF_SYNC_URL`) to pair and share chats. A build whose `HostedRelayURL` is empty has no default, and then nothing is copied and pairing says `no relay is set, so there is nowhere to pair through: set CODEAF_SYNC_URL to its address, or pass --via
`. A new home sends no relay requests before completing a pairing or offering a code or link. Reading the add-device instructions does not start sync. Older identities without the quiet marker retain their earlier behavior: see "Is my code sent anywhere before I pair" on the page *Pairing your chats with a second computer*. To use your own relay instead, set `CODEAF_SYNC_URL` as below. Turn sync off with `CODEAF_SYNC_URL=off`; pairing cannot override that with `--via`. ## Point codeaf at a relay — CODEAF_SYNC_URL, url or off @@ -30,7 +30,7 @@ CODEAF_SYNC_URL=https://relay.example.com codeaf ``` - **A web address** like `https://relay.example.com` or `http://host:8787`. Plain `http` is for trying it out inside an ssh tunnel. An address that is not a web address stops with `CODEAF_SYNC_URL is not a web address like http://host:8787`. -- **`off`** turns the relay off. Pairing then says `sync is off (CODEAF_SYNC_URL=off); pairing needs the sync service`. Home still lists every chat on this computer — chats this version saved and chats from older versions alike — each once, and each opens and can be written. +- **`off`** turns the relay off. Pairing then says `sync is off (CODEAF_SYNC_URL=off); pairing needs the relay`. Home still lists every chat on this computer — chats this version saved and chats from older versions alike — each once, and each opens and can be written. - **Unset:** a computer that was paired with a named relay uses the relay the pairing saved. Otherwise it uses the hosted default above, if this build has one, and has none if it does not. Your own computers must all name the same relay and hold the same identity, or they see different chats. @@ -66,29 +66,29 @@ Moving chats and pairing are available by default on Linux, macOS and native Win **Any caller with a valid signature may make an identity and store on your relay.** The relay has no list of allowed people: an identity is made from a key, and the relay accepts any key. Keep your relay on a private network, a tailnet or behind a proxy that checks who calls. One identity cannot read another's data. -## My sync service is too old to move chats — update before continuing here +## My relay is too old to move chats — update before moving here -An older sync service still pairs computers, lists and shows chats, saves every chat you write, and opens or continues a chat no computer holds (one the other computer closed, let go of after about 2 idle seconds when **Settings → General → idle handoff** / `CODEAF_IDLE_HANDOFF=1` is turned on — off by default — or let expire). Only taking a chat another computer still holds (running, or idle while `idle handoff` is off, before release, or on an older build) waits for it, because only an updated service can promise that the take displaces the holder you saw. This build says `taking an open chat from another computer waits for a sync service update; all else works, so close it there and continue here`. Close the chat on that computer (or let it go idle with `idle handoff` on), then continue or open it here. For your own service, replace the running `codeaf relay` with this build; the next attempt uses the update without reopening codeaf. +An older relay still pairs computers, lists and shows chats, saves every chat you write, and opens or continues a chat no computer holds (one the other computer closed, let go of after about 2 idle seconds when **Settings → General → idle handoff** / `CODEAF_IDLE_HANDOFF=1` is turned on — off by default — or let expire). Only taking a chat another computer still holds (running, or idle while `idle handoff` is off, before release, or on an older build) waits for it, because only an updated service can promise that the take displaces the holder you saw. This build says `taking an open chat from another computer waits for a relay update; all else works, so close it there and move it here`. Close the chat on that computer (or let it go idle with `idle handoff` on), then move or open it here. For your own service, replace the running `codeaf relay` with this build; the next attempt uses the update without reopening codeaf. A chat you write on this computer is never held back by an older service. Releases of codeaf check that the hosted service answers what they need before they ship. -## Starting your own sync service — codeaf relay help and the pairing command +## Starting your own relay — codeaf relay help and the pairing command Run `codeaf relay --listen 127.0.0.1:8901 --store `. The first line is `codeaf relay is listening on 127.0.0.1:8901 — on each computer: codeaf pair --via http://127.0.0.1:8901`. Use an address the other computers can reach; 127.0.0.1 reaches only the computer itself. `codeaf relay --help` lists the ordinary options, and `codeaf help env` lists both service variables. -`CODEAF_SYNC_URL` selects the sync service for chats; `off` disables syncing. `CODEAF_RELAY` is the fallback service override for pairing when `CODEAF_SYNC_URL` is unset, and the remote connection override for `serve` and `chat --at`. An explicit `--via` at pairing selects and remembers the service for later starts. Every instruction for the new computer includes that `--via` argument when the service is your own. +`CODEAF_SYNC_URL` selects the relay for chats; `off` disables syncing. `CODEAF_RELAY` is the fallback service override for pairing when `CODEAF_SYNC_URL` is unset, and the remote connection override for `serve` and `chat --at`. An explicit `--via` at pairing selects and remembers the service for later starts. Every instruction for the new computer includes that `--via` argument when the service is your own. -## The sync service did not answer — unreachable, slow or unable to agree +## The relay did not answer — unreachable, slow or unable to agree -A refused connection, failed name lookup or missing route to your own service says `nothing is answering at http://127.0.0.1:8901 — if that is your own sync service, start it there with codeaf relay`. The hosted equivalent is `cannot reach codeaf.agentfield.ai — check this computer's internet connection`. +A refused connection, failed name lookup or missing route to your own service says `nothing is answering at http://127.0.0.1:8901 — if that is your own relay, start it there with codeaf relay`. The hosted equivalent is `cannot reach codeaf.agentfield.ai — check this computer's internet connection`. -A timeout says `the sync service at http://127.0.0.1:8901 did not answer in time — try again`. A server error says `the sync service at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute`. Each sentence uses the address you selected. +A timeout says `the relay at http://127.0.0.1:8901 did not answer in time — try again`. A server error says `the relay at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute`. Each sentence uses the address you selected. -`codeaf pair`, `codeaf devices` and `codeaf cluster status` say `asking the sync service at 127.0.0.1:8901…` to the error stream after two seconds without an answer, only when that stream is a terminal. +`codeaf pair`, `codeaf devices` and `codeaf cluster status` say `asking the relay at 127.0.0.1:8901…` to the error stream after two seconds without an answer, only when that stream is a terminal. -## A chat keeps working when the sync service is down +## A chat keeps working when the relay is down -A sync outage says `the sync service at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back`, once per outage. Local saves and rewind keep working. A local save by itself does not prove that syncing recovered. After an actual successful sync call, the chat can say `syncing again`; a sustained renewal outage keeps its existing `this chat is syncing again` recovery line. +A sync outage says `the relay at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back`, once per outage. Local saves and rewind keep working. A local save by itself does not prove that syncing recovered. After an actual successful sync call, the chat can say `syncing again`; a sustained renewal outage keeps its existing `this chat is syncing again` recovery line. ## Do chat folder names sync through the hosted relay diff --git a/internal/manual/chat/relay-limits-and-refusals.md b/internal/manual/chat/relay-limits-and-refusals.md index 451ee70f6d..83a29afee4 100644 --- a/internal/manual/chat/relay-limits-and-refusals.md +++ b/internal/manual/chat/relay-limits-and-refusals.md @@ -1,12 +1,16 @@ # Relay limits and refusals -## Taking an open chat from another computer waits for a sync service update +## Taking an open chat from another computer waits for a relay update -An older service cannot promise that taking a chat displaces only the computer you saw holding it, so this build never sends that take to it. The sentence is `taking an open chat from another computer waits for a sync service update; all else works, so close it there and continue here`. Writing, saving, pairing, listing, viewing and opening or continuing a chat no computer holds (closed, released after about 2 idle seconds when `idle handoff` / `CODEAF_IDLE_HANDOFF=1` is turned on — off by default — or lapsed) keep working. Close the chat on that computer (or let it go idle with `idle handoff` on), then continue or open it here; update your own `codeaf relay` to this build. +An older service cannot promise that taking a chat displaces only the computer you saw holding it, so this build never sends that take to it. The sentence is `taking an open chat from another computer waits for a relay update; all else works, so close it there and move it here`. Writing, saving, pairing, listing, viewing and opening or continuing a chat no computer holds (closed, released after about 2 idle seconds when `idle handoff` / `CODEAF_IDLE_HANDOFF=1` is turned on — off by default — or lapsed) keep working. Close the chat on that computer (or let it go idle with `idle handoff` on), then move or open it here; update your own `codeaf relay` to this build. With remote control on and that computer running the chat, you can also open it live from Home and work in it without taking it (the page *Remote control*). + +## Does a direct view count against the daily allowance — live traffic, daily limit, watch only until midnight + +The daily allowance of live traffic that *Remote control* describes counts the bytes the server carries for a live view, and nothing else. A view that has moved onto a direct connection between the two computers adds nothing to it, and the allowance neither cuts that view off nor turns it watch only. A view that has not moved to a direct connection turns watch only until 00:00 UTC when the allowance is used up, as that page says. ## Is there a storage limit on the relay — how much can I sync -Hosted uploads need sync storage approval (Settings → Devices → sync storage); these limits apply with storage on. +Hosted uploads need relay storage approval (Settings → Devices → relay storage); these limits apply with storage on. **A hosted relay has limits.** The hosted relay in this repository sets, for each identity: @@ -22,10 +26,10 @@ With storage on, a chunk already held costs nothing again. Storage off refuses e ## How much sync space have I used -When hosted storage is off, `/status` shows one dim `sync storage off` line instead of sync space. The cached permission is refreshed in the background at launch and after each `/status`. +When hosted storage is off, `/status` shows one dim `relay storage off` line instead of sync space. The cached permission is refreshed in the background at launch and after each `/status`. With storage on, open `/status` in a chat to see a dim `sync space` line, for example -`sync space 2.8 GiB of 5 GiB`. It shows how big your sync storage is and how +`sync space 2.8 GiB of 5 GiB`. It shows how big your relay storage is and how close you are to the relay limit: the amount stored, then the byte limit the hosted relay reports. The same reading appears in `/status --json`. The permission refresher retains its last successful amount in this process. While hosted storage is on it makes no further permission requests, so this amount can trail new uploads. After a restart only the remembered on/off choice remains, and unknown usage draws no line. @@ -47,11 +51,11 @@ The hosted relay lets one network make **200 new identities in a day**. A networ Pairing has limits on both kinds of relay: 10 new codes in an hour for one network, and a relay holds at most 2,000 waiting pairings. The messages are on the pairing page, for example `too many pairings from this network; wait 7 min` and `sync is full right now; try again in a few minutes`. -## Sync storage is off — approval, retries and chats staying here +## Relay storage is off — approval, retries and chats staying here -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. -**Sync storage is off** (`403`, code `storage_off`). While blind pass-through carries your chats, the notice says `chats move between your computers by blind pass-through while both run codeaf; keys, memories, teams and preferences wait for sync storage (request access in Settings under Devices)`, once while it waits. When blind pass-through is off or unavailable, it says `sync storage is off for this account, so chats stay on this computer; request access in Settings under Devices`. No upload requests are made when this computer knows storage is off. A refresh that sees approval wakes sync automatically. This is separate from every full refusal; reads, pairing and live `--at` still work. Running uploads retry through the local gate on their normal backoff, capped at 60 seconds. One process-wide waiter starts chats waiting for storage within a minute of another process learning approval. Approval discovery runs at launch, after `/status`, and every ten minutes while a relay that reports storage is off (or a hosted address is unknown); serving computers use it too. It stops polling once storage is on. +**Relay storage is off** (`403`, code `storage_off`). While blind pass-through carries your chats, the notice says `chats move between your computers by blind pass-through while both run codeaf; keys, memories, teams and preferences wait for relay storage (request access in Settings under Devices)`, once while it waits. When blind pass-through is off or unavailable, it says `relay storage is off for this account, so chats stay on this computer; request access in Settings under Devices`. No upload requests are made when this computer knows storage is off. A refresh that sees approval wakes sync automatically. This is separate from every full refusal; reads, pairing and live `--at` still work. Running uploads retry through the local gate on their normal backoff, capped at 60 seconds. One process-wide waiter starts chats waiting for storage within a minute of another process learning approval. Approval discovery runs at launch, after `/status`, and every ten minutes while a relay that reports storage is off (or a hosted address is unknown); serving computers use it too. It stops polling once storage is on. ## What do I see when the relay says no @@ -75,7 +79,7 @@ A refused upload leaves the saved turn on this computer. These are the other sen - **Another of your computers stopped this one** (`401`, code `revoked`). The chat says `this device was removed by another of your devices, so this chat stays here only — run codeaf pair to bring it back`. Once removal is known, this computer stops contacting the relay; only a new pairing brings it back. - **The clock is off** (`401`, code `skew`). The chat says `this computer's clock is off by more than 5 minutes`, once. Running sync tries again at each normal turn of sync. If the clock refusal prevented sync from starting, correct the clock and reopen the chat. -Each startup refusal is said once while the chat waits. Running sync says each sentence once for as long as the trouble lasts, and again if the relay answers in between and then refuses again. Running sync retries an unreachable relay with the doubling wait; an unreachable startup is tried again on the chat's next activity. If this computer holds the chat and renewals fail for longer than one renewal period, it says `the sync service at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back` once. A successful renewal or publish then says `this chat is syncing again` once. A displaced or removed computer does not claim that it is syncing again. +Each startup refusal is said once while the chat waits. Running sync says each sentence once for as long as the trouble lasts, and again if the relay answers in between and then refuses again. Running sync retries an unreachable relay with the doubling wait; an unreachable startup is tried again on the chat's next activity. If this computer holds the chat and renewals fail for longer than one renewal period, it says `the relay at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back` once. A successful renewal or publish then says `this chat is syncing again` once. A displaced or removed computer does not claim that it is syncing again. ## Is the hosted relay full for everyone — global admission and storage limits diff --git a/internal/manual/chat/relay-what-it-stores-and-sees.md b/internal/manual/chat/relay-what-it-stores-and-sees.md index f3a315a811..087f37c652 100644 --- a/internal/manual/chat/relay-what-it-stores-and-sees.md +++ b/internal/manual/chat/relay-what-it-stores-and-sees.md @@ -1,24 +1,24 @@ # What the relay stores and what it can see -## Request access to sync storage — turn on sync storage, why don't my chats sync to my other computer +## Request access to relay storage (it used to be called sync storage) — turn on relay storage, turn on sync storage, why don't my chats sync to my other computer -Hosted sync storage is off by default while its privacy terms are being finished. Pairing does not turn it on. Saved keys stay on this computer, and no chat or file content is uploaded; the relay refuses even encrypted uploads. A chat can still move by blind pass-through between your paired computers while both are running codeaf: see *Blind pass-through*. Existing stored frames stay readable and nothing is deleted. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing does not turn it on. Saved keys stay on this computer, and no chat or file content is uploaded; the relay refuses even encrypted uploads. A chat can still move by blind pass-through between your paired computers while both are running codeaf: see *Blind pass-through*. Existing stored frames stay readable and nothing is deleted. Pairing, seeing your devices and `--at` still work while the other computer is on. With storage off, new chat turns cannot be continued on another computer while the first is off (blind pass-through needs both computers on), recovered from the relay after losing a computer, or sent as task copies. Teams sharing, synced provider keys, preferences, shared memories and idle handoff also wait. The relay still keeps device and directory coordination metadata, including existing chat records and leases; storage off does not erase those records. -After pairing, open **Settings → Devices → sync storage** in the terminal and press **enter** (`enter request access`) while it says **off**. In the desktop app, Devices and Advanced → Devices show **Sync storage** and **Request access…**. This opens a pre-filled GitHub issue. GitHub may ask you to sign in before showing the request. The terminal shows a request-code panel only when the browser cannot open; its **Open request on GitHub** link keeps the complete destination behind a short label. The desktop offers **Copy request link** if opening fails, and **Copy request code** while storage is off. +After pairing, open **Settings → Devices → relay storage** in the terminal and press **enter** (`enter request access`) while it says **off**. In the desktop app, Devices and Advanced → Devices show **Relay storage** and **Request access…**. This opens a pre-filled GitHub issue. GitHub may ask you to sign in before showing the request. The terminal shows a request-code panel only when the browser cannot open; its **Open request on GitHub** link keeps the complete destination behind a short label. The desktop offers **Copy request link** if opening fails, and **Copy request code** while storage is off. The request code is your identity id (`id_` followed by 32 hex digits). Approval is tied to this identity id. It is safe to post publicly and grants nothing by itself. The desktop reads this status locally and never contacts the relay merely to show the row. When blind pass-through is available, Devices and the pairing receipt explain that a chat can move while both computers are running. Its request button is offered only for hosted storage; a custom relay's storage permission belongs to its operator. -Turning sync storage off stops new uploads and leaves earlier frames readable. A self-hosted `codeaf relay --store ` keeps storage on and needs no request. Approved hosted accounts still have the limits on *Relay limits and refusals*. +Turning relay storage off stops new uploads and leaves earlier frames readable. A self-hosted `codeaf relay --store ` keeps storage on and needs no request. Approved hosted accounts still have the limits on *Relay limits and refusals*. -## How sync storage permission is discovered — custom addresses, startup and status +## How relay storage permission is discovered — custom addresses, startup and status -The relay's answer decides, whatever its hostname. When it reports storage permission, terminal Settings shows the sync storage row and `/status` shows the dim line `sync storage off` while off. A relay that answers without storage permission, including the self-hosted Go relay and older hosted Workers, keeps storage on and has no terminal row or line. The desktop still shows its effective storage permission. +The server's answer decides, whatever its hostname. When it reports storage permission, terminal Settings shows the relay storage row and `/status` shows the dim line `relay storage off` while off. A relay that answers without storage permission, including the self-hosted Go relay and older hosted Workers, keeps storage on and has no terminal row or line. The desktop still shows its effective storage permission. Before any answer, the three hosted addresses on *Hosted relay or your own relay* start closed; other addresses start open. A paired process probes an unanswered custom address once at startup. A successful answer is remembered for this account and relay, including when the field is absent. Sync off and unpaired homes make no requests. -Eligible serving processes check after their first home-state round; chat windows check at launch and after `/status` in chat, and every ten minutes while a relay that reports storage is off (or a hosted address is still unknown). Storage on or an answer without the field stops requests. Once approval is read, waiting chats and uploads start within a minute without a restart. Opening a chat never waits for a relay reading. A revoked or removed device stops approval polling. +Eligible serving processes check after their first home-state round; chat windows check at launch and after `/status` in chat, and every ten minutes while a relay that reports storage is off (or a hosted address is still unknown). Storage on or an answer without the field stops requests. Once approval is read, waiting chats and uploads start within a minute without a restart. Opening a chat never waits for that reading. A revoked or removed device stops approval polling. Repeated `/status` requests for the same home, identity and relay share a 30-second refresh window. The first request on a new binding is never held behind a previous account's refresh. @@ -26,35 +26,35 @@ Pairing asks for the storage answer alongside its other finishing work, with up Background chat publication waits silently while storage is off. It does not add a contradictory “could not be shared yet; will try again” notice or discard the chat's pending copy. Publication resumes after approval. -## Does the sync service keep my chat when I move it without sync storage — what blind pass-through leaves behind +## Does the relay keep my chat when I move it without relay storage — what blind pass-through leaves behind -While hosted sync storage is off and a chat moves by blind pass-through, the sync service keeps no chat or file content: the encrypted bytes pass through while both of your computers are running codeaf and are never written to the service. Everything stays encrypted end to end. +While hosted relay storage is off and a chat moves by blind pass-through, the relay keeps no chat or file content: the encrypted bytes pass through while both of your computers are running codeaf and are never written to the service. Everything stays encrypted end to end. -The service does hold a small directory record for each such chat, the same kind of thing pairing already stores. *What the sync service records for a chat in blind pass-through* lists every field. The title and the folder name are not among them, so the service holds no chat name and no folder name. WorkAF can read the chat’s title directly from its computer over the same end-to-end encrypted connection. +The service does hold a small directory record for each such chat, the same kind of thing pairing already stores. *What the relay records for a chat in blind pass-through* lists every field. The title and the folder name are not among them, so the service holds no chat name and no folder name. WorkAF can read the chat’s title directly from its computer over the same end-to-end encrypted connection. -`CODEAF_PASSTHROUGH=off` restores the previous behaviour: while storage is off, chats stay on the computer that has them. Blind pass-through does nothing when storage is approved or with a self-hosted sync service. *Blind pass-through* has the steps. +`CODEAF_PASSTHROUGH=off` restores the previous behaviour: while storage is off, chats stay on the computer that has them. Blind pass-through does nothing when storage is approved or with a self-hosted relay. *Blind pass-through* has the steps. -## What the sync service records for a chat in blind pass-through — the fields, the title and folder, the lease, what is never sent +## What the relay records for a chat in blind pass-through — the fields, the title and folder, the lease, what is never sent While blind pass-through is the road, the directory record for a chat holds only: its id; the kind of chat; the chat it was split from, if any; the id of its latest saved turn and when it was saved; the ids of the encrypted chunks that make it up, and their total size in bytes; and the hold on it: which computer has it, the hold's number and expiry, how many saved turns are not yet ready to take, how far getting them ready has got, and whether a turn is running. It also lists your own identity with an empty sealed key: the keys that open a chat never reach the service. **The title and the folder name are never sent**, not even sealed: not when a chat starts, not when it is saved, not for the separate chat a take keeps when you had edits that were never saved, and not by the background pass over older chats, which sends nothing at all while storage is off. The names stay in the chat on your computers; taking the chat is how a name reaches the other one. -Once sync storage is approved the record carries the sealed title and folder name again, as it always has. A self-hosted sync service always did. Message text is never part of this record: see *Why can't I send a message to a chat on another computer*. +Once relay storage is approved the record carries the sealed title and folder name again, as it always has. A self-hosted one always did. Message text is never part of this record: see *Why can't I send a message to a chat on another computer*. -## Why can't I send a message to a chat on another computer — messages wait for sync storage +## Why can't I send a message to a chat on another computer — messages wait for relay storage -A message to a chat that another of your computers holds is left in your computer's own record on the sync service until that computer takes it, sealed with your key. That is keeping your text on the service, so while hosted sync storage is off nothing is sent: the desktop does not offer the message box for such a chat, and a send that arrives anyway is refused with `Sync storage is off for this account, so a message can't wait for another computer. Bring the chat here to write to it.` Continue the chat here instead; blind pass-through moves it while both computers run codeaf. +A message to a chat that another of your computers holds is left in your computer's own record on the relay until that computer takes it, sealed with your key. That is keeping your text on the service, so while hosted relay storage is off nothing is sent: the desktop does not offer the message box for such a *waiting* message, and a send that arrives anyway is refused with `Relay storage is off for this account, so a message can't wait for another computer. Move the chat here to write to it.` Move the chat here instead; blind pass-through moves it while both computers run codeaf. A chat running on an online computer that you opened live (remote control on) is not a waiting message: the words go straight to that computer's running chat, sealed end to end so nothing in between can read them, and nothing is kept on the service, so storage being off does not stop it. *Open a chat running on another computer live in the desktop* has it. -Messages already waiting when storage was switched off can still be taken off the service. A self-hosted sync service and an approved account send messages as before. *Send a message to a chat working on another computer* has the details. +Messages already waiting when storage was switched off can still be taken off the service. A self-hosted relay and an approved account send messages as before. *Send a message to a chat working on another computer* has the details. ## Does the relay store my chats — what is on the relay's disk -The relay holds two things for each identity, kept apart from every other identity: a **directory** (one record for each chat, one for each of your computers) and a **store** of chat content. New content uploads need sync storage, which is off by default until approval (Settings → Devices → sync storage); directory records can remain while storage is off. +The relay holds two things for each identity, kept apart from every other identity: a **directory** (one record for each chat, one for each of your computers) and a **store** of chat content. New content uploads need relay storage, which is off by default until approval (Settings → Devices → relay storage); directory records can remain while storage is off. The content is in the store as **encrypted chunks**. Each chunk is sealed under a key that only your own computers have. The relay cannot open a chunk. It keeps the chunks you send, and your saved keys too: they travel as one more sealed chunk, like a chat. -Two things in the directory are sealed before they leave your computer: **the title of every chat** and **the name of every computer**. The relay stores them as sealed text and cannot read them. While blind pass-through is the road, the title of a chat (and its folder name) is not sent at all: see *What the sync service records for a chat in blind pass-through*. +Two things in the directory are sealed before they leave your computer: **the title of every chat** and **the name of every computer**. The relay stores them as sealed text and cannot read them. While blind pass-through is the road, the title of a chat (and its folder name) is not sent at all: see *What the relay records for a chat in blind pass-through*. There is no email or password sign-in on the relay. Your identity is an id that starts with `id_`, made from your key. @@ -77,6 +77,12 @@ The hosted relay has request logs and traces disabled. Rate counters retain netw The relay can also delete what it holds, or refuse to serve it. Keep a copy you care about on a computer of your own. +## What reaches the relay while a view is direct — setup messages, then nothing, does a STUN server learn anything about my chats + +A live view from another of your computers (*Remote control*) can move onto a direct connection between the two. Finding each other takes a few small messages sealed with your key that pass through the relay. Once the view has moved, none of its traffic goes there: typing, replies and files go straight between the two computers, so they are not in the byte counts or the daily allowance that the server keeps. + +A STUN server is a separate thing (by default Cloudflare's, then Google's). It is asked for this computer's public address and learns only that an app at that address asked; it never sees a chat, a name or a key. `CODEAF_REMOTE_ROAD=relay` asks none and never offers a direct connection. `CODEAF_REMOTE_STUN=off` asks none and still lets two computers on one network connect directly. + ## Does the relay see my code, my prompts or my files Hosted storage is off until approved; no new chat or file chunks are kept while off. With storage on, turns, tool output and files are sealed on your computer before they are sent. The relay gets ciphertext and sizes. diff --git a/internal/manual/chat/remote-control.md b/internal/manual/chat/remote-control.md new file mode 100644 index 0000000000..57d0b6f355 --- /dev/null +++ b/internal/manual/chat/remote-control.md @@ -0,0 +1,165 @@ +# Remote control: working in a chat that keeps running on another of your computers + +## See my chat from my other computer — open it live, drive my desktop from my laptop, remote control, work in a chat without moving it + +Remote control lets this computer open a chat that another of your computers is running, and work in it without moving it. The chat opens **live**. On Home, press `enter` on a row that says `working on tower` or `held on tower`. The chat opens marked `on tower · live`, its box says `Message tower`, and what you see is what tower is doing as it happens. Typing, steering and stopping act on tower, in tower's folder, with tower's files and tools. Nothing moves, and tower's own window keeps working. `/status` adds a row that says how it travels, `live · direct` or `live · relay`. + +Three things have to be true. The two computers are paired. Both are running codeaf, because the other computer has to be there to answer. And remote control is on, on both; it is off until you turn it on (see *Remote control is off*). A chat that no computer is running right now cannot be opened live. Remote control never starts a chat on another computer. For a chat that is not running anywhere, `enter` does what it always did, and moving it here is the only way to carry on. + +## A new chat on my other computer's Home — when it appears, while its first message is still running, working on , why it says untitled + +With remote control on, a chat shows on your other computers' Home as soon as its first turn **starts**, marked `working on `, and `enter` opens it live. Without remote control it appears when that first turn ends, as it always did. A chat nobody has typed in appears nowhere, so an opened and abandoned chat leaves no untitled row. Only the row travels this early: which computer runs the chat and that it is working, with no title, no folder and no words. To make that row the chat is saved once as it stands when the turn starts, which is your first message and no reply. With relay storage off that saved copy stays on the computer running the chat. + +With relay storage off, which is the default, the row never carries the chat's title, so on another computer's terminal Home it reads `untitled` while the first turn runs and after it ends, and after every later turn. The server in between is never given the name of a chat, so the title is not sent. The terminal fills it in from a copy of the chat that computer already holds, and a chat that was started on another computer has none there. WorkAF asks the computer running the chat for the title directly (see *Why a chat shows as untitled on my other computer*). With that storage approved, or a self-hosted server run with `--store`, the row gets its title and its latest state when the turn ends, like any chat. + +If the computer running it stops during that first turn, the row stays as `untitled` until the chat is opened again there. Opening it from another computer asks first. What it can bring is the chat as last saved, at most your first message and no reply, and only with that storage on: with it off, nothing comes while that computer is off. + +## Open it live or move it here — Move here versus remote control, which one does enter do + +Live leaves the chat, its files and its tools on the computer that runs it, and you work from here. **Move here** brings the chat to this computer, so it runs here from then on. + +With remote control on and the other computer online, `enter` on a chat that computer is running opens it live. The `Move this chat here?` card is behind `alt+m` on Home (bring work here), `alt+c` on the resume card and the **Move here** verb of the devices row. A computer that is offline still asks the card, because there is nothing to open live. + +To move a live chat, press `alt+m` inside it. It asks `Move this chat here?`; answer `1`, and the view says `Moving here…` while the chat arrives, then the chat runs on this computer. The other computer's window of that chat becomes a live view of this one. If the move fails, the chat stays where it was, you are back in the live view, and nothing you typed is lost. The older names for moving a chat are answered on the page *Continuing a chat that one of your machines holds*. + +## Home's project after a live view — does opening a chat live change my project, the project shows a folder from my other computer + +A live chat runs in a folder on the other computer, and that folder is not on this one. Inside the live view the chat names it as its own place, but Home does not take it as its project. The `project: ` label above Home's box, the first row of `projects` and the folder the next conversation opens in are the same while a live view is open as they were before you opened it, and the same after you close it. A project you picked with `alt+p`, `/project` or a click stays picked. + +This is only for live views. Opening a chat that runs on this computer, in whatever folder it was started in, still makes that folder Home's project, as it always did. + +## Watch only — what does watch only mean, the box says watch not type + +Each of your computers can be allowed to **watch** a chat that another computer runs, or to watch and **type** into it. A computer that may only watch sees everything live, and its box is replaced by: + +``` +tower lets this computer watch, not type. Change that in /devices there. +``` + +Typing sends nothing and the words you typed stay. The switch is on the computer that runs the chat, not on the one that watches. On that computer open `/devices` (or `/settings` → `Devices`) and move to the other computer's row. It says what that computer may do: `watch and type`, `watch only` or `not shared`. The key line gains `w watch` and `t type`. + +`w` turns watching on or off. Turning it off says `tower can no longer watch chats on this computer.`, closes its open views and turns typing off too, because a computer that cannot watch cannot type. Turning it on says `tower can watch chats on this computer.` `t` turns typing on or off. Turning it off says `tower can watch, not type.` Turning it on asks first: + +``` +let tower type into chats on this computer? y turns it on, any other key keeps it off +``` + +`y` turns it on and says `tower can type into chats on this computer.` Any other key, `esc` included, keeps it off. From a script, `codeaf devices permit "laptop" --drive on`. + +## Home asks whether my other computers may type — older paired computers, let them type, keep them watching + +A computer paired before remote control existed starts watch only, and a computer paired afterward starts with watch and type both on; the pairing screen says so. When you have computers paired earlier, Home asks once: + +``` +Let your other computers type into chats here? +tower can watch your chats here but cannot type yet. +1 let them type 2 keep them watching 3 choose in /devices +``` + +`1` lets them type and `2` keeps them watching. `3` keeps them watching and opens `/devices`, where each computer has its own `w` and `t`. Either answer ends the question for good. `esc` leaves it unanswered, and it comes back the next time Home opens. A computer paired earlier could already move any of your chats, so letting it watch adds no new reach; typing is the new power, which is why it starts off. + +## Direct or relay — does my remote view go through the relay, can my two computers connect directly, how do I see if remote control is direct, why does status say live direct + +A live view starts through the server in between, so the chat appears at once. About half a second later the two computers try to connect straight to each other. If that works, the view moves to the direct road and `/status` has a `road` row that says `live · direct`. If it does not, the view stays where it was and says `live · relay`. Both are normal, and neither prints a banner. Two computers on one network connect directly. + +Moving between the roads loses nothing. Words you typed are sent once, a turn that is running keeps going, and the keyboard stays with the computer that had it. A direct connection that stops working hands the view back to the server in between within 5 seconds when the server in between is reachable, again with no notice. + +Traffic on the direct road does not count toward the daily allowance on *Disconnected after ten minutes idle*, and that allowance never stops a view that is already direct. A view you leave idle for 10 minutes lets go of both roads. + +## Only use the relay — make remote control stay off the direct road, turn off direct connections, what is STUN and does codeaf contact Google, does remote control work on a network that blocks UDP + +A computer behind a network that blocks UDP, and a phone on mobile data, usually cannot connect directly, so their views stay on the server in between, and remote control works the same there. Nothing needs setting. + +While two of your computers connect directly, each learns the other's network address, and a public STUN server (Cloudflare's, then Google's) is asked for this computer's public address. Nothing about your chats goes to a STUN server, and what the server in between carries is still only encrypted bytes. Set `CODEAF_REMOTE_ROAD=relay` to keep every view on the relay and contact no STUN server; it works on either computer. + +`CODEAF_REMOTE_STUN` replaces the two servers with your own, as a comma list of `host:port`, and `off` asks none, which still connects two computers on one network. Turning remote control off turns all of this off. + +## Who has the keyboard — two computers on one chat, take the keyboard, typing from another computer + +Only one computer types into a live chat at a time. The other one shows: + +``` +typing from tower now · enter types here +``` + +That line stands where the box would be, so words already in the box are kept but not drawn, and a view that is not holding the keyboard always says so. When the other computer has not told this one its name, the line reads `typing from the other computer now · enter types here`. + +Press `enter` there to type from this computer instead. That first `enter` only takes the keyboard and sends nothing: the box comes back with any words it held when the other computer took the keyboard, and the next `enter` sends them once. Letters and commands typed while you are not holding the keyboard go nowhere, `/status` included, so press `enter` first and then type. This is the same hand-over two windows of one chat already do; scrolling, copy mode and Home (`space space`) still work while you are not holding the keyboard. + +## The other computer went offline — last seen copy, my words are still in the box, last seen + +When the computer running the chat stops answering, the view says `tower went offline`. It keeps what it last showed and the words in your box, and when tower comes back it picks up where it stopped, with no message missing and none shown twice. It says so within about 10 seconds while a turn is running or you have been using the keys, and within about 15 seconds on a view you are only looking at. + +If tower is not running the chat when you open it, and this computer has seen the chat before, you get the copy this computer kept: + +``` +tower offline · last seen 14:02 +``` + +It is read-only. If you press `enter` on words you typed it sends nothing: `not sent. tower is offline; your words are still in the box`. The copy lives only on this computer, as plain text in your codeaf folder, for the last 200 messages of up to 40 chats. Removing the computer, or moving the chat here, deletes it. Nothing in it was stored on the relay. + +## Does remote control need relay storage — works with relay storage off, can the relay read what I type + +No. Remote control works with relay storage off, while both computers are running codeaf. The server in between passes encrypted bytes between them that it cannot read, or, when the two can reach each other, they connect directly and none of it passes through the server in between. It keeps no copy of your chat text. What it can see while you work is how much encrypted traffic there is, when, and which of your computers are connected; the word *relay* on this page always means that server, as everywhere else in codeaf. + +What does need relay storage is a message for a computer that is **offline**: the desktop app can leave a waiting message for it, and the terminal cannot send anything to an offline computer at all. When the other computer is online, live typing needs no storage. + +## Turn remote control off for a computer — allow watch only, remove a computer, stop my laptop controlling my desktop + +Each computer has its own two switches, kept on the computer that runs the chats and nowhere else. On that computer open `/devices` (or `/settings` → `Devices`), move to the other computer's row and press `w` for watch or `t` for type; the row says `watch and type`, `watch only` or `not shared`. From a script, `codeaf devices permit "laptop" --watch off` or `--drive off`. + +Turning **watch** off, or removing the computer, closes its open views at once. Turning **type** off leaves it watching. Removing a computer closes that device only: a computer you lost still holds your keys, so the remedy for a lost computer is `codeaf identity rotate`, as the page *Lock out a lost computer* says. Remote control is a power you give a paired computer. Turn type off for a computer you only want to look at your chats. + +## What a remote viewer cannot do — answer a question that is waiting on my desktop from my laptop, irreversible questions, remembering a permission, raising approval + +A computer that works in your chat live can do what you can do in a chat you are watching: type, steer, stop work and answer an ordinary question. It cannot answer a question the chat marks as irreversible, ask the computer to remember a permission, or raise how much the chat may do without asking. Those are the other computer's own to answer, and a viewer that tries gets: + +``` +That one needs your OK on tower itself. Answer it there. +``` + +Anything else that would change the other computer's settings or files is refused with `tower does not allow that from another computer.` The question stays open on every screen, and the computer running the chat decides. + +## Disconnected after ten minutes idle — reconnect, daily limit, watch only until midnight + +A live view that you have not touched for 10 minutes, with no turn running, lets go of the connection, and says: + +``` +Disconnected after 10 minutes idle. Enter to reconnect. +``` + +The view stays readable, and `enter` reconnects. Nothing is lost. + +The computer running the chat also keeps a daily allowance of live traffic. When it is used up, every live view stays open and readable but turns watch only, and says `watch only until 00:00 UTC (daily limit)`. Typing works again after midnight UTC. The count survives a restart. + +## Why did my live view end — nobody is running it, watch is off, it ended there, remote control was turned off, too many computers + +The view says why in these words: + +- `tower is not running this chat right now.` Nobody is running it; open it from Home to move it. +- `tower does not share its chats with this computer. Change that in /devices there.` Watch is off for this computer. +- `tower closed this chat.` The chat ended there or was moved. +- `tower changed what this computer may do in its chats.` Reopen the chat to see the new setting. +- `tower turned remote control off.` Remote control was switched off on tower, which ends every live view of its chats. The view stays ended and does not redial. When it is back on, open the chat from Home again. +- `this computer was removed from your devices` The computer must pair again. +- `Restart codeaf on tower to share this chat.` Tower runs an older codeaf; close it there and open it again. +- `tower is closing codeaf.`, `Catching up with tower.`, `One message was too large to show live.` +- `tower has too many computers open on its chats right now. Try again in a minute.` + +## Open on desktop app — Open on a computer in WorkAF, Message the computer in the app + +The desktop app can open a chat another computer is running too. On such a chat it offers **Open on tower**, the strip says it is live, and its box reads `Message tower`. Move here is its other button. This needs a desktop app version that includes remote control; an older one keeps the single Move here button, and nothing in the terminal depends on it. + +## Remote control is off — how to turn it on, do I need to restart codeaf after turning remote control on, remote control says restart codeaf on the other computer + +Remote control is off until you turn it on, on both computers: open `/settings` → `Devices` and turn `remote control` on, or start codeaf with `CODEAF_REMOTE_CONTROL=1`. In the desktop app it is the **Remote control** switch in Settings → Devices (*Turn remote control on or off in the desktop app*). With it off, everything works as before: `enter` on another computer's chat asks to move it, and no computer can open yours live. + +You do not need to restart codeaf in the terminal. Turning it on in a window that is already open takes effect at once, both ways: the next `enter` on a chat another computer is running opens it live, and another computer can open yours. Turning it off does the same at once: `enter` asks to move the chat again and any computer that tries to open a chat of yours is refused, and the live views other computers already have open end within about half a minute. The chats here keep running and keep everything that was typed. + +On the computer that was watching, the view ends with `tower turned remote control off.` and nothing else: it does not say `tower went offline`, it does not start `reconnecting to tower`, and it does not try again by itself, because tower is running and said no. When remote control is back on there, open the chat from Home again. + +Both computers need a codeaf that includes it. If the other one still runs an older codeaf in the background, the view says `Restart codeaf on tower to share this chat.`: close codeaf there and open it again. + +## Remote control versus --at, --host and codeaf serve + +`codeaf chat --at`, `--host` and `codeaf serve` are unchanged and need no pairing: they work on a machine you reach by name, and `--at` may start a chat there. Remote control is different. It is for your own paired computers, it opens only chats they are already running, and it starts none. The page *Reaching this machine without ssh* compares them. diff --git a/internal/manual/chat/running-from-the-terminal.md b/internal/manual/chat/running-from-the-terminal.md index 1921c9ee2b..931a2695b9 100644 --- a/internal/manual/chat/running-from-the-terminal.md +++ b/internal/manual/chat/running-from-the-terminal.md @@ -1,11 +1,11 @@ # Commands you type in a terminal -## codeaf cluster status when the sync service cannot be reached +## codeaf cluster status when the relay cannot be reached If the service cannot be reached, `codeaf cluster status` exits with a failure status and uses the same sentence as `codeaf devices`: -`the sync service at
cannot be reached from here — check this computer's network`. -The address is your configured sync service. Check this computer's network +`the relay at
cannot be reached from here — check this computer's network`. +The address is your configured relay. Check this computer's network and that the service is running, then try the command again. ## Is there a newer version — update codeaf — update a dev build — keep a dev build up to date — latest dev — /update — why does it say this every time I start @@ -806,7 +806,7 @@ be read. A wrong passphrase and a damaged blob get the same refusal. computer you keep: a new root, every chat and your saved keys sealed again under it, and the old identity deleted by the relay after the grace period. It is how a lost computer is locked out for good. It asks first and says what it costs; `--abandon` stops a rotation that has not -switched yet. With hosted sync storage off it still completes, without resealing uploads: chats stay on your computers and the old stored frames wait for grace-period erasure. With storage on, successor proof carries approval unless the new identity already has its own setting. Read *Locking out a lost computer for good*. +switched yet. With hosted relay storage off it still completes, without resealing uploads: chats stay on your computers and the old stored frames wait for grace-period erasure. With storage on, successor proof carries approval unless the new identity already has its own setting. Read *Locking out a lost computer for good*. Each machine also has its own device key, made the first time and never exported. Your identity signs a small certificate for it, so two machines share one id but keep separate @@ -822,10 +822,10 @@ each: id, title, device, where it runs (`working on `, `held on ` turns from : discard`, or `-` for one held here or let go), and how long ago its last saved turn was. It needs no terminal UI, so it works over ssh. Without `--all` it prints the usage line. With sync off (`CODEAF_SYNC_URL=off`, or no relay to sync through) it prints -`sync is off: set CODEAF_SYNC_URL to your sync service's address` and lists nothing. With a relay +`sync is off: set CODEAF_SYNC_URL to your relay's address` and lists nothing. With a relay set but no identity on this machine it prints `this machine has no identity yet: codeaf identity import` and lists nothing, and when the -other machines cannot be reached it starts with `the sync service is not answering`. +other machines cannot be reached it starts with `the relay is not answering`. ## A different sync setting on an existing engine @@ -837,7 +837,7 @@ Only a terminal that sets `CODEAF_SYNC_URL` itself is asking for a different rel ## Sync your chats between machines — what is CODEAF_SYNC_URL, and CODEAF_SYNC_INTERVAL_MS -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. @@ -846,7 +846,7 @@ Older chats move through an independent copy. Once paired, codeaf prepares chats These environment settings are not rows in `/settings`. `CODEAF_SYNC_URL=off` stops relay traffic; new chats still keep their local cells. -## What is CODEAF_SYNC_URL — the sync service address or off +## What is CODEAF_SYNC_URL — the relay address or off **`CODEAF_SYNC_URL`** is the relay's address, like `http://host:8787`, or the word `off`. Plain `http` is for trying it out inside an ssh tunnel; later the relay needs TLS. Unset, it @@ -873,12 +873,12 @@ show your chats on the other machines once both machines share an identity and t ## Why did my tool call not run after I continued the chat on my laptop — closing the chat, the view-only window, kept branch and clock warning -With sync on, the chat you are typing in sends each saved turn to your sync service, and by default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`) holds the chat for this machine while it is open. Closing the chat sends what is left and lets go of it, and with `idle handoff` on in two or more paired machines an idle chat also lets go of its hold about 2 seconds after it goes idle once everything is saved, so another machine can continue it (or with `idle handoff` on open it directly on Home or through `agents.open` with no Continue-here step). New work in the window that released it takes it back in place if nobody else took it; unpaired, sync-off, single-device and default (`idle handoff` off) homes keep their hold while open. If this machine sleeps or loses its connection while still holding the chat, presence stops answering; the other machines mark it offline after 25 seconds of silence, within 30 seconds. The lease itself expires after about ninety seconds (after which another paired machine still asks Continue here, including when the holder was working; a window whose hold merely lapsed admits nothing until you reopen or continue it). +With sync on, the chat you are typing in sends each saved turn to your relay, and by default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`) holds the chat for this machine while it is open. Closing the chat sends what is left and lets go of it, and with `idle handoff` on in two or more paired machines an idle chat also lets go of its hold about 2 seconds after it goes idle once everything is saved, so another machine can continue it (or with `idle handoff` on open it directly on Home or through `agents.open` with no Move-here step). New work in the window that released it takes it back in place if nobody else took it; unpaired, sync-off, single-device and default (`idle handoff` off) homes keep their hold while open. If this machine sleeps or loses its connection while still holding the chat, presence stops answering; the other machines mark it offline after 25 seconds of silence, within 30 seconds. The lease itself expires after about ninety seconds (after which another paired machine still asks Move here, including when the holder was working; a window whose hold merely lapsed admits nothing until you reopen or continue it). You do not have to wait for expiry while a hold is still live: press enter on a chat that says `working on `, `held on ` or ` offline` on another -machine and choose **Move here** / **Continue here**, and it is taken at once (see "Continue a chat here that another +machine and choose **Move here**, and it is taken at once (see "Move a chat here that another machine left" in home). -When another machine does, this window says ` continued this chat. This copy is read-only and may be behind`, +When another machine does, this window says ` moved this chat. This copy is read-only and may be behind`, with the name of the machine that took over (or the first digits of its id when it has no name). From then on this window now only shows it: a tool call the model tries here answers with that same line and does not run, so the two machines never both change the chat. Nothing on the other machine is overwritten. @@ -903,7 +903,7 @@ Each time a conversation is synced to another machine, codeaf adds one line of c machine, `v3/sync/stats/.jsonl` in the codeaf home: how many turns, frames and objects that flush carried, how many bytes went up and came down, and how many put, get and has requests it made. Requests that no flush carries are counted too, in a line with a dash for its turn: what it cost to fetch a conversation -when you continue it here, and what a publish that failed had already sent. Sending your secrets along with +when you move it here, and what a publish that failed had already sent. Sending your secrets along with a conversation is counted apart, in `v3/sync/stats/vault.jsonl`, because it serves every conversation. A line holds counts only: no time, no file names, no titles and no content. The file never leaves the machine on its own. diff --git a/internal/manual/chat/running-on-another-machine.md b/internal/manual/chat/running-on-another-machine.md index 497e50bfc9..b03001e0ca 100644 --- a/internal/manual/chat/running-on-another-machine.md +++ b/internal/manual/chat/running-on-another-machine.md @@ -307,7 +307,7 @@ purpose, and says `this window is reading this conversation, not typing into it` ## How do I work on the same conversation from two computers — open multiple terminals and have things just transfer -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. diff --git a/internal/manual/chat/sessions-and-rewind.md b/internal/manual/chat/sessions-and-rewind.md index d2a45fb339..f6d6fa48ae 100644 --- a/internal/manual/chat/sessions-and-rewind.md +++ b/internal/manual/chat/sessions-and-rewind.md @@ -1078,11 +1078,11 @@ Tools keep working and the conversation still saves normally. Reopening the chat does not repeat the sentence. Restart codeaf to try saving file history again. Ordinary project chats with a usable saving connection keep their history. -## Closing one open chat while sync storage is off +## Closing one open chat while relay storage is off -Closing a chat with `/quit` or its close action can leave your other chats open. After a successful local save with sync storage off, codeaf says `saved here; sync storage is off for this account, so it stays on this computer`. On desktop quit the engine log keeps that receipt. +Closing a chat with `/quit` or its close action can leave your other chats open. After a successful local save with relay storage off, codeaf says `saved here; relay storage is off for this account, so it stays on this computer`. On desktop quit the engine log keeps that receipt. -When local saving succeeds but another upload is still pending, the sentence is `saved here; it reaches your other devices when the sync service at
answers`. It names the service used by the chat you closed. +When local saving succeeds but another upload is still pending, the sentence is `saved here; it reaches your other devices when the relay at
answers`. It names the service used by the chat you closed. If saving here fails, closing one chat still says `this chat could not be saved; its unsaved turns stay on this computer for the next start`. An unanswered save remains finishing in the background until its result arrives. Storage being off alone does not mean the local save failed. diff --git a/internal/manual/chat/settings.md b/internal/manual/chat/settings.md index d28683b1de..a1e6f09cfd 100644 --- a/internal/manual/chat/settings.md +++ b/internal/manual/chat/settings.md @@ -82,7 +82,7 @@ positive: on shows contextual tips, off hides them. Keyboard instructions and setting explanations stay visible either way. **Completed tool details** offers **collapsed** or **expanded** without changing the meaning of an existing profile. -**Settings → General → share teams** is on by default for paired computers. On the hosted sync service sharing needs sync storage approval (Settings → Devices → sync storage). It +**Settings → General → share teams** is on by default for paired computers. On the hosted relay sharing needs relay storage approval (Settings → Devices → relay storage). It shares teams, their members and settings, and recent Traffic as read-only history. The choice stays on each computer. Turning it off on either computer stops sharing between them: that computer stops sending and receiving teams and Traffic. What @@ -91,7 +91,7 @@ history is hidden while sharing is off and is kept for when it is turned back on. Unpaired computers are unaffected. A missing or empty choice reads on; a damaged configuration or invalid value reads off, as shown in Settings. -**Settings → General → idle handoff** (`idle_handoff`, environment `CODEAF_IDLE_HANDOFF`) is **off by default**. While off, open idle chats keep renewing their hold and released remote chats use **Continue here**. Turn it on in Settings or with `CODEAF_IDLE_HANDOFF=1` so paired idle chats release their hold about 2 seconds after upload and released shared chats open directly on Home and through `agents.open` (`can_open`). +**Settings → General → idle handoff** (`idle_handoff`, environment `CODEAF_IDLE_HANDOFF`) is **off by default**. While off, open idle chats keep renewing their hold and released remote chats use **Move here**. Turn it on in Settings or with `CODEAF_IDLE_HANDOFF=1` so paired idle chats release their hold about 2 seconds after upload and released shared chats open directly on Home and through `agents.open` (`can_open`). ## AI teams settings versus an individual AI team @@ -247,11 +247,13 @@ malformed JSON still reports an error. Spending-limit reads and settings writes continue to refuse unreadable files unless an explicit daily-limit override supplies the spending authority. -## Devices — sync storage, off or on, and request access +## Devices — relay storage (it used to be called sync storage), off or on, and request access -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. -A paired account whose service reports storage permission has a **sync storage** row showing **on** or **off**. While **off**, press Enter (`enter request access`) to open a pre-filled GitHub issue. The panel also shows the public request code and link if no browser opens. The code is your identity id (`id_` and 32 hex digits), safe to post and granting nothing by itself. Choosing this row in Settings search clears the search and opens Devices. While **off**, Enter also requests access. While **on**, it opens Devices without offering or making a request. The row is absent with sync off, before pairing, or when the service answers without storage permission. A window already open when you pair checks for the answer within about a minute; an open Settings page then updates its row automatically. The first `/status` after pairing shows the cached dim line `sync storage off` while storage is off. +A paired account whose service reports storage permission has a **relay storage** row showing **on** or **off**. While **off**, press Enter (`enter request access`) to open a pre-filled GitHub issue. The panel also shows the public request code and link if no browser opens. The code is your identity id (`id_` and 32 hex digits), safe to post and granting nothing by itself. Choosing this row in Settings search clears the search and opens Devices. While **off**, Enter also requests access. While **on**, it opens Devices without offering or making a request. The row is absent with sync off, before pairing, or when the service answers without storage permission. A window already open when you pair checks for the answer within about a minute; an open Settings page then updates its row automatically. The first `/status` after pairing shows the cached dim line `relay storage off` while storage is off. + +**Settings → Devices → remote control** (`remote_control`, environment `CODEAF_REMOTE_CONTROL`) stands below the computers and the add row, and is **off by default**. It lets another computer of yours open this computer's running chats and, if you allow it, type into them; Enter turns it on or off, and it applies at once. `CODEAF_REMOTE_CONTROL=1` turns it on for a launch and wins over the row. The row appears once the computer list has loaded and is absent when devices cannot work here. The page *Remote control* has the rest. ## Why Settings says held by an environment variable diff --git a/internal/manual/chat/starting-codeaf.md b/internal/manual/chat/starting-codeaf.md index 99e1ec0f9f..516da14416 100644 --- a/internal/manual/chat/starting-codeaf.md +++ b/internal/manual/chat/starting-codeaf.md @@ -839,13 +839,13 @@ reaches a conversation when you next open it or switch models; `OPENROUTER_API_KEY` still wins. `your key was not accepted for this model` means the provider refused the key; doctor helps find the source to replace. -## Chats on another computer and hosted sync storage +## Chats on another computer and hosted relay storage -Pairing and live `--at` access work while hosted sync storage is off. Hosted storage is off by default while its privacy terms are being finished, so chats are not stored on the sync service until approval; they still move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). After pairing, request access in Settings → Devices → sync storage → enter. The panel shows the public request code and link as well as opening a browser. Sync starts by itself after a background reading sees approval; `/status` refreshes it without holding up the chat. A self-hosted `codeaf relay --store ` needs no request. +Pairing and live `--at` access work while hosted relay storage is off. Hosted storage is off by default while its privacy terms are being finished, so chats are not stored on the relay until approval; they still move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). After pairing, request access in Settings → Devices → relay storage → enter. The panel shows the public request code and link as well as opening a browser. Sync starts by itself after a background reading sees approval; `/status` refreshes it without holding up the chat. A self-hosted `codeaf relay --store ` needs no request. -## Sync storage is off — a notice in an open chat +## Relay storage is off — a notice in an open chat -A paired account with storage off sees one of two notices once when a chat first tries to sync. While blind pass-through carries your chats it says `chats move between your computers by blind pass-through while both run codeaf; keys, memories, teams and preferences wait for sync storage (request access in Settings under Devices)`, because the chats are not stuck and only what needs the sync service's storage waits. When blind pass-through is off or unavailable (see *Turn off blind pass-through*), it says `sync storage is off for this account, so chats stay on this computer; request access in Settings under Devices`. If access is withdrawn after syncing starts, the chat shows it once again. This appears in the window showing the chat, including an already-open window. Your chats keep saving on this computer. +A paired account with storage off sees one of two notices once when a chat first tries to sync. While blind pass-through carries your chats it says `chats move between your computers by blind pass-through while both run codeaf; keys, memories, teams and preferences wait for relay storage (request access in Settings under Devices)`, because the chats are not stuck and only what needs the relay's storage waits. When blind pass-through is off or unavailable (see *Turn off blind pass-through*), it says `relay storage is off for this account, so chats stay on this computer; request access in Settings under Devices`. If access is withdrawn after syncing starts, the chat shows it once again. This appears in the window showing the chat, including an already-open window. Your chats keep saving on this computer. ## Starting after an upgrade — standing orders and rules from an earlier version diff --git a/internal/manual/chat/tasks-on-another-computer.md b/internal/manual/chat/tasks-on-another-computer.md index 77e44e6977..71f0d880e6 100644 --- a/internal/manual/chat/tasks-on-another-computer.md +++ b/internal/manual/chat/tasks-on-another-computer.md @@ -2,7 +2,7 @@ ## Can a task run on my other computer -On the hosted sync service this needs sync storage approval (Settings → Devices → sync storage). +On the hosted relay this needs relay storage approval (Settings → Devices → relay storage). Yes. Pair both computers with the same identity and run `codeaf serve --take-tasks` on the computer that will do the task. Both ends need Linux or macOS; Windows cannot @@ -31,7 +31,7 @@ same calls again; new calls from the other computer are added once. ## Run a task on my mac mini -On the hosted sync service this needs sync storage approval (Settings → Devices → sync storage). +On the hosted relay this needs relay storage approval (Settings → Devices → relay storage). Pair your Mac mini and this computer, then run `codeaf serve --take-tasks` on the mini. Use its shown name, quoting names that contain spaces: @@ -148,7 +148,7 @@ setting names another computer, without a special placement sentence. ## codeaf serve --take-tasks takes tasks from paired computers -On the hosted sync service this needs sync storage approval (Settings → Devices → sync storage). +On the hosted relay this needs relay storage approval (Settings → Devices → relay storage). Plain `codeaf serve` opens only the machine connection and does not take tasks. Run `codeaf serve --take-tasks` on the paired computer that should take tasks. It prints @@ -213,9 +213,9 @@ requires updating both ends before retrying. ## The task copy could not be sent -Task copies wait for hosted sync storage approval (Settings → Devices → sync storage); chats can still move by blind pass-through, but a task copy is sent through that storage. A self-hosted sync service with `--store` needs no request. +Task copies wait for hosted relay storage approval (Settings → Devices → relay storage); chats can still move by blind pass-through, but a task copy is sent through that storage. A self-hosted relay with `--store` needs no request. -While storage is off, sending or taking a task copy is refused on this computer before anything is sealed or asked of the sync service: it makes no request to the service's store at all, not even the question of whether an object is already there. The refusal is the same storage-off sentence as before. +While storage is off, sending or taking a task copy is refused on this computer before anything is sealed or asked of the server: it makes no request to the server's store at all, not even the question of whether an object is already there. The refusal is the same storage-off sentence as before. `the task copy changed while it was being sent; try again` keeps the copy here. Finish or pause the edits, then retry the task. diff --git a/internal/manual/chat/team-manager.md b/internal/manual/chat/team-manager.md index 417f3412b5..5862a91fc1 100644 --- a/internal/manual/chat/team-manager.md +++ b/internal/manual/chat/team-manager.md @@ -609,7 +609,7 @@ while it was closed. ## Team sharing and Traffic on another computer -Hosted sync storage approval is required for team sharing; storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: teams, shared team settings and Traffic wait. Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. +Hosted relay storage approval is required for team sharing; storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: teams, shared team settings and Traffic wait. Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. The traffic itself is kept in the profile of the machine the conversations run on, in `teams//traffic.jsonl`, one line per message, only ever added to. It holds only @@ -623,7 +623,7 @@ Once both computers share teams, Traffic also shows recent history from the othe computer, kept beside it in `teams//elsewhere.jsonl`. That history cannot deliver a message, start, stop, answer or wake a chat here. A message to a member or manager known to be on another computer is refused before writing; -continue that chat here from Home first, then send again. A room post or send to +move that chat here from Home first, then send again. A room post or send to several members reaches local recipients and names those not reached. If all recipients are elsewhere, nothing is written. An unavailable relay does not block local delivery. Decisions and escalations also check their recipients @@ -670,7 +670,7 @@ Review manager choices in Teams. ## Shared team spending caps and continued members -On the hosted sync service this needs sync storage approval (Settings → Devices → sync storage). +On the hosted relay this needs relay storage approval (Settings → Devices → relay storage). Teams and their settings share automatically between paired computers by default; an unpaired computer is unaffected. A shared team's spending cap counts spending diff --git a/internal/manual/chat/use-this-on-another-computer.md b/internal/manual/chat/use-this-on-another-computer.md index 05af49bde7..6d0dba6658 100644 --- a/internal/manual/chat/use-this-on-another-computer.md +++ b/internal/manual/chat/use-this-on-another-computer.md @@ -2,7 +2,7 @@ ## How do I use this on my laptop — pair a second computer with a code, connect another computer, and log in on a new machine -While hosted sync storage is off, a chat still moves by blind pass-through between your paired computers when both are running codeaf; see *Blind pass-through*. +While hosted relay storage is off, a chat still moves by blind pass-through between your paired computers when both are running codeaf; see *Blind pass-through*. Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. @@ -12,7 +12,7 @@ There is no account and no password to log in with. You pair: a code on one scre Use a code shown on a screen you own. -The computer that has your chats shows the code. The other computer types it. After that, both computers share the identity; chats copy between them when sync storage is on, and move by blind pass-through while both computers are running codeaf when it is off (*Blind pass-through*). +The computer that has your chats shows the code. The other computer types it. After that, both computers share the identity; chats copy between them when relay storage is on, and move by blind pass-through while both computers are running codeaf when it is off (*Blind pass-through*). This page is the code way. A new computer can also ask to join and be approved from a link, with a four-digit check: the page *Adding a computer to your devices, approving it, and removing it* tells it. @@ -37,7 +37,7 @@ The code is good for 10 minutes. It works once. ## Share my conversation with my other computer Pair the computers with `/pair` or `codeaf pair`. A computer with submitted -chats requires `--replace`. By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), **Continue here** moves a conversation to the other computer. With `idle handoff` on, an idle chat lets go about 2 seconds after going idle once saved to the sync service, and an explicitly released chat opens directly on the other computer (Enter on terminal Home, or `agents.open` on `can_open` rows in the app) with no Continue-here step; **Move here** or **Continue here** moves one another computer still holds or whose hold merely lapsed, including when its holder was working. +chats requires `--replace`. By default (`idle handoff` is off by default; turn it on in **Settings → General → idle handoff** or with `CODEAF_IDLE_HANDOFF=1`), **Move here** moves a conversation to the other computer. With `idle handoff` on, an idle chat lets go about 2 seconds after going idle once saved to the relay, and an explicitly released chat opens directly on the other computer (Enter on terminal Home, or `agents.open` on `can_open` rows in the app) with no Move-here step; **Move here** moves one another computer still holds or whose hold merely lapsed, including when its holder was working. ## Sync my chats — get my chats on my other computer, how to sync between paired computers @@ -50,9 +50,9 @@ Older chats become movable through independent copies after pairing; their origi ## My idle chat was continued on another computer — sending, queueing, steering and retrying -Before accepting new work, an open synced chat checks who holds it if its last confirmation is older than 2 seconds (back-to-back sends reuse it). The read waits at most 750 ms; sending cancels idle handoff preparation immediately without extending that deadline, and tasks recheck after slow preparation. If the sync service is unreachable, a window that still holds its chat keeps working locally and waits 30 seconds before asking again; a released window must confirm ownership first or leave your work unsent. +Before accepting new work, an open synced chat checks who holds it if its last confirmation is older than 2 seconds (back-to-back sends reuse it). The read waits at most 750 ms; sending cancels idle handoff preparation immediately without extending that deadline, and tasks recheck after slow preparation. If the relay is unreachable, a window that still holds its chat keeps working locally and waits 30 seconds before asking again; a released window must confirm ownership first or leave your work unsent. -By default (**Settings → General → idle handoff** is off), open idle chats keep renewing their hold and a released remote chat asks **Continue here**. When you turn **idle handoff** on in `/settings` or with `CODEAF_IDLE_HANDOFF=1` with two or more paired computers, an idle chat lets go about 2 seconds after going idle once its journal, working files, shared memory and settings are on the sync service (excluding rebuildable folders). Its window stays open as a reader; running turns, queued or steering work, tasks, jobs, unsaved writes and failed uploads keep the hold. With `idle handoff` on, a released chat opens directly on another paired computer with no Continue-here step (Enter on terminal Home, or `agents.open` on `can_open` rows); a live hold or a lapsed hold on another computer asks with **Move here** or **Continue here**. New work in the window that released its own idle hold takes the unchanged chat back in place with no prompt, keeping local install folders without a setup card; a newer saved head or a hold that merely lapsed admits nothing until you open or continue it. +By default (**Settings → General → idle handoff** is off), open idle chats keep renewing their hold and a released remote chat asks **Move here**. When you turn **idle handoff** on in `/settings` or with `CODEAF_IDLE_HANDOFF=1` with two or more paired computers, an idle chat lets go about 2 seconds after going idle once its journal, working files, shared memory and settings are on the relay (excluding rebuildable folders). Its window stays open as a reader; running turns, queued or steering work, tasks, jobs, unsaved writes and failed uploads keep the hold. With `idle handoff` on, a released chat opens directly on another paired computer with no Move-here step (Enter on terminal Home, or `agents.open` on `can_open` rows); a live hold or a lapsed hold on another computer asks with **Move here**. New work in the window that released its own idle hold takes the unchanged chat back in place with no prompt, keeping local install folders without a setup card; a newer saved head or a hold that merely lapsed admits nothing until you open or continue it. If another computer continued the chat, this window only shows it: sending, queueing, steering and retrying refuse before saving words or calling a model, naming that computer, while existing questions and stop still work. Sync-off, unpaired, single-computer and default (`idle handoff` off) homes keep their hold while open. @@ -107,7 +107,7 @@ Nothing is sent. The code is gone. If you were not at the screen, run `/pair` ag When you answer `y`, the computer that has your chats says: ``` -laptop is now paired. Your chats can continue there. +laptop is now paired. laptop can also see and control your chats here. Change that in /devices. ``` and the other computer says: @@ -201,7 +201,7 @@ too many pairings from this network; wait 7 min Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. -**Pairing gives the other computer your whole identity.** Your chats, your saved keys and your sync are all part of it. The other computer receives the identity keys; vault content such as saved keys still needs enabled sync storage to copy; chats, with their `.env` and other secret files, move by blind pass-through while both computers are running codeaf even when it is off. +**Pairing gives the other computer your whole identity.** Your chats, your saved keys and your sync are all part of it. The other computer receives the identity keys; vault content such as saved keys still needs enabled relay storage to copy; chats, with their `.env` and other secret files, move by blind pass-through while both computers are running codeaf even when it is off. It is not a view of your chats. It is a copy of you. Pair only a computer you own and trust. @@ -321,7 +321,7 @@ writes made after the replacement was installed. ## I got a new laptop — move my chats to a new machine -While hosted sync storage is off, a chat still moves by blind pass-through between your paired computers when both are running codeaf; see *Blind pass-through*. +While hosted relay storage is off, a chat still moves by blind pass-through between your paired computers when both are running codeaf; see *Blind pass-through*. Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. @@ -404,18 +404,18 @@ The first-run line about the hosted relay is said once, when chats are first cop Moving chats and pairing are available by default on Linux, macOS and native Windows on every build with a compatible engine. Pair both computers first. -Your chats live on your own computer first. When sync storage is enabled they are also copied, sealed, +Your chats live on your own computer first. When relay storage is enabled they are also copied, sealed, to the relay, so your other computers can open them. While hosted storage is off, a chat can still move by blind pass-through, sealed, from the computer that has it to the one taking it while both are running codeaf, and nothing is stored. Which relay is one setting, `CODEAF_SYNC_URL`, and there is no sign-in and no account: - **Unset** uses this build's channel relay when it has one — `https://codeaf.agentfield.ai/fabric` on stable releases and release candidates, `https://caf-fabric-staging.instrument-santosh.workers.dev` on staging builds, and `https://caf-fabric-dev.instrument-santosh.workers.dev` on dev builds and local builds from source — and says so once, in one line, the first time your chats are copied: `Your chats sync end-to-end encrypted through - codeaf's fabric (
), a sync service that only ever sees ciphertext; turn that off with + codeaf's fabric (
), a relay that only ever sees ciphertext; turn that off with CODEAF_SYNC_URL=off, or use your own with CODEAF_SYNC_URL=.` Channels do not sync with each other. A computer you paired with another one uses the relay that pairing saved instead. A build with no hosted relay has no default, and nothing is copied until you name a relay. - **`CODEAF_SYNC_URL=off`** turns the copying off. Nothing leaves the computer, and `codeaf pair` - says `sync is off (CODEAF_SYNC_URL=off); pairing needs the sync service`. + says `sync is off (CODEAF_SYNC_URL=off); pairing needs the relay`. - **`CODEAF_SYNC_URL=https://relay.example.com`** is your own relay. You run it with `codeaf relay --listen :8787 --store ` (see "Running the relay yourself" on the page *Reaching a machine with a pairing code*). The hosted relay and your own speak the same way, so @@ -440,7 +440,7 @@ What the relay does see is short: the number at the start of the code, the time, Pairing goes through the relay this computer syncs through. The first that answers wins: the one `CODEAF_SYNC_URL` names, else the one an earlier pairing saved, else this channel's hosted relay (`https://codeaf.agentfield.ai/fabric` on stable releases and release candidates, `https://caf-fabric-staging.instrument-santosh.workers.dev` on staging builds, or `https://caf-fabric-dev.instrument-santosh.workers.dev` on dev and local source builds) when this build has one. Channels do not sync with each other, so both computers must run the same channel or point `CODEAF_SYNC_URL` at the same relay. A build with no hosted relay has no default, so there you must name one: set `CODEAF_SYNC_URL` to the address of a relay, or pass it in the command. With no relay at all, `/pair` and `codeaf pair` say: ``` -no sync service is set, so there is nowhere to pair through: set CODEAF_SYNC_URL to its address, or pass --via
+no relay is set, so there is nowhere to pair through: set CODEAF_SYNC_URL to its address, or pass --via
``` ## Pair through your own relay, or stop relay traffic with CODEAF_SYNC_URL=off @@ -463,7 +463,7 @@ After the pairing, the other computer saves that relay and syncs through it; whe `CODEAF_SYNC_URL=off` turns sync off. Then pairing is not available. Both commands say so before they send anything: ``` -sync is off (CODEAF_SYNC_URL=off); pairing needs the sync service +sync is off (CODEAF_SYNC_URL=off); pairing needs the relay ``` ## The pairing relay does not answer, is full or is too old @@ -475,7 +475,7 @@ Other things the relay can say while you pair: The relay cannot be reached. The name is the host you used: ``` -nothing is answering at https://relay.example.com — if that is your own sync service, start it there with codeaf relay +nothing is answering at https://relay.example.com — if that is your own relay, start it there with codeaf relay ``` The relay is full. Try again in a few minutes: @@ -487,15 +487,15 @@ sync is full right now; try again in a few minutes The relay is an old one that does not know pairing: ``` -that sync service is too old for pairing +that relay is too old for pairing ``` -## Pairing timed out — the sync service did not answer in time +## Pairing timed out — the relay did not answer in time A request that runs out of time does not diagnose a network fault. It says: ``` -the sync service at https://relay.example.com did not answer in time — try again +the relay at https://relay.example.com did not answer in time — try again ``` The address is the service you used. Try pairing again; a busy service or disk @@ -527,7 +527,7 @@ Moving chats and pairing are available by default on Linux, macOS and native Win Older chats move through independent copies after pairing. Their original files and layout remain untouched for older builds. Nothing is deleted automatically to save disk. Native Windows moves chats with the native engine, just like Linux and macOS. -Continue here (or opening a free paired chat directly when `idle handoff` is on) installs the saved chat while other chats stay open. You can send +Move here (or opening a free paired chat directly when `idle handoff` is on) installs the saved chat while other chats stay open. You can send from the installed copy and open or continue it back on your other computer. Install Git for Windows to run commands; codeaf uses Git Bash, never the WSL launcher. A build with no compatible engine keeps moving chats absent and says @@ -569,9 +569,9 @@ A PEM certificate bundle containing only `BEGIN CERTIFICATE` blocks is kept in s A removed computer keeps working locally in a new chat and in a chat it held when it was removed. Those turns stay on this computer and do not sync. A chat another computer had already taken stays unsent here. Removal offers no way to take that chat back; pair the computer again to bring syncing back. -## Why does codeaf devices fail when the sync service is down +## Why does codeaf devices fail when the relay is down -If your devices cannot be listed, `codeaf devices` exits with an error explaining that the sync service cannot be reached. It does not say nothing is paired when the listing is unavailable. A connection that times out says the service did not answer in time. +If your devices cannot be listed, `codeaf devices` exits with an error explaining that the relay cannot be reached. It does not say nothing is paired when the listing is unavailable. A connection that times out says the service did not answer in time. ## Pairing fallback names and other local work @@ -585,7 +585,7 @@ If a computer with its own saved pairing keys has local work codeaf cannot count The chat’s `/pair` card also accepts the link shown on a new computer. It says `paste the link the new device shows, or on it run codeaf pair 43-209-648` and shows a `> Paste pairing link` field. The command carries `--via` for your own -sync service. Paste the link and press Enter to see the check number and approve +relay. Paste the link and press Enter to see the check number and approve with `a` or decline with `d`. A link for a different service is refused before lookup. Settings → Devices → Add another device opens this same card. @@ -604,6 +604,6 @@ If this computer has no saved pairing keys yet — for example it has only ever A computer that already has its own saved pairing keys follows the local-work refusal and explicit `--replace` rules above. -## Why pairing alone does not copy saved chats — sync storage access +## Why pairing alone does not copy saved chats — relay storage access -Hosted sync storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence and live `--at` still work. After pairing, press enter on **Settings → Devices → sync storage** to ask for approval. A self-hosted sync service with `--store` needs no request. +Hosted relay storage is off by default while its privacy terms are being finished. Pairing alone does not enable it: saved keys, preferences, shared memories, teams, idle handoff and task copies wait. Chats and their files do not wait: they move by blind pass-through between your paired computers while both are running codeaf (*Blind pass-through*). Pairing, device presence, remote control (once it is turned on) and live `--at` still work. After pairing, press enter on **Settings → Devices → relay storage** to ask for approval. A self-hosted relay with `--store` needs no request. diff --git a/internal/manual/chat/what-i-can-do.md b/internal/manual/chat/what-i-can-do.md index 2f156b3a41..5358c75844 100644 --- a/internal/manual/chat/what-i-can-do.md +++ b/internal/manual/chat/what-i-can-do.md @@ -18,7 +18,8 @@ not a hard word limit; the wording and length can vary with the model and the ta ## Is this only for programming — is codeaf only for code, or for any kind of work? -Not only programming. Nothing else on this page is about code in particular: +Not only programming. codeaf is not only a programming tool or only for writing software, and +nothing else on this page is about code in particular: files, shell commands, the web, pictures, audio and video, your connected accounts, your own settings. A folder of contracts, a pile of recordings to transcribe and a repository are the same material to codeaf — whatever is in the diff --git a/internal/manual/chat/what-i-remember.md b/internal/manual/chat/what-i-remember.md index 5986956162..7a1b6ee27a 100644 --- a/internal/manual/chat/what-i-remember.md +++ b/internal/manual/chat/what-i-remember.md @@ -661,7 +661,7 @@ one line on a failed row is the whole of what it says. ## Are my memories shared across computers? Does /remember work on my other computer — hand edited memories follow my paired computers, memory missing on the new laptop -Shared memories wait for hosted sync storage approval (Settings → Devices → sync storage). A self-hosted sync service with `--store` needs no request. A chat's own memory history moves with the chat. +Shared memories wait for hosted relay storage approval (Settings → Devices → relay storage). A self-hosted relay with `--store` needs no request. A chat's own memory history moves with the chat. Person and project memory follow your paired computers through the encrypted vault within one sync round, including hand-edited lines in the Memory place and lines written by older chats. No chat needs to be continued first. Concurrent edits of different lines both survive; for the same line the later edit wins, including forgetting a line. The service receives ciphertext only. @@ -669,7 +669,7 @@ Machine-scoped memories describe one computer and stay there. An unpaired home s ## Memory in older local conversations and new moving chats -On the hosted sync service, the memory that syncs through the encrypted vault waits for sync storage approval (Settings → Devices → sync storage); a chat's own memory history moves with the chat. +On the hosted relay, the memory that syncs through the encrypted vault waits for relay storage approval (Settings → Devices → relay storage); a chat's own memory history moves with the chat. Memories use the local store on each computer. After pairing, an older conversation gets an independent movable copy with its earlier memory history sealed into `.cell/memories.jsonl`; the original is untouched. Person and project memory also sync independently through the encrypted vault. diff --git a/internal/manual/chat/when-the-connection-drops.md b/internal/manual/chat/when-the-connection-drops.md index f424ac4592..524558bcb8 100644 --- a/internal/manual/chat/when-the-connection-drops.md +++ b/internal/manual/chat/when-the-connection-drops.md @@ -55,6 +55,10 @@ are on the machine you are sitting at, so they are never at risk. And the conver journaled on the far machine as it happens — the far machine is the only thing that writes that file — so nothing that reached it is lost either way. +## My live view of a chat on another computer lost its connection — the direct road stopped, no notice + +A chat opened live from another of your computers (*Remote control*) can travel straight between the two computers. When that direct connection stops working, the view goes back to the relay within 5 seconds when the relay is reachable, and `/status` changes from `live · direct` to `live · relay`. Nothing is printed on the screen. The words you typed are kept and sent once, a reply that is still running keeps arriving, and whoever had the keyboard keeps it. If the relay cannot be reached either, the view says `tower went offline`, keeps what it last showed and your words, and picks up where it stopped when the connection returns. + ## The reply stopped halfway through If the model connection ends before the model reports a finish reason or sends its `[DONE]` diff --git a/internal/manual/chat/worker-harness.md b/internal/manual/chat/worker-harness.md index 2c0ca5fc4c..f5de4aac26 100644 --- a/internal/manual/chat/worker-harness.md +++ b/internal/manual/chat/worker-harness.md @@ -1180,7 +1180,7 @@ checkpoint writes; it does not change legacy task placement or rewrite history. ## Open a task that finished on another computer A task that finished on another computer is still available in Tasks after you -continue its chat here. Open it to read its title, saved description when present, +move its chat here. Open it to read its title, saved description when present, recorded steps and worker transcript. The historical page is read-only: finished work cannot be restarted, retried or resumed from that page. The original computer keeps its existing task page. diff --git a/internal/manual/chat_test.go b/internal/manual/chat_test.go index b213657dc8..c66d6f93fa 100644 --- a/internal/manual/chat_test.go +++ b/internal/manual/chat_test.go @@ -241,6 +241,9 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { {"queue a message for my other computer while its turn is working", "desktop-sync"}, {"my message to the other computer was never delivered because it is offline", "desktop-sync"}, {"message to my other computer didn't send, can't reach relay", "desktop-sync"}, + {"can my laptop watch or type into a chat that is running on my desktop", "desktop-sync"}, + {"does someone watching my chat from another computer stop it being closed when it goes idle", "desktop-sync"}, + {"I closed a chat on this desktop and my other computer says it closed", "desktop-sync"}, {"my crew from the other computer shows as loose chats in the desktop", "desktop-sync"}, {"can I continue a crew made on another computer here", "desktop-sync"}, // C9: Windows shell questions must reach the self-contained Git Bash section. @@ -3956,6 +3959,50 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { {"does the sync service see my chat title or folder name when I move a chat without sync storage", "relay-what-it-stores-and-sees"}, {"why can't I message a chat on another computer while sync storage is off", "desktop-sync"}, {"Sync storage is off for this account, so a message can't wait for another computer", "desktop-sync"}, + // Remote control (internal/manual/chat/remote-control.md): working in a chat + // another of the person's computers is running, without moving it. + {"how do I see my chat from my other computer", "remote-control"}, + {"can I drive a chat on my desktop from my laptop without moving it", "remote-control"}, + {"open a chat that is running on another computer live", "remote-control"}, + {"why can't I type in a chat that is running on my other computer", "remote-control"}, + {"what does watch only mean", "remote-control"}, + {"who has the keyboard when two computers have the same chat open", "remote-control"}, + {"my desktop went offline while I was looking at its chat", "remote-control"}, + {"my live view says my desktop turned remote control off", "remote-control"}, + {"does remote control work when relay storage is off", "remote-control"}, + {"how do I stop my laptop from controlling my desktop's chats", "remote-control"}, + {"can the relay read what I type on my other computer", "remote-control"}, + {"why was I disconnected after ten minutes", "remote-control"}, + {"it says daily limit and watch only", "remote-control"}, + {"how do I turn remote control on", "remote-control"}, + {"what is the difference between remote control and move here", "remote-control"}, + {"can my laptop answer a question that is waiting on my desktop", "remote-control"}, + {"remote control says restart codeaf on the other computer", "remote-control"}, + {"do I need to restart codeaf after I turn remote control on", "remote-control"}, + {"I turned remote control on in settings but enter still asks to move the chat", "remote-control"}, + {"after I open a chat live from my other computer Home's project is a folder that does not exist on this computer", "remote-control"}, + {"does opening a chat live change the project on home", "remote-control"}, + {"is remote control the same as codeaf serve and --at", "remote-control"}, + // The direct road (the same page): two computers on one network connect + // without the relay, what /status says, and the switches that govern it. + {"does my remote view go through the relay", "remote-control"}, + {"can my two computers connect directly", "remote-control"}, + {"how do I see if remote control is direct", "remote-control"}, + {"make remote control only use the relay", "remote-control"}, + {"what is STUN and does codeaf contact Google", "remote-control"}, + {"why does status say live direct", "remote-control"}, + {"does remote control work on a network that blocks UDP", "remote-control"}, + // The desktop's own switch (desktop-sync.md): where it is and why it says restart. + {"how do I turn on remote control in the desktop app", "desktop-sync"}, + {"the Remote control switch in the desktop settings says restart", "desktop-sync"}, + {"Remote control is set by CODEAF_REMOTE_CONTROL and the switch is greyed out", "desktop-sync"}, + // The keyboard of a chat the desktop runs (desktop-sync.md): who is typing, and Type here. + {"my desktop chat says Typing from another computer now and I can't type", "desktop-sync"}, + {"how do I take the keyboard back in the desktop app from my other computer", "desktop-sync"}, + {"what does the Type here button do in the desktop", "desktop-sync"}, + // A new chat on another computer's Home (remote-control.md): when the row first appears. + {"my new chat does not show on my other computer while its first message is still running", "remote-control"}, + {"when does a chat appear on my other computer's Home with remote control on", "remote-control"}, // Sharing and moving inside an organization: roles, grants, the // operator's policy, a shared chat read-only, move against share, an // expiry, and Afi's pane and a task's conversation as sessions. @@ -5194,8 +5241,8 @@ func TestTheDeviceQuestionsReachTheirPages(t *testing.T) { const add, cont, naming = "add-or-remove-a-computer", "continuing-a-chat-on-another-computer", "naming-a-device" for _, probe := range []struct{ asked, page, says string }{ {"why can't I type in this chat", cont, "Your words stay in the box"}, - {"my message did not send and home opened with a question", cont, "Continue this chat here?"}, - {"continue on this machine", cont, "Continue tower's latest chat here?"}, + {"my message did not send and home opened with a question", cont, "Move this chat here?"}, + {"continue on this machine", cont, "Move tower's latest chat here?"}, {"what does running on tower mean", cont, "Move here"}, {"what does moved from tower in 3.2s mean", cont, "Everything as you left it."}, {"what is the card that says set this machine up", cont, "set up"}, @@ -5279,7 +5326,7 @@ func TestTheCrossComputerQuestionsReachTheFactThatAnswersThem(t *testing.T) { {"is the task history carried to the other computer", "continuing-a-chat-on-another-computer", "rebuilt from the chat's own record"}, {"does /remember work on my other computer", "what-i-remember", "within one sync round"}, {"how do I take a chat back from my other computer", "continuing-a-chat-on-another-computer", "Nothing has to be returned or switched off first."}, - {"what happens if two computers continue the same chat at once", "continuing-a-chat-on-another-computer", "The slower one sees `another device continued this chat first`"}, + {"what happens if two computers continue the same chat at once", "continuing-a-chat-on-another-computer", "The slower one sees `another device moved this chat first`"}, {"where does sync go by default", "relay-hosted-or-your-own", "https://codeaf.agentfield.ai/fabric"}, {"which relay does a dev build or staging build use", "relay-hosted-or-your-own", "https://caf-fabric-dev.instrument-santosh.workers.dev"}, {"do dev and stable builds sync with each other", "relay-hosted-or-your-own", "Channels do not sync with each other"}, @@ -5453,7 +5500,7 @@ func TestStorageOptInSettingsAndTeamsQuestions(t *testing.T) { t.Run(probe.question, func(t *testing.T) { for _, section := range Chat().Search(probe.question, DefaultResults) { if section.Page == probe.page && strings.HasPrefix(section.Title, probe.heading) { - if !strings.Contains(section.Body, "sync storage approval") { + if !strings.Contains(section.Body, "relay storage approval") { t.Fatalf("approval missing: %s", section.Body) } return diff --git a/internal/manual/cluster_truth_test.go b/internal/manual/cluster_truth_test.go index b120686a5d..cde06f37a5 100644 --- a/internal/manual/cluster_truth_test.go +++ b/internal/manual/cluster_truth_test.go @@ -79,7 +79,7 @@ func TestR30CoordinationQuotesMatchProductStrings(t *testing.T) { for page, body := range flatChatPages(t) { for _, match := range quotes.FindAllStringSubmatch(body, -1) { text := match[1] - for _, prefix := range []string{"this cluster", "this computer must join", "this computer is still joining", "this codeaf build", "the leadership request", "codeaf: directory upgrade", "this work may be incomplete", "another device continued this chat first"} { + for _, prefix := range []string{"this cluster", "this computer must join", "this computer is still joining", "this codeaf build", "the leadership request", "codeaf: directory upgrade", "this work may be incomplete", "another device moved this chat first"} { if strings.HasPrefix(text, prefix) { if _, ok := seen[text]; !ok { t.Errorf("%s quotes a sentence absent from the product: %q", page, text) diff --git a/internal/manual/idle_handoff_test.go b/internal/manual/idle_handoff_test.go index 9434708b91..dcf1074469 100644 --- a/internal/manual/idle_handoff_test.go +++ b/internal/manual/idle_handoff_test.go @@ -7,7 +7,7 @@ import ( func TestIdleOpen_C6_C7_IndexedAnswersDistinguishFreeAndHeld(t *testing.T) { for _, probe := range []struct{ question, phrase string }{ - {"a row on home and the verb it offers", "There is no Continue-here card"}, + {"a row on home and the verb it offers", "There is no Move-here card"}, {"I reopened an old local chat after the other computer let go", "latest saved history here automatically"}, {"Continue a chat here that another machine left", "released chat opens directly"}, {"Why a chat says held on build-box or build-box offline", "released chat opens here directly"}, diff --git a/internal/manual/relay_defects_test.go b/internal/manual/relay_defects_test.go index 7562df1a87..afb5b0cf3a 100644 --- a/internal/manual/relay_defects_test.go +++ b/internal/manual/relay_defects_test.go @@ -18,10 +18,10 @@ func TestRelayDefectAnswersSurvivePacking(t *testing.T) { compressed := newCorpus(packed.New(archive), "chat/*.md") for _, corpus := range []*Corpus{Chat(), compressed} { for _, probe := range []struct{ query, page, words string }{ - {"my chosen chat while a startup chat is still arriving", "home", "continuing next; is still on its way here"}, + {"my chosen chat while a startup chat is still arriving", "home", "moving next; is still on its way here"}, {"slow chat listing timeout waiting for a service host", "continuing-a-chat-on-another-computer", " did not answer in 25s; still trying"}, {"my typed message after continue here is kept does it send by itself", "continuing-a-chat-on-another-computer", "your message is still in the box; press enter to send it"}, - {"continue here another device continuing first picked this chat up again", "continuing-a-chat-on-another-computer", " picked this chat up again; press enter to continue it here"}, + {"continue here another device continuing first picked this chat up again", "continuing-a-chat-on-another-computer", " picked this chat up again; press enter to move it here"}, {"relay trust proxy registration dial pairing X-Forwarded-For", "relay-hosted-or-your-own", "registration, dial and pairing limits"}, } { found := false @@ -37,7 +37,7 @@ func TestRelayDefectAnswersSurvivePacking(t *testing.T) { page, _ := corpus.Page("continuing-a-chat-on-another-computer") for _, part := range strings.Split(page, "\n## ")[1:] { heading, _, _ := strings.Cut(part, "\n") - if strings.HasPrefix(heading, "my choice while") || strings.HasPrefix(heading, "My typed message") || strings.HasPrefix(heading, "slow chat listing") || strings.HasPrefix(heading, "Continue here does nothing") || strings.HasPrefix(heading, "why continue here failed") { + if strings.HasPrefix(heading, "my choice while") || strings.HasPrefix(heading, "My typed message") || strings.HasPrefix(heading, "slow chat listing") || strings.HasPrefix(heading, "Move here does nothing") || strings.HasPrefix(heading, "why move here failed") { if len([]rune(part)) > 2000 { t.Errorf("section exceeds 2000 characters: %s", heading) } diff --git a/internal/manual/remote_control_test.go b/internal/manual/remote_control_test.go new file mode 100644 index 0000000000..787475bc5e --- /dev/null +++ b/internal/manual/remote_control_test.go @@ -0,0 +1,131 @@ +package manual + +import ( + "strings" + "testing" + "unicode/utf8" + + "github.com/Agent-Field/codeaf/internal/chatlist" +) + +// REMOTE CONTROL IS A FEATURE THE CHAT CANNOT GUESS. A person who sees "tower went +// offline" or "watch, not type" on a live view asks the chat what it means, and the +// chat answers from this page alone: its training data has never met the feature. +// So every sentence the view can say is on the page word for word, the page says +// the feature is off until it is turned on, and the questions people ask reach it. + +const remoteControlPage = "remote-control" + +// V13: every sentence a live view can say is on the remote control page, spelled as +// the code spells it, so a person who asks about one is answered with that sentence. +func TestEverySentenceOfALiveViewIsOnTheRemoteControlPage(t *testing.T) { + page, ok := Chat().Page(remoteControlPage) + if !ok { + t.Fatalf("the page %s is not in the chat corpus", remoteControlPage) + } + const host = "tower" + said := []string{ + chatlist.LiveMoving, + chatlist.LiveIdle, + chatlist.LiveBudget, + chatlist.LiveRemoved, + chatlist.LiveWentOffline(host), + chatlist.LiveOfflineSeen(host, "14:02"), + chatlist.LiveNotSentOffline(host), + chatlist.LiveWatchOnly(host), + chatlist.LiveTypingFrom(host), + chatlist.LiveNotAllowedHere(host), + chatlist.LiveNeedsItsOwnOK(host), + } + // The close reasons are a closed set; the page lists the ones a person meets. + for _, reason := range []string{ + "not-running", "not-allowed", "holder-gone", "holder-old", "removed", + "permit-changed", "lagging", "frame-too-large", "budget", "idle", "host-closing", "too-many", "remote-control-off", + } { + said = append(said, chatlist.LiveSaid(reason, host)) + } + for _, sentence := range said { + if !strings.Contains(page, sentence) { + t.Errorf("the page %s does not say %q: add it to internal/manual/chat/%s.md", remoteControlPage, sentence, remoteControlPage) + } + } +} + +// V13: three questions are pinned to the SECTION that answers them, not only to the +// page, because the page holds a dozen sections and these are the ones a +// person asks with a sentence on the screen in front of them. +func TestTheQuestionsAboutAWordOnALiveViewReachTheSectionThatExplainsIt(t *testing.T) { + for _, tc := range []struct { + question string + title string + says string + }{ + {"what does watch only mean", "watch only", "lets this computer watch, not type"}, + {"it says tower went offline", "went offline", "last seen"}, + {"how do I turn remote control on", "Remote control is off", "CODEAF_REMOTE_CONTROL=1"}, + {"it says tower turned remote control off", "Why did my live view end", "tower turned remote control off."}, + } { + found := false + for _, section := range Chat().Search(tc.question, DefaultResults) { + if section.Page == remoteControlPage && strings.Contains(section.Title, tc.title) && strings.Contains(section.Body, tc.says) { + found = true + } + } + if !found { + t.Errorf("%q did not reach the %q section of %s", tc.question, tc.title, remoteControlPage) + } + } +} + +// The page says what is true on the day it ships: remote control is off until it +// is turned on, and a computer that has not been allowed can only watch. +func TestTheRemoteControlPageSaysItIsOffUntilTurnedOnAndHowToTurnItOn(t *testing.T) { + page, _ := Chat().Page(remoteControlPage) + for _, needle := range []string{ + "off until you turn it on", + "CODEAF_REMOTE_CONTROL=1", + "`remote control`", + "codeaf devices permit", + "never starts a chat", + "codeaf identity rotate", + } { + if !strings.Contains(page, needle) { + t.Errorf("the page does not say %q", needle) + } + } +} + +// The page keeps the vocabulary law of the device pages: it never speaks of the +// machinery, and the word relay names only the server and its storage. +func TestTheRemoteControlPageKeepsTheVocabularyLaw(t *testing.T) { + page, _ := Chat().Page(remoteControlPage) + low := strings.ToLower(page) + for _, banned := range []string{"fleet", "enroll", "enrol", "lease", "directory", "vault", "blob", "manifest", "takeover", "take over", "continue here"} { + if strings.Contains(low, banned) { + t.Errorf("the remote control page says %q", banned) + } + } + for _, banned := range []string{"the board", "the self page", "standing watch", "resident employee", "front desk"} { + if strings.Contains(low, banned) { + t.Errorf("the remote control page speaks of the resident: %q", banned) + } + } +} + +// Each section is retrieved alone, so each stays under the cap and says what it is +// about in its own words. +func TestEverySectionOfTheRemoteControlPageIsSelfContainedAndShort(t *testing.T) { + n := 0 + for _, section := range Chat().Sections() { + if section.Page != remoteControlPage { + continue + } + n++ + if size := utf8.RuneCountInString(section.Title) + utf8.RuneCountInString(section.Body); size > 2000 { + t.Errorf("section %q is %d characters, over the 2000 a retrieved section may be", section.Title, size) + } + } + if n < 13 { + t.Errorf("the page has %d sections; the outline has at least 13", n) + } +} diff --git a/internal/manual/retired_words_test.go b/internal/manual/retired_words_test.go new file mode 100644 index 0000000000..7c20f7c686 --- /dev/null +++ b/internal/manual/retired_words_test.go @@ -0,0 +1,61 @@ +package manual + +import ( + "strings" + "testing" +) + +// The chat manual's words for two things changed on 2026-11-23. That no page +// offers the old words is internal/wordlaw's law (it reads the pages as text); +// what is tested here is the other half of the contract, that the manual still +// ANSWERS somebody who remembers them: one heading holds both the new words and +// the old ones, and a question in the old words reaches it. + +// oldLabelSection is the one section that spells the retired label, in its +// heading, so the page answers by either spelling. +func oldLabelSection(title string) bool { + lower := strings.ToLower(title) + return strings.Contains(lower, "continue here") && strings.Contains(lower, "move here") +} + +func TestTheOldLabelStillReachesTheMovePage(t *testing.T) { + const page = "continuing-a-chat-on-another-computer" + for _, asked := range []string{ + "what happened to the Continue here button", + "where did Continue here go", + "I used to click Continue here on home, what is it called now", + "Continue here is now Move here", + } { + found := false + for _, section := range Chat().Search(asked, DefaultResults) { + if section.Page == page && oldLabelSection(section.Title) && strings.Contains(section.Body, "**Move here** is the one verb") { + found = true + } + } + if !found { + t.Errorf("%q did not reach the section that answers by the old label", asked) + } + } +} + +// The storage switch is "relay storage" now. Contract: a person who remembers +// "sync storage" still reaches the sections that answer for it, and the name +// they find says what it is called now. +func TestTheOldStorageNameStillReachesRelayStorage(t *testing.T) { + for _, probe := range []struct{ asked, page string }{ + {"what happened to sync storage", "relay-what-it-stores-and-sees"}, + {"how do I turn on sync storage", "relay-what-it-stores-and-sees"}, + {"where is the sync storage row in settings", "settings"}, + } { + found := false + for _, section := range Chat().Search(probe.asked, DefaultResults) { + lower := strings.ToLower(section.Title) + if section.Page == probe.page && strings.Contains(lower, "relay storage") && strings.Contains(lower, "sync storage") { + found = true + } + } + if !found { + t.Errorf("%q did not reach %s under a heading that names both spellings", probe.asked, probe.page) + } + } +} diff --git a/internal/pair/edge_relay_test.go b/internal/pair/edge_relay_test.go index 2a2e57385d..384637b886 100644 --- a/internal/pair/edge_relay_test.go +++ b/internal/pair/edge_relay_test.go @@ -506,7 +506,7 @@ func TestRelayTooOld(t *testing.T) { // A RELAY THAT DOES NOT ANSWER IS NAMED BY ITS HOST, and the offering device // shows no code it could not serve. func TestRelayUnreachable(t *testing.T) { - const want = "nothing is answering at https://relay.test — if that is your own sync service, start it there with codeaf relay" + const want = "nothing is answering at https://relay.test — if that is your own relay, start it there with codeaf relay" t.Run("at the first question", func(t *testing.T) { r, hostile := hostileRig(t) hostile.failLimits(unreachable()) diff --git a/internal/pair/edge_serve_test.go b/internal/pair/edge_serve_test.go index 7c0009de94..c566f7a1dd 100644 --- a/internal/pair/edge_serve_test.go +++ b/internal/pair/edge_serve_test.go @@ -295,7 +295,7 @@ func TestServeSaysOnceThatItLostSyncAndComesBack(t *testing.T) { server.Start() t.Cleanup(server.Close) screen := &screenLog{} - host := &Host{Service: server.URL, Device: aDevice(t), Devices: BookAt(filepath.Join(t.TempDir(), "devices.json")), Desk: &Desk{}, Say: screen.say} + host := &Host{Service: server.URL, Device: aDevice(t), Devices: BookAt(filepath.Join(t.TempDir(), "devices.json")), Desk: &Desk{}, Say: screen.say, sleep: retriesQuickly} ctx, stop := context.WithCancel(context.Background()) ended := make(chan struct{}) go func() { _ = host.Run(ctx); close(ended) }() @@ -304,7 +304,7 @@ func TestServeSaysOnceThatItLostSyncAndComesBack(t *testing.T) { down.Store(true) wire.cut() - time.Sleep(4 * time.Second) // the first retries come at one and two seconds + time.Sleep(4 * time.Second) // several retries come, a second apart at most down.Store(false) waitForCondition(t, "the machine to register again", func() bool { return len(door.Ledgers()) == 1 @@ -364,7 +364,7 @@ func TestServeWaitsOutItsOwnStaleName(t *testing.T) { t.Cleanup(server.Close) screen := &screenLog{} device := aDevice(t) - host := &Host{Service: server.URL, Device: device, Devices: BookAt(filepath.Join(t.TempDir(), "devices.json")), Desk: &Desk{}, Say: screen.say} + host := &Host{Service: server.URL, Device: device, Devices: BookAt(filepath.Join(t.TempDir(), "devices.json")), Desk: &Desk{}, Say: screen.say, sleep: retriesQuickly} ctx, stop := context.WithCancel(context.Background()) ended := make(chan struct{}) var runErr error @@ -611,7 +611,10 @@ func TestDroppedRegistrationBacksOffAndPrintsBannerOnce(t *testing.T) { awaitStep(t, connected, fmt.Sprintf("reconnect %d", i+1)) } - wantWaits := []time.Duration{ + // V22: the first wait after a drop is one second plus a draw from the + // next five, and every later wait is the doubling schedule (2 s, 4 s ... + // capped at a minute) scaled by 0.75 to 1.25, so no two computers keep step. + schedule := []time.Duration{ 1 * time.Second, 2 * time.Second, 4 * time.Second, @@ -623,9 +626,9 @@ func TestDroppedRegistrationBacksOffAndPrintsBannerOnce(t *testing.T) { time.Minute, time.Minute, } - for i, want := range wantWaits { - if waits[i] != want { - t.Fatalf("backoff %d was %v, want %v (all: %v)", i+1, waits[i], want, waits) + for i, step := range schedule { + if !inBackoffBand(waits[i], step, i == 0) { + t.Fatalf("backoff %d was %v, want %s (all: %v)", i+1, waits[i], bandWords(step, i == 0), waits) } } if got := len(codes(screen.all())); got != 1 { @@ -647,8 +650,8 @@ func TestDroppedRegistrationBacksOffAndPrintsBannerOnce(t *testing.T) { // resets the backoff to 1s. advance(steadyAfter + time.Second) wire.cut() - if reset := awaitStep(t, slept, "backoff after steady registration"); reset != time.Second { - t.Fatalf("backoff after holding >= %v was %v, want 1s", steadyAfter, reset) + if reset := awaitStep(t, slept, "backoff after steady registration"); !inBackoffBand(reset, time.Second, true) { + t.Fatalf("backoff after holding >= %v was %v, want %s", steadyAfter, reset, bandWords(time.Second, true)) } }) @@ -690,15 +693,44 @@ func TestDroppedRegistrationBacksOffAndPrintsBannerOnce(t *testing.T) { t.Fatalf("raw package sentinel leaked to screen: %q", line) } } - want := []time.Duration{time.Second, 2 * time.Second, 4 * time.Second} - for i := range want { - if waits[i] != want[i] { - t.Fatalf("429 backoff %d was %v, want %v (all: %v)", i+1, waits[i], want[i], waits) + schedule := []time.Duration{time.Second, 2 * time.Second, 4 * time.Second} + for i, step := range schedule { + if !inBackoffBand(waits[i], step, i == 0) { + t.Fatalf("429 backoff %d was %v, want %s (all: %v)", i+1, waits[i], bandWords(step, i == 0), waits) } } }) } +// inBackoffBand says whether a wait is one the spread schedule can produce at +// this step: the first wait after a drop is in [1 s, 6 s), and every later one is +// the step scaled into [0.75, 1.25) of itself. +func inBackoffBand(got, step time.Duration, first bool) bool { + if first { + return got >= time.Second && got < 6*time.Second + } + return got >= step*3/4 && got < step*5/4 +} + +func bandWords(step time.Duration, first bool) string { + if first { + return "a first wait in [1s, 6s)" + } + return fmt.Sprintf("a wait in [%v, %v)", step*3/4, step*5/4) +} + +// retriesQuickly stands in for the retry wait in a test that watches a real relay +// come and go. The schedule is spread over several seconds on purpose, which is +// right for a fleet and slow for one test, so the wait is capped at a second. +func retriesQuickly(ctx context.Context, d time.Duration) error { + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(min(d, time.Second)): + return nil + } +} + func waitForCondition(t *testing.T, what string, ok func() bool) { t.Helper() deadline := time.Now().Add(5 * time.Second) diff --git a/internal/pair/errors.go b/internal/pair/errors.go index b5c2b41884..d299d7ed79 100644 --- a/internal/pair/errors.go +++ b/internal/pair/errors.go @@ -24,7 +24,7 @@ import ( // The facts, so a caller can tell them apart before phrasing them. var ( // ErrNoRelay is this machine having no relay address at all. - ErrNoRelay = errors.New("pair: no sync service is configured") + ErrNoRelay = errors.New("pair: no relay is configured") // ErrNotPaired is this device never having been let in to that machine. ErrNotPaired = errors.New("pair: this device is not paired with that machine") // ErrWrongCode is the pairing code not matching. @@ -40,7 +40,7 @@ var ( // NoRelay is the first sentence: nothing is configured. func NoRelay(name string) error { - return fmt.Errorf("no sync service is set up on this machine, so --at has nowhere to look for %s — set %s to a sync service, or reach that machine with --host over ssh", name, RelayEnv) + return fmt.Errorf("no relay is set up on this machine, so --at has nowhere to look for %s — set %s to a relay, or reach that machine with --host over ssh", name, RelayEnv) } // Unreachable is the second: something is configured and it is not answering. @@ -89,7 +89,7 @@ func NoAnswer(name string) error { // Busy is the relay turning connections away. func Busy() error { - return errors.New("the sync service is turning connections away right now — try again in a minute") + return errors.New("the relay is turning connections away right now — try again in a minute") } // Stopped is what a machine says to a device it no longer lets in. It travels @@ -147,13 +147,13 @@ var ( // ErrBadGrant is what arrived as a grant and could not be used. ErrBadGrant = errors.New("what the other device sent could not be read; nothing was changed") // ErrSyncOff is a person who has turned the relay off. - ErrSyncOff = errors.New("sync is off (CODEAF_SYNC_URL=off); pairing needs the sync service") + ErrSyncOff = errors.New("sync is off (CODEAF_SYNC_URL=off); pairing needs the relay") // ErrNoSync is a person with no relay set at all. - ErrNoSync = errors.New("no sync service is set, so there is nowhere to pair through: set CODEAF_SYNC_URL to its address, or pass --via
") + ErrNoSync = errors.New("no relay is set, so there is nowhere to pair through: set CODEAF_SYNC_URL to its address, or pass --via
") // ErrRelayBusy is a relay at one of its global caps. ErrRelayBusy = errors.New("sync is full right now; try again in a few minutes") // ErrRelayTooOld is a relay that does not know pairing yet. - ErrRelayTooOld = errors.New("that sync service is too old for pairing") + ErrRelayTooOld = errors.New("that relay is too old for pairing") // ErrDifferentChats is a computer that already has chats of its own. ErrDifferentChats = errors.New("this computer has local work, so nothing was changed. To pair it anyway, run this again with --replace: local chats stay on this computer but no longer sync; shared memories and settings are cleared") // ErrAlreadyPaired is a computer that already holds the chats being offered. @@ -229,13 +229,13 @@ func (e cannotReachError) Unwrap() error { return ErrCannotReach } // NoDoorForServe gives the machine operator a remedy on this machine. func NoDoorForServe(service string) error { - return fmt.Errorf("the sync service at %s syncs chats but does not connect machines — run your own with `codeaf relay` and set %s to it", service, RelayEnv) + return fmt.Errorf("the relay at %s syncs chats but does not connect machines — run your own with `codeaf relay` and set %s to it", service, RelayEnv) } // notConnectedError keeps readiness checks independent of the visible sentence. type notConnectedError struct{ name string } func (e notConnectedError) Error() string { - return fmt.Sprintf("%s is not connected to the sync service right now — run `codeaf serve` on that machine", e.name) + return fmt.Sprintf("%s is not connected to the relay right now — run `codeaf serve` on that machine", e.name) } func (e notConnectedError) Unwrap() error { return ErrNotConnected } diff --git a/internal/pair/intent_tunnel_test.go b/internal/pair/intent_tunnel_test.go new file mode 100644 index 0000000000..b88b810c97 --- /dev/null +++ b/internal/pair/intent_tunnel_test.go @@ -0,0 +1,180 @@ +package pair + +import ( + "bytes" + "crypto/ecdh" + "crypto/rand" + "errors" + "io" + "net" + "testing" + "time" +) + +// V21 / D2: a single registration can serve multiple doors when the first byte +// on the stream selects the Noise prologue for that intent, and a stream whose +// intent and prologue do not match fails the handshake. +func TestAnIntentAndItsPrologueSelectTheTunnel(t *testing.T) { + newKey := func() *ecdh.PrivateKey { + k, err := ecdh.X25519().GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + return k + } + a, b := newKey(), newKey() + prologues := map[byte]string{ + IntentFiles: "codeaf files door v1 connect", + IntentLive: "codeaf live door v1 connect", + } + + for _, tc := range []struct { + name string + intent byte + prologue string + }{ + {name: "files intent", intent: IntentFiles, prologue: prologues[IntentFiles]}, + {name: "live intent", intent: IntentLive, prologue: prologues[IntentLive]}, + } { + t.Run(tc.name, func(t *testing.T) { + near, far := net.Pipe() + defer near.Close() + defer far.Close() + _ = near.SetDeadline(time.Now().Add(3 * time.Second)) + _ = far.SetDeadline(time.Now().Add(3 * time.Second)) + + type accepted struct { + tunnel *Tunnel + intent byte + err error + } + done := make(chan accepted, 1) + go func() { + tun, got, err := AcceptWithKeyPrologues(far, b, nil, prologues) + done <- accepted{tunnel: tun, intent: got, err: err} + }() + + client, err := ConnectWithKeyIntent(near, b.PublicKey().Bytes(), a, tc.intent, tc.prologue) + if err != nil { + t.Fatal(err) + } + server := <-done + if server.err != nil { + t.Fatal(server.err) + } + if server.intent != tc.intent { + t.Fatalf("accepted intent = %q, want %q", server.intent, tc.intent) + } + if !bytes.Equal(client.ChannelBinding(), server.tunnel.ChannelBinding()) { + t.Fatal("endpoints do not share the completed channel binding") + } + if !bytes.Equal(server.tunnel.Peer(), a.PublicKey().Bytes()) { + t.Fatal("responder did not authenticate the initiator key") + } + + msg := []byte("encrypted payload for selected intent") + errCh := make(chan error, 1) + go func() { + _, err := client.Write(msg) + errCh <- err + }() + got := make([]byte, len(msg)) + if _, err := io.ReadFull(server.tunnel, got); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, msg) { + t.Fatalf("read %q, want %q", got, msg) + } + if err := <-errCh; err != nil { + t.Fatal(err) + } + }) + } + + t.Run("mismatched intent and prologue fail the handshake", func(t *testing.T) { + near, far := net.Pipe() + defer near.Close() + defer far.Close() + _ = near.SetDeadline(time.Now().Add(3 * time.Second)) + _ = far.SetDeadline(time.Now().Add(3 * time.Second)) + + done := make(chan error, 1) + go func() { + defer far.Close() + _, _, err := AcceptWithKeyPrologues(far, b, nil, prologues) + done <- err + }() + + if _, err := ConnectWithKeyIntent(near, b.PublicKey().Bytes(), a, IntentLive, prologues[IntentFiles]); err == nil { + t.Fatal("handshake completed when the intent selected a different prologue") + } + if err := <-done; err == nil { + t.Fatal("responder accepted a mismatched prologue") + } + }) +} + +// V21 / D2: an intent refused by the admission check or absent from the +// responder's prologue map closes the connection before any byte is written back. +func TestAnUnadmittedIntentIsClosedBeforeAnyByteIsWrittenBack(t *testing.T) { + b, err := ecdh.X25519().GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + prologues := map[byte]string{ + IntentFiles: "codeaf files door v1 connect", + IntentLive: "codeaf live door v1 connect", + } + + for _, tc := range []struct { + name string + intent byte + admit func(byte) bool + prologues map[byte]string + }{ + { + name: "refused by admit callback", + intent: IntentLive, + admit: func(intent byte) bool { return intent != IntentLive }, + prologues: prologues, + }, + { + name: "intent absent from prologues", + intent: IntentLive, + admit: nil, + prologues: map[byte]string{IntentFiles: prologues[IntentFiles]}, + }, + { + name: "unknown intent byte", + intent: 'Z', + admit: func(byte) bool { return true }, + prologues: prologues, + }, + } { + t.Run(tc.name, func(t *testing.T) { + near, far := net.Pipe() + defer near.Close() + defer far.Close() + _ = near.SetDeadline(time.Now().Add(3 * time.Second)) + _ = far.SetDeadline(time.Now().Add(3 * time.Second)) + + done := make(chan error, 1) + go func() { + _, _, err := AcceptWithKeyPrologues(far, b, tc.admit, tc.prologues) + done <- err + }() + + if _, err := near.Write([]byte{tc.intent}); err != nil { + t.Fatal(err) + } + var buf [16]byte + n, readErr := near.Read(buf[:]) + if n != 0 || !errors.Is(readErr, io.EOF) { + t.Fatalf("read %d bytes (%v) after unadmitted intent, want 0 bytes and io.EOF", n, readErr) + } + if err := <-done; err == nil { + t.Fatal("responder returned nil error for an unadmitted intent") + } + }) + } +} diff --git a/internal/pair/join.go b/internal/pair/join.go index fdd71e720a..a30e5bafb7 100644 --- a/internal/pair/join.go +++ b/internal/pair/join.go @@ -103,6 +103,9 @@ func Join(ctx context.Context, route Mailbox, j Joining, typed string, ui JoinUI // The other device can only confirm after this home has kept the grant. // If the confirmation is lost, this home still holds the approved grant. _ = intro.took() + if !joined.Already { + stampJoin(grant.Identity.ID()) + } } return joined, err } diff --git a/internal/pair/l4_words_test.go b/internal/pair/l4_words_test.go index 8916d229da..8a47d449d6 100644 --- a/internal/pair/l4_words_test.go +++ b/internal/pair/l4_words_test.go @@ -42,7 +42,7 @@ func TestL4PairCompletionVoice(t *testing.T) { if got := (Joined{With: "laptop-a"}).Sentence(); got != "Paired with laptop-a. Run codeaf to open your chats." { t.Fatal(got) } - if got := PairedChatsLine("desk-b"); got != "desk-b is now paired. Your chats can continue there." { + if got := PairedChatsLine("desk-b"); got != "desk-b is now paired. desk-b can also see and control your chats here. Change that in /devices." { t.Fatal(got) } if got := WaitingChatsLine("a b c"); got != "Waiting for approval on your other device; it should show: a b c" { @@ -116,7 +116,7 @@ func TestL4ServeRemedyIsLocal(t *testing.T) { // L4-H6d: code-pairing server failures use the same sentence as devices and cluster. func TestL4CodePairServiceFailure(t *testing.T) { got := phraseBox(wireauth.ErrUnavailable, "http://127.0.0.1:8901") - if got.Error() != "the sync service at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute" { + if got.Error() != "the relay at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute" { t.Fatal(got) } } diff --git a/internal/pair/lines.go b/internal/pair/lines.go index df087c5dc5..4af028d54e 100644 --- a/internal/pair/lines.go +++ b/internal/pair/lines.go @@ -158,8 +158,14 @@ func CheckQuestion(check string) string { return "Check number " + check + ". Approve only if the new device shows the same number." } +// PairedControlLine tells the approving person that a newly paired computer can +// view and type into chats on this computer and where to change that permission. +func PairedControlLine(name string) string { + return name + " can also see and control your chats here. Change that in /devices." +} + // ApprovedLine is what the approving device says when it let one in. -func ApprovedLine(name string) string { return name + " is now paired. Your chats can continue there." } +func ApprovedLine(name string) string { return name + " is now paired. " + PairedControlLine(name) } // RecordUnsaidLine is what a device says when its own record did not reach the // directory after a pairing that itself worked: the pairing stands, and the diff --git a/internal/pair/lines_test.go b/internal/pair/lines_test.go index 45f4c43670..35b33602d9 100644 --- a/internal/pair/lines_test.go +++ b/internal/pair/lines_test.go @@ -1,6 +1,9 @@ package pair -import "testing" +import ( + "strings" + "testing" +) // A pairing that reached no workspaces says only that it paired: a count of // zero is never printed. @@ -28,3 +31,29 @@ func TestWantsToJoinLineNamesTheSystem(t *testing.T) { } } } + +// V25: the approval sentence tells the person that a newly paired computer can +// see and control chats here and where to change that permission, without internal jargon. +func TestThePairedLineSaysTheNewDeviceCanControlChatsHere(t *testing.T) { + const wantControl = "laptop can also see and control your chats here. Change that in /devices." + if got := PairedControlLine("laptop"); got != wantControl { + t.Fatalf("PairedControlLine(\"laptop\") = %q, want %q", got, wantControl) + } + gotApproved := ApprovedLine("laptop") + if !strings.HasPrefix(gotApproved, "laptop is now paired. ") { + t.Fatalf("ApprovedLine(\"laptop\") = %q, want prefix %q", gotApproved, "laptop is now paired. ") + } + if !strings.HasSuffix(gotApproved, wantControl) { + t.Fatalf("ApprovedLine(\"laptop\") = %q, want suffix %q", gotApproved, wantControl) + } + if want := "laptop is now paired. " + wantControl; gotApproved != want { + t.Fatalf("ApprovedLine(\"laptop\") = %q, want %q", gotApproved, want) + } + for _, banned := range []string{"relay", "take", "lease", "node", "manifest", "cell", "directory", "cas"} { + for _, line := range []string{PairedControlLine("laptop"), ApprovedLine("laptop")} { + if strings.Contains(strings.ToLower(line), banned) { + t.Errorf("line %q contains banned word %q", line, banned) + } + } + } +} diff --git a/internal/pair/linkjoin.go b/internal/pair/linkjoin.go index a603f5ec46..9c9f7416f6 100644 --- a/internal/pair/linkjoin.go +++ b/internal/pair/linkjoin.go @@ -211,6 +211,7 @@ func (a *asker) install(ctx context.Context, j LinkJoining, g LinkGrant) (LinkJo return LinkJoined{Joined: joined}, err } joined.Already = false + stampJoin(g.Identity.ID()) } fleet, err := j.Pull(ctx) if err != nil { diff --git a/internal/pair/pair_test.go b/internal/pair/pair_test.go index 8775d99ad8..a37faeba20 100644 --- a/internal/pair/pair_test.go +++ b/internal/pair/pair_test.go @@ -535,7 +535,7 @@ func TestEveryWayThisFailsSaysWhichWayItFailed(t *testing.T) { if err == nil { t.Fatal("--at opened with no relay set up") } - if !strings.Contains(err.Error(), "no sync service is set up on this machine") { + if !strings.Contains(err.Error(), "no relay is set up on this machine") { t.Fatalf("with no relay, --at said %q", err) } if !strings.Contains(err.Error(), "--host over ssh") { @@ -560,7 +560,7 @@ func TestEveryWayThisFailsSaysWhichWayItFailed(t *testing.T) { _, address := liveRelay(t) t.Setenv(RelayEnv, address) _, err := asking.Open(context.Background()) - if err == nil || !strings.Contains(err.Error(), "is not connected to the sync service right now") { + if err == nil || !strings.Contains(err.Error(), "is not connected to the relay right now") { t.Fatalf("with nothing registered, --at said %v", err) } if !strings.Contains(err.Error(), "codeaf serve") { diff --git a/internal/pair/permit_test.go b/internal/pair/permit_test.go new file mode 100644 index 0000000000..b8eda72c69 --- /dev/null +++ b/internal/pair/permit_test.go @@ -0,0 +1,526 @@ +package pair + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/identity" +) + +func boolPtr(v bool) *bool { return &v } + +// V11: a watch-only device has drive turned off, and partial updates change +// only the non-nil field while keeping the other field from the effective permit. +func TestAWatchOnlyDeviceHasDriveOff(t *testing.T) { + book := PermitsAt(filepath.Join(t.TempDir(), "permits.json")) + const id = "id_alpha" + const dev = "dev_laptop" + + if err := book.Set(id, dev, boolPtr(true), boolPtr(false), "person"); err != nil { + t.Fatal(err) + } + got, class := book.For(id, dev) + if !got.Watch || got.Drive || class != ClassExplicit || got.By != "person" || got.At.IsZero() { + t.Fatalf("after watch=true drive=false: got (%+v, %v), want Watch=true Drive=false ClassExplicit", got, class) + } + + if err := book.Set(id, dev, nil, boolPtr(true), "person"); err != nil { + t.Fatal(err) + } + got, class = book.For(id, dev) + if !got.Watch || !got.Drive || class != ClassExplicit { + t.Fatalf("after drive=true: got (%+v, %v), want Watch=true Drive=true ClassExplicit", got, class) + } + + if err := book.Set(id, dev, boolPtr(false), nil, "person"); err != nil { + t.Fatal(err) + } + got, class = book.For(id, dev) + if got.Watch || !got.Drive || class != ClassExplicit { + t.Fatalf("after watch=false: got (%+v, %v), want Watch=false Drive=true ClassExplicit", got, class) + } +} + +// V25: a pairing recorded in the one-time legacy snapshot stays drive-off while +// a pairing made afterwards defaults to drive-on, and the snapshot never grows. +func TestAPairingMadeAfterThisShipsHasDriveOnAndOneBeforeStaysOff(t *testing.T) { + book := PermitsAt(filepath.Join(t.TempDir(), "permits.json")) + const id = "id_alpha" + + if err := book.SnapshotLegacy(id, []string{"dev_a", "dev_b"}); err != nil { + t.Fatal(err) + } + for _, legacyDev := range []string{"dev_a", "dev_b"} { + got, class := book.For(id, legacyDev) + if !got.Watch || got.Drive || class != ClassLegacy { + t.Fatalf("For(%q) = (%+v, %v), want Watch=true Drive=false ClassLegacy", legacyDev, got, class) + } + } + if got, class := book.For(id, "dev_c"); !got.Watch || !got.Drive || class != ClassNew { + t.Fatalf("For(\"dev_c\") = (%+v, %v), want Watch=true Drive=true ClassNew", got, class) + } + + if err := book.SnapshotLegacy(id, []string{"dev_a", "dev_b", "dev_c"}); err != nil { + t.Fatal(err) + } + if got, class := book.For(id, "dev_c"); !got.Watch || !got.Drive || class != ClassNew { + t.Fatalf("after second SnapshotLegacy, For(\"dev_c\") = (%+v, %v), want Watch=true Drive=true ClassNew", got, class) + } + + fresh := PermitsAt(filepath.Join(t.TempDir(), "fresh-permits.json")) + if err := fresh.SnapshotLegacy("id_beta", nil); err != nil { + t.Fatal(err) + } + for _, dev := range []string{"dev_a", "dev_b", "dev_c"} { + if got, class := fresh.For("id_beta", dev); !got.Watch || !got.Drive || class != ClassNew { + t.Fatalf("fresh For(%q) = (%+v, %v), want Watch=true Drive=true ClassNew", dev, got, class) + } + } +} + +// V25, V14: missing, unreadable, corrupt, foreign-identity, or unsnapshotted +// permit files all fail safe to watch-only legacy behavior without panicking. +func TestPermitBookFailsSafeToLegacyOnMissingCorruptForeignOrUnsnapshottedFiles(t *testing.T) { + dir := t.TempDir() + + // No file on disk. + absent := PermitsAt(filepath.Join(dir, "absent.json")) + if got, class := absent.For("id_alpha", "dev_a"); !got.Watch || got.Drive || class != ClassLegacy { + t.Fatalf("absent file: got (%+v, %v), want Watch=true Drive=false ClassLegacy", got, class) + } + + // Garbage JSON on disk. + garbagePath := filepath.Join(dir, "garbage.json") + if err := os.WriteFile(garbagePath, []byte("{not valid json"), 0o600); err != nil { + t.Fatal(err) + } + garbage := PermitsAt(garbagePath) + if got, class := garbage.For("id_alpha", "dev_a"); !got.Watch || got.Drive || class != ClassLegacy { + t.Fatalf("garbage file: got (%+v, %v), want Watch=true Drive=false ClassLegacy", got, class) + } + + // Valid file bound to another identity. + foreign := PermitsAt(filepath.Join(dir, "foreign.json")) + if err := foreign.SnapshotLegacy("id_other", nil); err != nil { + t.Fatal(err) + } + if err := foreign.Set("id_other", "dev_a", boolPtr(true), boolPtr(true), "person"); err != nil { + t.Fatal(err) + } + if got, class := foreign.For("id_alpha", "dev_a"); !got.Watch || got.Drive || class != ClassLegacy { + t.Fatalf("foreign identity file: got (%+v, %v), want Watch=true Drive=false ClassLegacy", got, class) + } + + // Valid file for the same identity with no snapshot yet. + noSnapPath := filepath.Join(dir, "nosnap.json") + if err := os.WriteFile(noSnapPath, []byte(`{"v":1,"identity":"id_alpha","legacy":[]}`), 0o600); err != nil { + t.Fatal(err) + } + noSnap := PermitsAt(noSnapPath) + if got, class := noSnap.For("id_alpha", "dev_a"); !got.Watch || got.Drive || class != ClassLegacy { + t.Fatalf("unsnapshotted file: got (%+v, %v), want Watch=true Drive=false ClassLegacy", got, class) + } +} + +// V11, V25: an explicit row overrides a device's legacy or new class, and +// Forget removes the explicit row so the device returns to its class. +func TestExplicitPermitBeatsClassAndForgetRestoresClass(t *testing.T) { + book := PermitsAt(filepath.Join(t.TempDir(), "permits.json")) + const id = "id_alpha" + + if err := book.SnapshotLegacy(id, []string{"dev_legacy"}); err != nil { + t.Fatal(err) + } + if err := book.Set(id, "dev_legacy", nil, boolPtr(true), "person"); err != nil { + t.Fatal(err) + } + if got, class := book.For(id, "dev_legacy"); !got.Watch || !got.Drive || class != ClassExplicit { + t.Fatalf("explicit override on legacy device: got (%+v, %v), want Watch=true Drive=true ClassExplicit", got, class) + } + + if err := book.Forget("dev_legacy"); err != nil { + t.Fatal(err) + } + if got, class := book.For(id, "dev_legacy"); !got.Watch || got.Drive || class != ClassLegacy { + t.Fatalf("after Forget on legacy device: got (%+v, %v), want Watch=true Drive=false ClassLegacy", got, class) + } + + if err := book.Set(id, "dev_new", nil, boolPtr(false), "person"); err != nil { + t.Fatal(err) + } + if got, class := book.For(id, "dev_new"); !got.Watch || got.Drive || class != ClassExplicit { + t.Fatalf("explicit override on new device: got (%+v, %v), want Watch=true Drive=false ClassExplicit", got, class) + } + if err := book.Forget("dev_new"); err != nil { + t.Fatal(err) + } + if got, class := book.For(id, "dev_new"); !got.Watch || !got.Drive || class != ClassNew { + t.Fatalf("after Forget on new device: got (%+v, %v), want Watch=true Drive=true ClassNew", got, class) + } +} + +// V25: NeedsAsk is true only when legacy devices exist and asked is empty; +// Asked stamps asked forever and grants drive only to listed legacy devices when allow is true. +func TestHomeAsksOnceForLegacyDevicesAndNeverAgain(t *testing.T) { + const id = "id_alpha" + + emptyBook := PermitsAt(filepath.Join(t.TempDir(), "empty.json")) + if emptyBook.NeedsAsk(id) { + t.Fatal("NeedsAsk was true before any snapshot") + } + if err := emptyBook.SnapshotLegacy(id, nil); err != nil { + t.Fatal(err) + } + if emptyBook.NeedsAsk(id) { + t.Fatal("NeedsAsk was true with no legacy devices") + } + + allowBook := PermitsAt(filepath.Join(t.TempDir(), "allow.json")) + if err := allowBook.SnapshotLegacy(id, []string{"dev_a", "dev_b"}); err != nil { + t.Fatal(err) + } + if !allowBook.NeedsAsk(id) { + t.Fatal("NeedsAsk was false with legacy devices and asked empty") + } + if err := allowBook.Asked(id, true, []string{"dev_a", "dev_not_legacy"}); err != nil { + t.Fatal(err) + } + if allowBook.NeedsAsk(id) { + t.Fatal("NeedsAsk remained true after Asked(allow=true)") + } + if got, class := allowBook.For(id, "dev_a"); !got.Watch || !got.Drive || class != ClassExplicit || got.By != "asked" { + t.Fatalf("dev_a after Asked(allow=true): got (%+v, %v), want explicit drive-on by \"asked\"", got, class) + } + if got, class := allowBook.For(id, "dev_b"); !got.Watch || got.Drive || class != ClassLegacy { + t.Fatalf("unlisted legacy dev_b after Asked(allow=true): got (%+v, %v), want ClassLegacy drive-off", got, class) + } + if got, class := allowBook.For(id, "dev_not_legacy"); !got.Watch || !got.Drive || class != ClassNew { + t.Fatalf("non-legacy device listed in Asked: got (%+v, %v), want ClassNew (no explicit row)", got, class) + } + + denyBook := PermitsAt(filepath.Join(t.TempDir(), "deny.json")) + if err := denyBook.SnapshotLegacy(id, []string{"dev_a"}); err != nil { + t.Fatal(err) + } + if !denyBook.NeedsAsk(id) { + t.Fatal("NeedsAsk was false before Asked(allow=false)") + } + if err := denyBook.Asked(id, false, nil); err != nil { + t.Fatal(err) + } + if denyBook.NeedsAsk(id) { + t.Fatal("NeedsAsk remained true after Asked(allow=false)") + } + if got, class := denyBook.For(id, "dev_a"); !got.Watch || got.Drive || class != ClassLegacy { + t.Fatalf("dev_a after Asked(allow=false): got (%+v, %v), want unchanged ClassLegacy", got, class) + } +} + +// V25: writing the permit book enforces 0600 file and 0700 directory modes, +// persists no path separators in any JSON string or key, and leaves no temp file behind. +func TestPermitBookDiskModesNoPathsAndNoTempFileLeftBehind(t *testing.T) { + dir := filepath.Join(t.TempDir(), "v3", "remote") + path := filepath.Join(dir, "permits.json") + book := PermitsAt(path) + const id = "id_alpha" + + if err := book.SnapshotLegacy(id, []string{"dev_a"}); err != nil { + t.Fatal(err) + } + if err := book.Set(id, "dev_b", boolPtr(true), boolPtr(false), "person"); err != nil { + t.Fatal(err) + } + if err := book.Asked(id, true, []string{"dev_a"}); err != nil { + t.Fatal(err) + } + + if _, err := os.Stat(path + ".new"); !os.IsNotExist(err) { + t.Fatalf("temporary file %s.new still exists (err=%v)", path, err) + } + if runtime.GOOS != "windows" { + fileInfo, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if got := fileInfo.Mode().Perm(); got != 0o600 { + t.Fatalf("file mode = %04o, want 0600", got) + } + dirInfo, err := os.Stat(dir) + if err != nil { + t.Fatal(err) + } + if got := dirInfo.Mode().Perm(); got != 0o700 { + t.Fatalf("dir mode = %04o, want 0700", got) + } + } + + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var doc any + if err := json.Unmarshal(raw, &doc); err != nil { + t.Fatal(err) + } + var checkNoSlash func(v any) + checkNoSlash = func(v any) { + switch val := v.(type) { + case string: + if strings.Contains(val, "/") || strings.Contains(val, `\`) { + t.Fatalf("persisted JSON string %q contains a path separator", val) + } + case []any: + for _, item := range val { + checkNoSlash(item) + } + case map[string]any: + for k, item := range val { + if strings.Contains(k, "/") || strings.Contains(k, `\`) { + t.Fatalf("persisted JSON key %q contains a path separator", k) + } + checkNoSlash(item) + } + } + } + checkNoSlash(doc) +} + +// V11: concurrent Set calls across eight goroutines are serialized so every device row lands. +func TestPermitBookConcurrentSetsAcrossEightGoroutinesAllLand(t *testing.T) { + book := PermitsAt(filepath.Join(t.TempDir(), "permits.json")) + const id = "id_alpha" + const workers = 8 + + var wg sync.WaitGroup + errs := make(chan error, workers) + for i := range workers { + dev := fmt.Sprintf("dev_%d", i) + drive := i%2 == 0 + wg.Add(1) + go func(dev string, drive bool) { + defer wg.Done() + if err := book.Set(id, dev, boolPtr(true), boolPtr(drive), "person"); err != nil { + errs <- err + } + }(dev, drive) + } + wg.Wait() + close(errs) + for err := range errs { + t.Fatal(err) + } + + for i := range workers { + dev := fmt.Sprintf("dev_%d", i) + wantDrive := i%2 == 0 + got, class := book.For(id, dev) + if class != ClassExplicit || !got.Watch || got.Drive != wantDrive { + t.Fatalf("For(%q) = (%+v, %v), want Watch=true Drive=%v ClassExplicit", dev, got, class, wantDrive) + } + } +} + +// V11: Watch fires when another PermitBook instance writes the file, stays +// quiet when nothing changes, and returns when its context is canceled. +func TestPermitBookWatchFiresOnExternalWriteAndStopsOnCancel(t *testing.T) { + prev := permitPollInterval + permitPollInterval = 5 * time.Millisecond + t.Cleanup(func() { permitPollInterval = prev }) + + path := filepath.Join(t.TempDir(), "permits.json") + writer := PermitsAt(path) + if err := writer.SnapshotLegacy("id_alpha", []string{"dev_a"}); err != nil { + t.Fatal(err) + } + + watcher := PermitsAt(path) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + var count atomic.Int32 + fired := make(chan struct{}, 8) + done := make(chan struct{}) + go func() { + defer close(done) + watcher.Watch(ctx, 0, func() { + count.Add(1) + select { + case fired <- struct{}{}: + default: + } + }) + }() + + // Wait across several poll intervals with no write: changed must not fire. + select { + case <-fired: + t.Fatal("Watch fired when nothing changed") + case <-time.After(25 * time.Millisecond): + } + + // Write through another PermitBook instance: changed must fire once. + if err := writer.Set("id_alpha", "dev_a", boolPtr(true), boolPtr(true), "person"); err != nil { + t.Fatal(err) + } + select { + case <-fired: + case <-time.After(time.Second): + t.Fatal("Watch did not fire after another PermitBook wrote") + } + + // Wait across several more poll intervals without writing: no second fire. + select { + case <-fired: + t.Fatalf("Watch fired again without another write (count=%d)", count.Load()) + case <-time.After(25 * time.Millisecond): + } + + cancel() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("Watch did not return after context cancellation") + } +} + +// V25: a computer that finishes Join or JoinByLink stamps permits.json with an +// empty legacy list so every device it later meets defaults to ClassNew (drive on). +func TestJoiningStampsAnEmptyLegacySnapshotSoLaterDevicesAreNew(t *testing.T) { + t.Run("code join", func(t *testing.T) { + r := newChatRig(t) + t.Setenv("CODEAF_HOME", r.homeB) + ctx := context.Background() + a, b := newScreen(), newScreen() + done := r.offer(ctx, a) + code := a.nextCode(t) + + if _, err := r.join(ctx, r.homeB, code.Shown(), b); err != nil { + t.Fatal(err) + } + if end := within(t, done); end.err != nil { + t.Fatal(end.err) + } + + permitPath := filepath.Join(r.homeB, "v3", "remote", "permits.json") + raw, err := os.ReadFile(permitPath) + if err != nil { + t.Fatalf("permits.json not written on code join: %v", err) + } + var f permitFile + if err := json.Unmarshal(raw, &f); err != nil { + t.Fatal(err) + } + if f.Identity != r.a.ID() || f.Since == "" || len(f.Legacy) != 0 { + t.Fatalf("code join permit file = %+v, want identity=%s non-empty since and empty legacy", f, r.a.ID()) + } + if Permits().NeedsAsk(r.a.ID()) { + t.Fatal("NeedsAsk was true on a freshly joined computer") + } + if got, class := Permits().For(r.a.ID(), "dev_later"); !got.Watch || !got.Drive || class != ClassNew { + t.Fatalf("For(\"dev_later\") after code join = (%+v, %v), want Watch=true Drive=true ClassNew", got, class) + } + }) + + t.Run("link join", func(t *testing.T) { + r := newLinkRig(t) + t.Setenv("CODEAF_HOME", r.new) + ui, done := r.start(t, context.Background()) + in := waitInvite(t, ui) + ref, err := ReadLink(in.Ref.Token()) + if err != nil { + t.Fatal(err) + } + asking, err := r.approver.Look(context.Background(), ref) + if err != nil { + t.Fatal(err) + } + if err := r.approver.Approve(context.Background(), asking); err != nil { + t.Fatal(err) + } + if res := waitResult(t, done); res.err != nil { + t.Fatal(res.err) + } + + idID := r.approver.Identity.ID() + permitPath := filepath.Join(r.new, "v3", "remote", "permits.json") + raw, err := os.ReadFile(permitPath) + if err != nil { + t.Fatalf("permits.json not written on link join: %v", err) + } + var f permitFile + if err := json.Unmarshal(raw, &f); err != nil { + t.Fatal(err) + } + if f.Identity != idID || f.Since == "" || len(f.Legacy) != 0 { + t.Fatalf("link join permit file = %+v, want identity=%s non-empty since and empty legacy", f, idID) + } + if Permits().NeedsAsk(idID) { + t.Fatal("NeedsAsk was true on a freshly link-joined computer") + } + if got, class := Permits().For(idID, "dev_later"); !got.Watch || !got.Drive || class != ClassNew { + t.Fatalf("For(\"dev_later\") after link join = (%+v, %v), want Watch=true Drive=true ClassNew", got, class) + } + }) +} + +// V25, the offering side: the computer that was alone and now shares its chats +// records that everyone it meets next is a new pairing, so the first computer a +// person ever pairs types out of the box. A computer that already had a fleet +// keeps its older pairings older. +func TestTheComputerThatOffersAPairingRecordsThatTheNextOnesAreNew(t *testing.T) { + t.Run("a computer that was alone", func(t *testing.T) { + dir := t.TempDir() + id, err := identity.EnsureSolo(dir) + if err != nil { + t.Fatal(err) + } + book := PermitsAt(filepath.Join(dir, "permits.json")) + if err := EndSoloAt(dir, book); err != nil { + t.Fatal(err) + } + if identity.Solo(dir) { + t.Fatal("the computer still says it is alone after it shared its chats") + } + // The first full read of a roster that now holds the other computer must + // not take it for an older pairing. + if err := book.SnapshotLegacy(id.ID(), []string{"dev_host", "dev_laptop"}); err != nil { + t.Fatal(err) + } + if got, class := book.For(id.ID(), "dev_laptop"); !got.Watch || !got.Drive || class != ClassNew { + t.Fatalf("the first computer paired is (%+v, %v), want Watch=true Drive=true ClassNew", got, class) + } + if book.NeedsAsk(id.ID()) { + t.Fatal("the computer asks whether its first pairing may type, which it never was told to refuse") + } + }) + + t.Run("a computer that already had other computers", func(t *testing.T) { + dir := t.TempDir() + id, err := identity.Ensure(dir) + if err != nil { + t.Fatal(err) + } + if identity.Solo(dir) { + t.Fatal("the fixture's identity is solo, so it does not stand for a fleet") + } + book := PermitsAt(filepath.Join(dir, "permits.json")) + if err := EndSoloAt(dir, book); err != nil { + t.Fatal(err) + } + if err := book.SnapshotLegacy(id.ID(), []string{"dev_host", "dev_old"}); err != nil { + t.Fatal(err) + } + if got, class := book.For(id.ID(), "dev_old"); got.Drive || class != ClassLegacy { + t.Fatalf("an older pairing is (%+v, %v) after another computer was offered a pairing, want watch only and legacy", got, class) + } + }) +} diff --git a/internal/pair/permits.go b/internal/pair/permits.go new file mode 100644 index 0000000000..3d93dc91ce --- /dev/null +++ b/internal/pair/permits.go @@ -0,0 +1,386 @@ +package pair + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/fsreplace" + "github.com/Agent-Field/codeaf/internal/identity" +) + +// Permit records whether one paired computer may watch and type into chats +// hosted on this computer, who set that choice, and when. +type Permit struct { + Watch, Drive bool + By string + At time.Time +} + +// PermitClass tells how a device's effective permit was decided. +type PermitClass int + +const ( + // ClassExplicit means a row in permits.json names this device directly. + ClassExplicit PermitClass = iota + // ClassLegacy means the device was already paired before remote control + // took its first roster snapshot, or the permit file cannot be trusted yet. + ClassLegacy + // ClassNew means the device joined after the host's legacy snapshot was recorded. + ClassNew +) + +// permitPollInterval is the default polling period for PermitBook.Watch so +// tests can shrink it without sleeping on a wall-clock second. +var permitPollInterval = time.Second + +// PermitBook is the host-local record of per-device watch and drive permissions. +// +// THIS FILE LIVES ONLY ON THE HOST AND NEVER TRAVELS THROUGH SYNC OR THE +// DIRECTORY. A permission about what another computer may run here is a local +// decision of the machine that runs the tools, separate from the whole-machine +// book that codeaf serve reads. +type PermitBook struct { + path string + + mu sync.Mutex +} + +// Permits is the permit book in the default state directory. +func Permits() *PermitBook { + return PermitsAt(filepath.Join(Dir(), "permits.json")) +} + +// PermitsAt opens the permit book at an explicit file path. +func PermitsAt(path string) *PermitBook { + return &PermitBook{path: path} +} + +type permitDefaults struct { + Watch bool `json:"watch"` + Drive bool `json:"drive"` +} + +type permitRow struct { + Watch bool `json:"watch"` + Drive bool `json:"drive"` + By string `json:"by,omitempty"` + At time.Time `json:"at,omitempty"` +} + +type permitFile struct { + V int `json:"v"` + Identity string `json:"identity"` + Since string `json:"since,omitempty"` + Legacy []string `json:"legacy"` + New *permitDefaults `json:"new,omitempty"` + Asked string `json:"asked,omitempty"` + Devices map[string]permitRow `json:"devices,omitempty"` +} + +func legacyPermit() (Permit, PermitClass) { + return Permit{Watch: true, Drive: false}, ClassLegacy +} + +func (f permitFile) effectiveFor(identity, device string) (Permit, PermitClass) { + if identity == "" || device == "" || f.Identity == "" || f.Identity != identity { + return legacyPermit() + } + if row, ok := f.Devices[device]; ok { + return Permit{Watch: row.Watch, Drive: row.Drive, By: row.By, At: row.At}, ClassExplicit + } + if f.Since == "" { + return legacyPermit() + } + if slices.Contains(f.Legacy, device) { + return legacyPermit() + } + watch, drive := true, true + if f.New != nil { + watch, drive = f.New.Watch, f.New.Drive + } + return Permit{Watch: watch, Drive: drive}, ClassNew +} + +// For returns the effective watch and drive permission for device under identity. +// Any missing, unreadable, foreign, or unsnapshotted file fails safe to watch-only +// legacy behavior so an older pairing never gains drive access by accident. +func (b *PermitBook) For(identity, device string) (Permit, PermitClass) { + b.mu.Lock() + defer b.mu.Unlock() + var f permitFile + if ok, err := b.read(&f); err != nil || !ok { + return legacyPermit() + } + return f.effectiveFor(identity, device) +} + +// Set records an explicit permit row for device under identity, changing only +// the fields whose pointer is non-nil and starting from the device's current +// effective permit. Writing for a different identity rebinds the file because +// an identity rotation or replacement changes every device identifier. +func (b *PermitBook) Set(identity, device string, watch, drive *bool, by string) error { + b.mu.Lock() + defer b.mu.Unlock() + var f permitFile + _, _ = b.read(&f) + if f.Identity != identity { + f = freshPermitFile(identity) + } + cur, _ := f.effectiveFor(identity, device) + if watch != nil { + cur.Watch = *watch + } + if drive != nil { + cur.Drive = *drive + } + if f.Devices == nil { + f.Devices = make(map[string]permitRow) + } + f.Devices[device] = permitRow{ + Watch: cur.Watch, + Drive: cur.Drive, + By: by, + At: time.Now().UTC(), + } + return b.write(f) +} + +// SnapshotLegacy records the one-time list of devices that were already paired +// when this computer first enabled permits for identity. Once written for an +// identity, a later call is a no-op so newly paired devices stay ClassNew. +func (b *PermitBook) SnapshotLegacy(identity string, roster []string) error { + b.mu.Lock() + defer b.mu.Unlock() + var f permitFile + _, _ = b.read(&f) + if f.Identity != identity { + f = freshPermitFile(identity) + } + if f.Since != "" { + return nil + } + f.Since = time.Now().UTC().Format(time.RFC3339Nano) + f.Legacy = make([]string, 0, len(roster)) + for _, dev := range roster { + if dev != "" && !slices.Contains(f.Legacy, dev) { + f.Legacy = append(f.Legacy, dev) + } + } + return b.write(f) +} + +// NeedsAsk reports whether this host should show the one-time prompt asking +// whether legacy paired computers may type into chats here. +func (b *PermitBook) NeedsAsk(identity string) bool { + b.mu.Lock() + defer b.mu.Unlock() + var f permitFile + if ok, err := b.read(&f); err != nil || !ok { + return false + } + if identity == "" || f.Identity != identity || f.Since == "" { + return false + } + return f.Asked == "" && len(f.Legacy) > 0 +} + +// Asked records that the one-time legacy prompt was answered, and when allow is +// true grants drive permission to each listed device that belongs to the legacy snapshot. +func (b *PermitBook) Asked(identity string, allow bool, devices []string) error { + b.mu.Lock() + defer b.mu.Unlock() + var f permitFile + _, _ = b.read(&f) + if f.Identity != identity { + f = freshPermitFile(identity) + } + now := time.Now().UTC() + f.Asked = now.Format(time.RFC3339Nano) + if allow { + if f.Devices == nil { + f.Devices = make(map[string]permitRow) + } + for _, dev := range devices { + if slices.Contains(f.Legacy, dev) { + f.Devices[dev] = permitRow{ + Watch: true, + Drive: true, + By: "asked", + At: now, + } + } + } + } + return b.write(f) +} + +// Forget removes any explicit row for device so it returns to its snapshot class. +func (b *PermitBook) Forget(device string) error { + b.mu.Lock() + defer b.mu.Unlock() + var f permitFile + ok, err := b.read(&f) + if err != nil { + return err + } + if !ok { + return nil + } + if _, exists := f.Devices[device]; !exists { + return nil + } + delete(f.Devices, device) + return b.write(f) +} + +type permitFileStamp struct { + exists bool + size int64 + modTime time.Time +} + +func statPermitFile(path string) permitFileStamp { + info, err := os.Stat(path) + if err != nil { + return permitFileStamp{} + } + return permitFileStamp{ + exists: true, + size: info.Size(), + modTime: info.ModTime(), + } +} + +func (s permitFileStamp) same(other permitFileStamp) bool { + return s.exists == other.exists && s.size == other.size && s.modTime.Equal(other.modTime) +} + +// Watch polls the permit file's modification time and size until ctx is done, +// calling changed whenever either differs from the previous observation. +func (b *PermitBook) Watch(ctx context.Context, interval time.Duration, changed func()) { + if interval <= 0 { + interval = permitPollInterval + } + last := statPermitFile(b.path) + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + cur := statPermitFile(b.path) + if !cur.same(last) { + last = cur + if changed != nil { + changed() + } + } + } + } +} + +func freshPermitFile(identity string) permitFile { + return permitFile{ + V: 1, + Identity: identity, + Legacy: []string{}, + New: &permitDefaults{Watch: true, Drive: true}, + Devices: make(map[string]permitRow), + } +} + +func (b *PermitBook) read(into *permitFile) (bool, error) { + var raw []byte + err := fsreplace.Retry(func() error { + var err error + raw, err = os.ReadFile(b.path) + return err + }) + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + if err != nil { + return false, err + } + if len(strings.TrimSpace(string(raw))) == 0 { + return false, nil + } + if err := json.Unmarshal(raw, into); err != nil { + return false, fmt.Errorf("%s is not readable any more: %w", b.path, err) + } + return true, nil +} + +func (b *PermitBook) write(what permitFile) error { + if what.V == 0 { + what.V = 1 + } + if what.Legacy == nil { + what.Legacy = []string{} + } + if what.New == nil { + what.New = &permitDefaults{Watch: true, Drive: true} + } + dir := filepath.Dir(b.path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + _ = os.Chmod(dir, 0o700) + raw, err := json.MarshalIndent(what, "", " ") + if err != nil { + return err + } + // The permit book controls which remote devices may drive tools on this + // computer, so it is owner-only and replaced atomically through a temp file. + temporary := b.path + ".new" + if err := os.WriteFile(temporary, append(raw, '\n'), 0o600); err != nil { + return err + } + _ = os.Chmod(temporary, 0o600) + return fsreplace.Rename(temporary, b.path) +} + +// stampJoin records an empty legacy snapshot after a computer joins an +// identity so every device it later meets defaults to ClassNew. +func stampJoin(identity string) { + if identity == "" { + return + } + _ = Permits().SnapshotLegacy(identity, nil) +} + +// EndSoloAt is [identity.EndSolo] for the computer that OFFERS a pairing, and the +// other half of what [stampJoin] does for the one that joins. A computer that was +// alone has no older pairing: every computer it meets from this moment is a new one, +// so it writes the empty legacy snapshot now, before the first of them is on its +// roster. WITHOUT THIS THE FIRST PAIRING OF EVERY PERSON WAS AN OLDER ONE: the +// computer read its roster for the first time after the other had joined, took the +// other for something that was already there, and left it watching and unable to +// type until the person said otherwise. +// +// A computer that was not alone is left as it was, because the computers already on +// its roster ARE older pairings and its first roster read names them. A failure to +// write the snapshot is not a failure to pair: the computer then stays on the safe +// side, watch only. +func EndSoloAt(dir string, book *PermitBook) error { + alone := identity.Solo(dir) + if err := identity.EndSolo(dir); err != nil { + return err + } + if !alone || book == nil { + return nil + } + if id, err := identity.Load(dir); err == nil && id.ID() != "" { + _ = book.SnapshotLegacy(id.ID(), nil) + } + return nil +} diff --git a/internal/pair/permits_home_test.go b/internal/pair/permits_home_test.go new file mode 100644 index 0000000000..f1c8eca3e5 --- /dev/null +++ b/internal/pair/permits_home_test.go @@ -0,0 +1,65 @@ +package pair + +import ( + "os" + "testing" + + "github.com/Agent-Field/codeaf/internal/home" + "github.com/Agent-Field/codeaf/internal/identity" +) + +// C2: the permit book is remote control's own file in a home, written on the +// computer that offers a pairing and on the one that joins. It must never make +// that home count as having local work: a computer that was paired, and then +// left alone, still has to be able to join another set of computers, and a home +// that was only started must still look unused after the book is written. +func TestThePermitBookNeverMakesAHomeLookUsed(t *testing.T) { + dir := t.TempDir() + t.Setenv(home.EnvVar, dir) + if _, err := identity.EnsureSolo(dir); err != nil { + t.Fatal(err) + } + // The computer that offers writes the empty legacy snapshot the moment its + // solo state ends, through the same call the app and the terminal make. + if err := EndSoloAt(dir, Permits()); err != nil { + t.Fatal(err) + } + id, err := identity.Load(dir) + if err != nil { + t.Fatal(err) + } + // And a choice the person made about one computer, so the book holds rows + // as well as the snapshot. + yes := true + if err := Permits().Set(id.ID(), "another-computer", &yes, &yes, "test"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(Permits().path); err != nil { + t.Fatalf("the permit book was not written, so this proves nothing: %v", err) + } + if ok, err := identity.Pristine(dir); err != nil || !ok { + t.Fatalf("the permit book made a home that was only started look used: pristine=%v err=%v", ok, err) + } + if ok, err := identity.Joinable(dir); err != nil || !ok { + t.Fatalf("the permit book blocked a join: joinable=%v err=%v", ok, err) + } +} + +// The joining computer writes its book after it has kept the grant, under the +// identity it joined. That must not count either: the same home can be removed +// from the set later and join another. +func TestAComputerThatJoinedStillLooksUnusedWithItsBook(t *testing.T) { + dir := t.TempDir() + t.Setenv(home.EnvVar, dir) + id, err := identity.Ensure(dir) + if err != nil { + t.Fatal(err) + } + stampJoin(id.ID()) + if _, err := os.Stat(Permits().path); err != nil { + t.Fatalf("the join did not write the book, so this proves nothing: %v", err) + } + if ok, err := identity.Joinable(dir); err != nil || !ok { + t.Fatalf("the book a join wrote blocked the next join: joinable=%v err=%v", ok, err) + } +} diff --git a/internal/pair/record_write_test.go b/internal/pair/record_write_test.go new file mode 100644 index 0000000000..b35aa5efbe --- /dev/null +++ b/internal/pair/record_write_test.go @@ -0,0 +1,126 @@ +package pair + +import ( + "bytes" + "crypto/ecdh" + "crypto/rand" + "encoding/binary" + "io" + "net" + "testing" + "time" +) + +// countingWriter remembers every call to Write, so a test can say how many +// messages a record became on a stream that sends one message per write. +type countingWriter struct { + writes [][]byte +} + +func (c *countingWriter) Write(p []byte) (int, error) { + c.writes = append(c.writes, append([]byte(nil), p...)) + return len(p), nil +} + +// D21 / V35: a record is ONE write, and the bytes it puts on the wire are the +// same bytes the old prefix-then-body pair of writes produced, so a build with +// either behaviour reads the other's records. +func TestARecordIsOneWrite(t *testing.T) { + for _, size := range []int{0, 1, 31, 4096, maxRecord} { + body := bytes.Repeat([]byte{0xA5}, size) + var counted countingWriter + if err := writeRecord(&counted, body); err != nil { + t.Fatalf("a %d-byte record: %v", size, err) + } + if len(counted.writes) != 1 { + t.Fatalf("a %d-byte record took %d writes, want exactly 1", size, len(counted.writes)) + } + var prefix [2]byte + binary.BigEndian.PutUint16(prefix[:], uint16(size)) + want := append(prefix[:], body...) + if !bytes.Equal(counted.writes[0], want) { + t.Fatalf("a %d-byte record's bytes are not the two-byte big-endian length then the body", size) + } + got, err := readRecord(bytes.NewReader(counted.writes[0])) + if err != nil { + t.Fatalf("a %d-byte record does not read back: %v", size, err) + } + if size == 0 { + if len(got) != 0 { + t.Fatalf("an empty record read back %d bytes", len(got)) + } + } else if !bytes.Equal(got, body) { + t.Fatalf("a %d-byte record read back different bytes", size) + } + } + if err := writeRecord(&countingWriter{}, make([]byte, maxRecord+1)); err == nil { + t.Fatal("a record over the Noise ceiling was written") + } +} + +// D8 / V38: the direct road has its own intent byte and its own prologue, so a +// stream made for the direct road completes only against the direct prologue +// and never against the relay's live door or the files door. +func TestTheDirectIntentSelectsItsOwnPrologueAndNoOtherCompletesIt(t *testing.T) { + a, err := ecdh.X25519().GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + b, err := ecdh.X25519().GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + prologues := map[byte]string{ + IntentFiles: "codeaf files door v1 connect", + IntentLive: "codeaf live door v1 connect", + IntentDirect: "codeaf live door v1 direct", + } + if IntentDirect == IntentLive || IntentDirect == IntentFiles { + t.Fatal("the direct intent shares a byte with another door") + } + + attempt := func(intent byte, prologue string) (client *Tunnel, serverIntent byte, clientErr, serverErr error) { + near, far := net.Pipe() + defer near.Close() + defer far.Close() + _ = near.SetDeadline(time.Now().Add(3 * time.Second)) + _ = far.SetDeadline(time.Now().Add(3 * time.Second)) + type accepted struct { + intent byte + err error + } + done := make(chan accepted, 1) + go func() { + defer far.Close() + tun, got, err := AcceptWithKeyPrologues(far, b, nil, prologues) + if tun != nil { + // The stream must carry bytes both ways once it completes. + buf := make([]byte, 2) + _, err = io.ReadFull(tun, buf) + } + done <- accepted{intent: got, err: err} + }() + client, clientErr = ConnectWithKeyIntent(near, b.PublicKey().Bytes(), a, intent, prologue) + if client != nil { + _, _ = client.Write([]byte("ok")) + } + res := <-done + return client, res.intent, clientErr, res.err + } + + client, got, clientErr, serverErr := attempt(IntentDirect, prologues[IntentDirect]) + if clientErr != nil || serverErr != nil || client == nil { + t.Fatalf("the direct intent with the direct prologue did not complete: client %v, server %v", clientErr, serverErr) + } + if got != IntentDirect { + t.Fatalf("the responder saw intent %q, want %q", got, IntentDirect) + } + for _, wrong := range []string{prologues[IntentLive], prologues[IntentFiles]} { + if _, _, clientErr, serverErr := attempt(IntentDirect, wrong); clientErr == nil || serverErr == nil { + t.Fatalf("the direct intent completed with the prologue %q (client %v, server %v)", wrong, clientErr, serverErr) + } + } + if _, _, clientErr, serverErr := attempt(IntentLive, prologues[IntentDirect]); clientErr == nil || serverErr == nil { + t.Fatalf("the live intent completed with the direct prologue (client %v, server %v)", clientErr, serverErr) + } +} diff --git a/internal/pair/serve.go b/internal/pair/serve.go index 203179739a..de9c0fd549 100644 --- a/internal/pair/serve.go +++ b/internal/pair/serve.go @@ -75,7 +75,7 @@ const steadyAfter = time.Minute // TooManyRegistrationsLine is what `codeaf serve` prints when the relay turns // registrations away at its per-minute ceiling. -const TooManyRegistrationsLine = "the sync service is turning registrations away right now — waiting before trying again" +const TooManyRegistrationsLine = "the relay is turning registrations away right now — waiting before trying again" // LostSyncLine is what `codeaf serve` prints, once per outage, when its // connection to the relay is lost and it starts trying again. @@ -100,6 +100,20 @@ func (h *Host) handshakeWithin() time.Duration { return HandshakeWithin } +// spread is how long to actually wait at a point in a back-off schedule. A +// relay restart drops every machine and every viewer in the same instant, and +// a schedule that is exactly one second then two then four brings them all +// back in the same instants too, into a relay that counts registrations per +// minute. The first wait after a drop is therefore [relay.FirstRetry], and +// every later one is the schedule's own wait scaled by [relay.Jitter], so the +// caps keep their meaning on average and no two machines keep step. +func spread(schedule time.Duration, first bool) time.Duration { + if first { + return relay.FirstRetry() + } + return relay.Jitter(schedule) +} + func (h *Host) wait(ctx context.Context, d time.Duration) error { if h.sleep != nil { return h.sleep(ctx, d) @@ -156,12 +170,15 @@ func (h *Host) sayBanner(line string, force bool) { // again cannot fix. func (h *Host) Run(ctx context.Context) error { if strings.TrimSpace(h.Service) == "" { - return errors.New("no sync service is set up on this machine, so there is nowhere to be reachable from — set " + RelayEnv + " to your sync service") + return errors.New("no relay is set up on this machine, so there is nowhere to be reachable from — set " + RelayEnv + " to your relay") } if h.Desk != nil && h.Desk.Now == nil && h.Now != nil { h.Desk.Now = h.Now } + // wait is the back-off schedule, doubled after each wait and capped at a + // minute. It is never slept as it stands: see [spread]. wait := time.Second + first := true announced := false // told and throttled are each said once per spell, not once per retry. // told is set when the person has been told sync was lost and not yet @@ -241,13 +258,15 @@ func (h *Host) Run(ctx context.Context) error { // backing off instead of hammering the relay every second. if h.now().Sub(since) >= steadyAfter { wait = time.Second + first = true throttled = false } } - if err := h.wait(ctx, wait); err != nil { + if err := h.wait(ctx, spread(wait, first)); err != nil { return nil } + first = false if wait *= 2; wait > time.Minute { wait = time.Minute } diff --git a/internal/pair/tunnel.go b/internal/pair/tunnel.go index a97580621a..77e0352ffd 100644 --- a/internal/pair/tunnel.go +++ b/internal/pair/tunnel.go @@ -78,13 +78,20 @@ func ConnectWithKey(conn io.ReadWriteCloser, peer []byte, key *ecdh.PrivateKey) // door can never complete against a door of a different kind, even when a // caller hands both the same static key. It must not be empty. func ConnectWithKeyPrologue(conn io.ReadWriteCloser, peer []byte, key *ecdh.PrivateKey, prologue string) (*Tunnel, error) { + return ConnectWithKeyIntent(conn, peer, key, IntentFiles, prologue) +} + +// ConnectWithKeyIntent is ConnectWithKeyPrologue when a registration serves +// more than one door and the first byte on the stream selects which prologue +// the responder runs. +func ConnectWithKeyIntent(conn io.ReadWriteCloser, peer []byte, key *ecdh.PrivateKey, intent byte, prologue string) (*Tunnel, error) { if key == nil { return nil, errors.New("pair: an identity tunnel needs a static key") } if prologue == "" { return nil, errors.New("pair: an identity tunnel needs a prologue") } - return connectTaskTunnel(conn, peer, Device{private: key}.noiseKey(), "", prologue) + return connectTaskTunnel(conn, peer, Device{private: key}.noiseKey(), intent, "", prologue) } // AcceptWithKey answers an identity task tunnel. Device authorization follows @@ -102,15 +109,31 @@ func AcceptWithKeyPrologue(conn io.ReadWriteCloser, key *ecdh.PrivateKey, prolog if prologue == "" { return nil, errors.New("pair: an identity tunnel needs a prologue") } + tunnel, _, err := AcceptWithKeyPrologues(conn, key, nil, map[byte]string{IntentFiles: prologue}) + return tunnel, err +} + +// AcceptWithKeyPrologues answers an identity tunnel on a registration that may +// carry more than one intent byte. An intent without a prologue or one that +// admit refuses closes the stream before a single byte is written back. +func AcceptWithKeyPrologues(conn io.ReadWriteCloser, key *ecdh.PrivateKey, admit func(intent byte) bool, prologues map[byte]string) (*Tunnel, byte, error) { + if key == nil { + return nil, 0, errors.New("pair: an identity tunnel needs a static key") + } + if len(prologues) == 0 { + return nil, 0, errors.New("pair: an identity tunnel needs a prologue") + } var intent [1]byte if _, err := io.ReadFull(conn, intent[:]); err != nil { - return nil, err + return nil, 0, err } - if intent[0] != intentConnect { - return nil, errors.New("this door takes identity connections") + prologue := prologues[intent[0]] + if prologue == "" || (admit != nil && !admit(intent[0])) { + _ = conn.Close() + return nil, intent[0], errors.New("this door takes identity connections") } tunnel, _, err := acceptTaskTunnel(conn, Device{private: key}.noiseKey(), func([]byte, string) error { return nil }, prologue) - return tunnel, err + return tunnel, intent[0], err } // Read hands back plaintext. A record arrives whole and is drained across as @@ -264,8 +287,8 @@ func acceptAsMachine(conn io.ReadWriteCloser, me Device, allow func(key []byte, return &Tunnel{conn: conn, peer: deviceKey, send: second, recv: first}, deviceKey, nil } -func connectTaskTunnel(conn io.ReadWriteCloser, machineKey []byte, static noise.DHKey, label, prologue string) (*Tunnel, error) { - if _, err := conn.Write([]byte{intentConnect}); err != nil { +func connectTaskTunnel(conn io.ReadWriteCloser, machineKey []byte, static noise.DHKey, intent byte, label, prologue string) (*Tunnel, error) { + if _, err := conn.Write([]byte{intent}); err != nil { return nil, err } handshake, err := noise.NewHandshakeState(noise.Config{ diff --git a/internal/pair/wire.go b/internal/pair/wire.go index 41383badfb..6505ed97a2 100644 --- a/internal/pair/wire.go +++ b/internal/pair/wire.go @@ -21,6 +21,21 @@ import ( const ( intentPair byte = 'P' intentConnect byte = 'C' + + // IntentFiles is the first byte a files-door or task-door connection writes, + // matching the original connect byte so older builds and newer builds speak + // the same wire without negotiation. + IntentFiles byte = intentConnect + // IntentLive is the first byte a live-view stream writes on the files-door + // registration so the host can separate live views from file transfers before + // starting Noise. + IntentLive byte = 'L' + // IntentDirect is the first byte a viewer writes on a peer-to-peer data + // channel, where the files door's own prologue map selects the direct road's + // prologue. It is a different byte from IntentLive on purpose: a stream + // made for the relay can never complete against the direct road, and the + // host decides the road from this byte, never from anything the viewer says. + IntentDirect byte = 'D' ) // maxRecord is a Noise message's own ceiling, and therefore this framing's. @@ -30,19 +45,22 @@ const maxRecord = 65535 // AEAD tag. const maxPlain = maxRecord - 16 +// writeRecord sends one length-prefixed record in ONE write. +// +// THE PREFIX AND THE BODY GO TOGETHER because the stream underneath may be +// message-oriented: a relay carrier bills a message per write and a peer-to-peer +// data channel sends one message per write, so the old two writes doubled the +// message count of every record on both. The bytes on the wire are exactly the +// ones the two writes produced, so a build that still writes two reads this +// one and the other way round. func writeRecord(w io.Writer, body []byte) error { if len(body) > maxRecord { return fmt.Errorf("pair: a %d-byte record is over the %d-byte limit", len(body), maxRecord) } - var prefix [2]byte - binary.BigEndian.PutUint16(prefix[:], uint16(len(body))) - if _, err := w.Write(prefix[:]); err != nil { - return err - } - if len(body) == 0 { - return nil - } - _, err := w.Write(body) + record := make([]byte, 2+len(body)) + binary.BigEndian.PutUint16(record, uint16(len(body))) + copy(record[2:], body) + _, err := w.Write(record) return err } diff --git a/internal/relay/breaker.go b/internal/relay/breaker.go new file mode 100644 index 0000000000..b67fb25749 --- /dev/null +++ b/internal/relay/breaker.go @@ -0,0 +1,54 @@ +package relay + +// THE ABUSE BREAKER FOR A LIVE STREAM. It is the relay's one answer to a surface +// that sends more than any live view ever does, and it is computed from the +// clock of the chunk that arrives: no timer and no goroutine stand behind it. +// The hosted relay has the same rule for the same reason, which is that a timer +// is exactly what would keep an idle object awake, and its twin is +// relay/hosted/src/engine/breaker.js, under the same two numbers. +// +// IT CUTS AND DOES NOT SHAPE. This package cannot read a byte it carries, so it +// cannot batch, delay or fold anything: ending the stream is its only move. The +// host and the viewer pace themselves long before this matters, and the number +// is four times the pace a correct host holds, so a correct host never trips it. +// It exists for a host that ignores its own pace. + +import "time" + +// breakerReason is what a cut stream's close frame says, with close code 1008 +// (policy violation) on the WebSocket carrier. It is the same sentence the +// hosted relay uses (BREAKER_REASON in carrier.js). +const breakerReason = "sending faster than a live view does" + +// breaker is a leaky bucket holding [BreakerWindow] worth of [BreakerRate] and +// draining at that rate, so a stream is over its rate when it has sent more than +// that rate sustained across the window, whether as one burst or as a steady flow +// a little above the line. One direction of one stream has one, and one goroutine +// reads it, so it holds no lock. +type breaker struct { + level float64 + at time.Time + started bool +} + +// capacity is how many bytes the bucket holds: the rate for the whole window. +func (b *breaker) capacity() float64 { + return float64(BreakerRate) * BreakerWindow.Seconds() +} + +// charge counts n bytes arriving at now and answers true once the stream is over +// its rate. A clock that steps backwards drains nothing, which only ever forgives. +func (b *breaker) charge(n int, now time.Time) bool { + if b.started && now.After(b.at) { + b.level -= now.Sub(b.at).Seconds() * float64(BreakerRate) + if b.level < 0 { + b.level = 0 + } + } + if !b.started || now.After(b.at) { + b.at = now + } + b.started = true + b.level += float64(n) + return b.level > b.capacity() +} diff --git a/internal/relay/breaker_test.go b/internal/relay/breaker_test.go new file mode 100644 index 0000000000..08293dfd46 --- /dev/null +++ b/internal/relay/breaker_test.go @@ -0,0 +1,210 @@ +package relay + +import ( + "context" + "io" + "net" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/coder/websocket" +) + +const mib = 1 << 20 + +// The breaker is a leaky bucket: a burst over the window, or a flow above the +// rate, trips it; a flow under the rate never does, however long it runs. +func TestTheBreakerIsALeakyBucket(t *testing.T) { + start := time.Unix(1_000_000, 0) + capacity := int(float64(BreakerRate) * BreakerWindow.Seconds()) + + var burst breaker + if burst.charge(capacity, start) { + t.Fatal("exactly the window's allowance is not over the rate") + } + if !burst.charge(1, start) { + t.Fatal("one byte more than the window's allowance is") + } + + var twice breaker + tripped := 0 + for second := 1; second <= 20 && tripped == 0; second++ { + if twice.charge(8*mib, start.Add(time.Duration(second)*time.Second)) { + tripped = second + } + } + if tripped < 5 || tripped > 6 { + t.Fatalf("twice the rate tripped at second %d, want 5 or 6", tripped) + } + + var under breaker + for second := 1; second <= 3600; second++ { + if under.charge(3*mib, start.Add(time.Duration(second)*time.Second)) { + t.Fatalf("3 MiB a second is under the rate and tripped at second %d", second) + } + } + + var rests breaker + rests.charge(capacity, start) + if rests.charge(capacity, start.Add(BreakerWindow)) { + t.Fatal("a stream that rested for the window did not start again from empty") + } + + var backwards breaker + backwards.charge(capacity, start) + if !backwards.charge(1, start.Add(-time.Hour)) { + t.Fatal("a clock that stepped backwards drained the bucket") + } +} + +// reads yields a source of `total` bytes in 32 KiB reads, moving a fake clock by +// `each` before every read, so a test fixes the rate and the clock is not real. +type reads struct { + now *time.Time + each time.Duration + total int + sinceStart time.Duration +} + +func (r *reads) Read(p []byte) (int, error) { + if r.total <= 0 { + return 0, io.EOF + } + *r.now = r.now.Add(r.each) + r.sinceStart += r.each + n := min(len(p), r.total) + r.total -= n + return n, nil +} + +// The pace a correct host holds, one MiB a second, never meets the breaker, and +// twice the rate is cut inside the window and after its allowance is spent. +func TestACorrectPaceNeverMeetsTheBreakerAndTwiceTheRateDoes(t *testing.T) { + now := time.Unix(1_000_000, 0) + server := &Server{Now: func() time.Time { return now }} + + paced := &reads{now: &now, each: time.Second / 32, total: 600 * mib} // 1 MiB a second for ten minutes + moved, over := server.carry(io.Discard, paced, DoorLive) + if over || moved != int64(600*mib) { + t.Fatalf("a correct pace moved %d bytes and over=%v; want all 600 MiB and no cut", moved, over) + } + + fast := &reads{now: &now, each: time.Second / 256, total: 600 * mib} // 8 MiB a second + moved, over = server.carry(io.Discard, fast, DoorLive) + if !over { + t.Fatal("twice the rate was never cut") + } + if fast.sinceStart < 4900*time.Millisecond || fast.sinceStart > 6100*time.Millisecond { + t.Fatalf("twice the rate was cut after %v, want after about 5 s", fast.sinceStart) + } + if moved < 35*mib || moved > 45*mib { + t.Fatalf("%d bytes crossed before the cut, want about 40 MiB", moved) + } +} + +// A stream that did not claim the live class is copied exactly as it always was: +// a move's 8 MiB answers and every older client's traffic arrive in an instant +// and are never counted. +func TestAStreamWithNoLiveClassIsNeverHeldToARate(t *testing.T) { + now := time.Unix(1_000_000, 0) + server := &Server{Now: func() time.Time { return now }} + for _, class := range []string{"", DoorMove} { + source := &reads{now: &now, each: 0, total: 200 * mib} + moved, over := server.carry(io.Discard, source, class) + if over || moved != int64(200*mib) { + t.Fatalf("class %q moved %d bytes, over=%v; want 200 MiB and no cut", class, moved, over) + } + } +} + +// startFlood registers a machine on a relay whose clock never moves, so every +// byte sent counts against the breaker, and returns what the machine received. +func startFlood(t *testing.T, class string) (surface net.Conn, received *atomic.Int64, ended chan struct{}) { + t.Helper() + frozen := time.Unix(1_000_000, 0) + service := &Server{Now: func() time.Time { return frozen }} + server := httptest.NewServer(service) + t.Cleanup(server.Close) + t.Cleanup(server.CloseClientConnections) + address := server.URL + registration, err := Register(context.Background(), address, aKey(t)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = registration.Close() }) + conn, err := DialDoor(context.Background(), address, registration.Name(), class) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + engine, err := registration.Accept() + if err != nil { + t.Fatal(err) + } + received = new(atomic.Int64) + ended = make(chan struct{}) + go func() { + buf := make([]byte, 64<<10) + for { + n, err := engine.Read(buf) + received.Add(int64(n)) + if err != nil { + close(ended) + return + } + } + }() + return conn, received, ended +} + +// A live stream sending far faster than any live view is cut, the surface is +// told with close code 1008, and the machine is told the stream is over. +func TestALiveStreamSendingFasterThanAnyViewIsCutWithPolicyViolation(t *testing.T) { + surface, received, ended := startFlood(t, DoorLive) + chunk := make([]byte, 64<<10) + for sent := 0; sent < 64*mib; sent += len(chunk) { + if _, err := surface.Write(chunk); err != nil { + break + } + } + buf := make([]byte, 1) + _, err := surface.Read(buf) + if websocket.CloseStatus(err) != websocket.StatusPolicyViolation { + t.Fatalf("the surface heard %v, want a close with code 1008 (%d)", err, websocket.StatusPolicyViolation) + } + select { + case <-ended: + case <-time.After(10 * time.Second): + t.Fatal("the machine was never told the cut stream is over") + } + allowance := int64(float64(BreakerRate) * BreakerWindow.Seconds()) + if got := received.Load(); got <= 0 || got > allowance { + t.Fatalf("the machine received %d bytes before the cut, want something up to the %d-byte allowance", got, allowance) + } +} + +// The same flood on a stream that claimed no live class, or a move, is carried +// whole: the breaker is class-gated, and an unclassified dial behaves as today. +func TestTheSameFloodOnAStreamWithNoLiveClassIsCarriedWhole(t *testing.T) { + for _, class := range []string{"", DoorMove} { + t.Run("class="+class, func(t *testing.T) { + surface, received, _ := startFlood(t, class) + const total = 40 * mib + chunk := make([]byte, 64<<10) + for sent := 0; sent < total; sent += len(chunk) { + if _, err := surface.Write(chunk); err != nil { + t.Fatalf("a stream with no live class was cut after %d bytes: %v", sent, err) + } + } + deadline := time.Now().Add(30 * time.Second) + for received.Load() < total { + if time.Now().After(deadline) { + t.Fatalf("the machine received %d of %d bytes", received.Load(), total) + } + time.Sleep(10 * time.Millisecond) + } + }) + } +} diff --git a/internal/relay/class_test.go b/internal/relay/class_test.go new file mode 100644 index 0000000000..fad2625624 --- /dev/null +++ b/internal/relay/class_test.go @@ -0,0 +1,160 @@ +package relay + +import ( + "context" + "errors" + "io" + "net/http" + "testing" + "time" +) + +// dialAll opens n dials of one class against a registered machine and keeps +// them open until the test ends. An empty class is the dial an older build makes. +func dialAll(t *testing.T, address, name, class string, n int) []io.Closer { + t.Helper() + var held []io.Closer + for i := 0; i < n; i++ { + conn, err := DialDoor(context.Background(), address, name, class) + if err != nil { + t.Fatalf("dial %d of class %q: %v", i+1, class, err) + } + t.Cleanup(func() { _ = conn.Close() }) + held = append(held, conn) + } + return held +} + +// refused says whether a dial of this class is turned away as busy, which is +// how a machine at its ceiling answers: a 429, which the client reads as ErrTooMany. +func refused(t *testing.T, address, name, class string) bool { + t.Helper() + conn, err := DialDoor(context.Background(), address, name, class) + if err == nil { + t.Cleanup(func() { _ = conn.Close() }) + return false + } + if !errors.Is(err, ErrTooMany) { + t.Fatalf("a dial of class %q failed with %v, want it accepted or turned away as busy", class, err) + } + return true +} + +func aMachine(t *testing.T, address string) string { + t.Helper() + registration, err := Register(context.Background(), address, aKey(t)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = registration.Close() }) + // Every surface the relay opens lands on the machine's accept queue, which + // holds only a ceiling's worth, so a test that dials all of them drains it. + go func() { + for { + stream, err := registration.Accept() + if err != nil { + return + } + go func() { _, _ = io.Copy(io.Discard, stream) }() + } + }() + return registration.Name() +} + +// V21: with fourteen live viewers attached the fifteenth live dial is refused, +// and a move dial still succeeds, twice, because two streams are kept for it. +func TestLiveDialsStopAtFourteenAndMoveKeepsTwo(t *testing.T) { + _, address := live(t) + name := aMachine(t, address) + + dialAll(t, address, name, DoorLive, LiveStreams) + if !refused(t, address, name, DoorLive) { + t.Fatalf("a live dial past %d streams was accepted", LiveStreams) + } + dialAll(t, address, name, DoorMove, MaxStreams-LiveStreams) + if !refused(t, address, name, DoorMove) { + t.Fatalf("a move dial past %d streams was accepted", MaxStreams) + } + if !refused(t, address, name, "") { + t.Fatalf("an unclassified dial past %d streams was accepted", MaxStreams) + } +} + +// V21: a dial that claims no class, which is every dial from a build older than +// the class, gets all sixteen streams, exactly as before. +func TestAnUnclassifiedDialStillGetsAllSixteen(t *testing.T) { + _, address := live(t) + name := aMachine(t, address) + dialAll(t, address, name, "", MaxStreams) + if !refused(t, address, name, "") { + t.Fatalf("an unclassified dial past %d streams was accepted", MaxStreams) + } +} + +// A class this relay has never heard of is not an error and not a class: the +// dial is held to the full sixteen, so a class a later build adds does not turn +// an older relay's answer into a refusal. +func TestAnUnknownDoorIsTreatedAsNoDoor(t *testing.T) { + for _, said := range []string{"bogus", "LIVE", "Live", "live,move", ""} { + t.Run(said, func(t *testing.T) { + sets := func(door http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.Header.Set(HeaderDoor, said) + door.ServeHTTP(w, r) + }) + } + address := mounted(t, "/fabric", sets(&Server{})) + name := aMachine(t, address) + dialAll(t, address, name, "", MaxStreams) + if !refused(t, address, name, "") { + t.Fatalf("a dial claiming %q past %d streams was accepted", said, MaxStreams) + } + }) + } +} + +// The reservation is measured against the machine's total, so streams from +// older clients cannot crowd a move out of the two kept for it. +func TestUnclassifiedStreamsCannotCrowdAMoveOutOfItsTwo(t *testing.T) { + _, address := live(t) + name := aMachine(t, address) + dialAll(t, address, name, "", LiveStreams) + if !refused(t, address, name, DoorLive) { + t.Fatal("a live dial was accepted at a total of 14") + } + dialAll(t, address, name, DoorMove, 1) + dialAll(t, address, name, "", 1) + if !refused(t, address, name, DoorMove) { + t.Fatalf("a move dial past %d streams was accepted", MaxStreams) + } +} + +// A live stream that ends gives its slot back to the next live dial. +func TestAnEndedLiveStreamFreesItsSlot(t *testing.T) { + _, address := live(t) + name := aMachine(t, address) + held := dialAll(t, address, name, DoorLive, LiveStreams) + if !refused(t, address, name, DoorLive) { + t.Fatal("the fifteenth live dial was accepted") + } + _ = held[0].Close() + deadline := time.Now().Add(10 * time.Second) + for refused(t, address, name, DoorLive) { + if time.Now().After(deadline) { + t.Fatal("a closed live stream never freed its slot") + } + time.Sleep(20 * time.Millisecond) + } +} + +// The class is read on the raw upgrade as well as the WebSocket, so a relay +// reached either way holds the same ceilings. +func TestTheClassGateHoldsOnTheRawCarrierToo(t *testing.T) { + address := mounted(t, "/fabric", rawOnly(&Server{})) + name := aMachine(t, address) + dialAll(t, address, name, DoorLive, LiveStreams) + if !refused(t, address, name, DoorLive) { + t.Fatal("the fifteenth live dial on the raw carrier was accepted") + } + dialAll(t, address, name, DoorMove, 1) +} diff --git a/internal/relay/client.go b/internal/relay/client.go index e10de96022..5def5e5b8b 100644 --- a/internal/relay/client.go +++ b/internal/relay/client.go @@ -142,10 +142,36 @@ func (r *Registration) Close() error { // a Noise handshake against a pinned key — and nothing else in this tree may // put a session frame on this pipe. func Dial(ctx context.Context, service, name string) (io.ReadWriteCloser, error) { + conn, err := DialDoor(ctx, service, name, "") + if err != nil { + return nil, err + } + return conn, nil +} + +// DialDoor is [Dial] that says what the stream is for. A class of [DoorLive] or +// [DoorMove] is sent in [HeaderDoor], and the empty class sends nothing, which +// is exactly the dial an older build makes. +// +// A CLASS THAT IS NEITHER OF THOSE IS REFUSED HERE AND NOT SENT. The relay would +// read an unknown value as no class, so a misspelling would quietly turn a +// viewer's dial into an unclassified one that is held to the full sixteen, the +// opposite of what the caller meant; the mistake is cheaper to see as an error +// in the person's own build than as a machine that fills up. The refusal is a +// sentence about a program and not a person: no screen has a reason to show it. +func DialDoor(ctx context.Context, service, name, class string) (net.Conn, error) { if !ValidName(name) { return nil, fmt.Errorf("%q is not the shape of a machine name — they look like otter-lamp-42", name) } - return upgrade(ctx, service, DialPrefix+name, http.Header{}) + header := http.Header{} + switch class { + case "": + case DoorLive, DoorMove: + header.Set(HeaderDoor, class) + default: + return nil, fmt.Errorf("relay: %q is not a dial class — the classes are %q and %q", class, DoorLive, DoorMove) + } + return upgrade(ctx, service, DialPrefix+name, header) } // upgrade dials the service and takes the connection over. @@ -158,7 +184,7 @@ func Dial(ctx context.Context, service, name string) (io.ReadWriteCloser, error) func upgrade(ctx context.Context, service, path string, header http.Header) (net.Conn, error) { address, err := url.Parse(strings.TrimSpace(service)) if err != nil || address.Host == "" || (address.Scheme != "http" && address.Scheme != "https") { - return nil, fmt.Errorf("%q is not a sync service URL — it looks like https://relay.example.com", service) + return nil, fmt.Errorf("%q is not a relay URL — it looks like https://relay.example.com", service) } // The relay address may carry a path of its own (https://host/fabric), and // the door is beneath it, as every other client's route is. Refusals name @@ -264,7 +290,7 @@ func refusal(base, path string, status int, said string) error { case relaySentence(said): return errors.New(said) default: - return fmt.Errorf("the sync service at %s refused this connection (%d) — check the address it was given", base, status) + return fmt.Errorf("the relay at %s refused this connection (%d) — check the address it was given", base, status) } } diff --git a/internal/relay/constants_law_test.go b/internal/relay/constants_law_test.go new file mode 100644 index 0000000000..dae3701503 --- /dev/null +++ b/internal/relay/constants_law_test.go @@ -0,0 +1,85 @@ +package relay + +import ( + "os" + "regexp" + "strconv" + "strings" + "testing" +) + +// ONE SOURCE OF TRUTH FOR EVERY NUMBER THE TWO RELAYS ENFORCE. The hosted Worker +// states them again in relay/hosted/src/engine/carrier.js, under the Go names in a +// trailing comment, and a number stated in two places drifts. A relay whose Worker +// still allowed sixteen live dials after this package said fourteen would pass +// every test of both and fail a person, so this reads the Worker's file and holds +// each constant to this package's. The Worker's own tests read relay.go for the +// same table from the other side. +func TestTheWorkerStatesTheSameNumbersAsThisPackage(t *testing.T) { + raw, err := os.ReadFile("../../relay/hosted/src/engine/carrier.js") + if err != nil { + t.Fatal(err) + } + source := string(raw) + expression := func(name string) string { + t.Helper() + found := regexp.MustCompile(`(?m)^export const ` + name + ` = ([^;]+);`).FindStringSubmatch(source) + if found == nil { + t.Fatalf("carrier.js has no `export const %s`", name) + } + return strings.TrimSpace(found[1]) + } + number := func(name string) int64 { + t.Helper() + text := expression(name) + if left, right, shifted := strings.Cut(text, "<<"); shifted { + base, errBase := strconv.ParseInt(strings.TrimSpace(left), 10, 64) + by, errBy := strconv.ParseInt(strings.TrimSpace(right), 10, 64) + if errBase != nil || errBy != nil { + t.Fatalf("%s = %q is not a number or a shift", name, text) + } + return base << by + } + n, err := strconv.ParseInt(text, 10, 64) + if err != nil { + t.Fatalf("%s = %q is not a number", name, text) + } + return n + } + text := func(name string) string { + t.Helper() + return strings.Trim(expression(name), `'"`) + } + + for _, row := range []struct { + js string + want int64 + }{ + {"MAX_PAYLOAD", MaxPayload}, + {"MAX_STREAMS", MaxStreams}, + {"LIVE_STREAMS", LiveStreams}, + {"HANDSHAKE_MS", HandshakeWithin.Milliseconds()}, + {"PROBE_MS", ProbeWithin.Milliseconds()}, + {"DIALS_PER_MINUTE", DialsPerMinute}, + {"REGISTRATIONS_PER_MINUTE", RegistrationsPerMinute}, + {"BREAKER_BYTES_PER_SECOND", BreakerRate}, + {"BREAKER_WINDOW_MS", BreakerWindow.Milliseconds()}, + } { + if got := number(row.js); got != row.want { + t.Errorf("%s is %d in the Worker and %d in this package", row.js, got, row.want) + } + } + for _, row := range []struct{ js, want string }{ + {"DOOR_LIVE", DoorLive}, + {"DOOR_MOVE", DoorMove}, + {"HEADER_DOOR", strings.ToLower(HeaderDoor)}, + {"BREAKER_REASON", breakerReason}, + } { + if got := text(row.js); got != row.want { + t.Errorf("%s is %q in the Worker and %q in this package", row.js, got, row.want) + } + } + if MaxStreams-LiveStreams != 2 { + t.Errorf("%d streams are kept for a move; the design keeps 2", MaxStreams-LiveStreams) + } +} diff --git a/internal/relay/dialdoor_test.go b/internal/relay/dialdoor_test.go new file mode 100644 index 0000000000..e34e3bb7e3 --- /dev/null +++ b/internal/relay/dialdoor_test.go @@ -0,0 +1,145 @@ +package relay + +import ( + "context" + "net/http" + "strings" + "sync" + "testing" +) + +// dialLog records the class header of every dial that reaches a relay, so a test +// can say what a client SENT and not merely what the relay did with it. +type dialLog struct { + mu sync.Mutex + dials int + classes []string + present []bool +} + +func (l *dialLog) wrap(door http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, DialPrefix) { + l.mu.Lock() + l.dials++ + _, sent := r.Header[http.CanonicalHeaderKey(HeaderDoor)] + l.classes = append(l.classes, r.Header.Get(HeaderDoor)) + l.present = append(l.present, sent) + l.mu.Unlock() + } + door.ServeHTTP(w, r) + }) +} + +// The classes and the number they are measured against are the wire's spelling, +// and the Worker spells them the same way. +func TestTheClassesAreWhatTheWireSpells(t *testing.T) { + if DoorLive != "live" || DoorMove != "move" || HeaderDoor != "Codeaf-Door" { + t.Errorf("classes %q and %q in header %q; want live, move, Codeaf-Door", DoorLive, DoorMove, HeaderDoor) + } + if LiveStreams != 14 || MaxStreams != 16 { + t.Errorf("LiveStreams %d, MaxStreams %d; want 14 and 16", LiveStreams, MaxStreams) + } + if MaxStreams-LiveStreams != 2 { + t.Errorf("%d streams are kept for moving a chat; want 2", MaxStreams-LiveStreams) + } +} + +// A classified dial says its class on both carriers, and an unclassified one, +// which is what every older build sends, says nothing at all. +func TestADialSaysItsClassOnBothCarriersOrNothing(t *testing.T) { + carriers := map[string]func(http.Handler) http.Handler{ + "websocket": func(h http.Handler) http.Handler { return wsOnly(h) }, + "raw": func(h http.Handler) http.Handler { return rawOnly(h) }, + } + for carrier, front := range carriers { + for _, class := range []string{DoorLive, DoorMove, ""} { + t.Run(carrier+"/"+class, func(t *testing.T) { + var log dialLog + address := mounted(t, "/fabric", front(log.wrap(&Server{}))) + registration, err := Register(context.Background(), address, aKey(t)) + if err != nil { + t.Fatal(err) + } + defer func() { _ = registration.Close() }() + + conn, err := DialDoor(context.Background(), address, registration.Name(), class) + if err != nil { + t.Fatalf("DialDoor(%q): %v", class, err) + } + defer func() { _ = conn.Close() }() + engine, err := registration.Accept() + if err != nil { + t.Fatal(err) + } + defer func() { _ = engine.Close() }() + if _, err := conn.Write([]byte("hi")); err != nil { + t.Fatal(err) + } + if got := readN(t, engine, 2); got != "hi" { + t.Fatalf("a classified dial carried %q, want it to work like any other", got) + } + + log.mu.Lock() + defer log.mu.Unlock() + if log.dials != 1 { + t.Fatalf("%d dials reached the relay, want 1", log.dials) + } + if log.classes[0] != class || log.present[0] != (class != "") { + t.Fatalf("sent class %q (header present: %v), want %q (present: %v)", log.classes[0], log.present[0], class, class != "") + } + }) + } + } +} + +// Dial is the unclassified dial and always was: a build that has not been +// taught a class must reach a machine exactly as it did. +func TestDialSendsNoClass(t *testing.T) { + var log dialLog + address := mounted(t, "/fabric", log.wrap(&Server{})) + registration, err := Register(context.Background(), address, aKey(t)) + if err != nil { + t.Fatal(err) + } + defer func() { _ = registration.Close() }() + conn, err := Dial(context.Background(), address, registration.Name()) + if err != nil { + t.Fatal(err) + } + _ = conn.Close() + log.mu.Lock() + defer log.mu.Unlock() + if log.dials != 1 || log.present[0] { + t.Fatalf("Dial sent %d dials, class header present: %v; want one dial and no header", log.dials, log.present) + } +} + +// A class this build does not know is an error before anything is sent, so a +// misspelling cannot quietly become an unclassified dial that fills the machine. +func TestAClassNobodyKnowsIsRefusedBeforeItIsSent(t *testing.T) { + var log dialLog + address := mounted(t, "/fabric", log.wrap(&Server{})) + for _, class := range []string{"Live", "watch", " move", "live,move"} { + conn, err := DialDoor(context.Background(), address, "otter-lamp-42", class) + if err == nil { + _ = conn.Close() + t.Fatalf("DialDoor(%q) was accepted", class) + } + if !strings.Contains(err.Error(), "not a dial class") { + t.Errorf("DialDoor(%q) said %q, want it to say the class is not one", class, err) + } + } + log.mu.Lock() + defer log.mu.Unlock() + if log.dials != 0 { + t.Fatalf("%d dials reached the relay for classes that should never be sent", log.dials) + } +} + +// A bad name is still refused first, with the sentence it always had. +func TestDialDoorKeepsTheNameCheck(t *testing.T) { + if _, err := DialDoor(context.Background(), "http://127.0.0.1:1", "nope", DoorLive); err == nil || !strings.Contains(err.Error(), "shape of a machine name") { + t.Fatalf("a bad name gave %v", err) + } +} diff --git a/internal/relay/jitter.go b/internal/relay/jitter.go new file mode 100644 index 0000000000..4efc9289c6 --- /dev/null +++ b/internal/relay/jitter.go @@ -0,0 +1,59 @@ +package relay + +// EVERY CLIENT OF THIS RELAY DROPS AT THE SAME INSTANT WHEN THE RELAY DOES. A +// deploy, a restart or a network that flaps closes every carrier and every +// attached surface in one breath, and a client that waits a fixed second before +// its first retry is then a thousand clients arriving in the same second. The +// relay's own limits count per minute and per network, so the second wave is +// turned away and retries on the same schedule as the third, which is how an +// outage that lasted a moment becomes one that lasts a minute. +// +// So a wait is never exactly what the loop above it computed. The first retry +// after a drop is spread over a few seconds, and every later wait is spread a +// little either way. Jitter cures the spike and nothing else: it cannot make a +// computer that needs more registrations a minute than the relay allows fit, +// because the allowance is per minute whatever the spread. + +import ( + "math/rand/v2" + "time" +) + +// The spread of the first retry after a drop is one second at the least and six +// at the most, which is short enough that a chat that resumes when its host +// returns does not feel the wait, and wide enough to flatten one relay +// instance's reconnect burst. +const ( + firstRetryFloor = time.Second + firstRetrySpread = 5 * time.Second +) + +// The band every later wait is scaled into: three quarters to five quarters of +// what the loop's own doubling computed. Centred on one, so the caps and the +// back-off a loop already has keep their meaning on average. +const ( + jitterLow = 0.75 + jitterSpan = 0.5 +) + +// rnd is the random source, a package variable so a test can pin it. It answers +// a number in [0, 1), which is what [rand.Float64] answers and what the two +// formulas below are written against. +var rnd = rand.Float64 + +// FirstRetry is how long a client waits before the first retry after it was +// dropped: one second plus a uniform draw from [0, 5 s). Only that first wait +// uses it; a loop that has already waited once doubles and calls [Jitter]. +func FirstRetry() time.Duration { + return firstRetryFloor + time.Duration(rnd()*float64(firstRetrySpread)) +} + +// Jitter spreads a wait a loop has already computed: d times a uniform draw from +// [0.75, 1.25). A wait that is not positive comes back unchanged, because there +// is nothing to spread and a loop that asked for no wait meant none. +func Jitter(d time.Duration) time.Duration { + if d <= 0 { + return d + } + return time.Duration(float64(d) * (jitterLow + rnd()*jitterSpan)) +} diff --git a/internal/relay/jitter_test.go b/internal/relay/jitter_test.go new file mode 100644 index 0000000000..2811f598f7 --- /dev/null +++ b/internal/relay/jitter_test.go @@ -0,0 +1,92 @@ +package relay + +import ( + "testing" + "time" +) + +// pinned makes the random source answer the given draws in turn, repeating the +// last, and puts the real one back when the test ends. +func pinned(t *testing.T, draws ...float64) { + t.Helper() + was := rnd + t.Cleanup(func() { rnd = was }) + i := 0 + rnd = func() float64 { + d := draws[min(i, len(draws)-1)] + i++ + return d + } +} + +// A client dropped by a relay restart waits one second and then a draw from the +// next five, so a thousand of them do not come back in the same second. +func TestTheFirstRetryIsOneSecondPlusAnythingUpToFive(t *testing.T) { + for _, tc := range []struct { + draw float64 + want time.Duration + }{ + {0, time.Second}, + {0.5, 3500 * time.Millisecond}, + {0.2, 2 * time.Second}, + } { + pinned(t, tc.draw) + if got := FirstRetry(); got != tc.want { + t.Errorf("draw %v: first retry %v, want %v", tc.draw, got, tc.want) + } + } + pinned(t, 0.9999999) + if got := FirstRetry(); got < 5*time.Second || got >= 6*time.Second { + t.Errorf("the top of the range gave %v, want within [5s, 6s)", got) + } +} + +// Every later wait is the loop's own doubled wait scaled into three quarters to +// five quarters of it, so a cap keeps meaning what it meant on average. +func TestAWaitIsSpreadAQuarterEitherWay(t *testing.T) { + pinned(t, 0) + if got := Jitter(8 * time.Second); got != 6*time.Second { + t.Errorf("the bottom of the range gave %v, want 6s", got) + } + pinned(t, 0.5) + if got := Jitter(8 * time.Second); got != 8*time.Second { + t.Errorf("the middle of the range gave %v, want exactly the wait asked for", got) + } + pinned(t, 0.9999999) + if got := Jitter(8 * time.Second); got < 9*time.Second || got >= 10*time.Second { + t.Errorf("the top of the range gave %v, want within [9s, 10s) of 8s", got) + } +} + +// A loop that asked for no wait, or for an impossible one, is not given one. +func TestNoWaitIsSpreadIntoAWait(t *testing.T) { + pinned(t, 0.9) + for _, d := range []time.Duration{0, -time.Second} { + if got := Jitter(d); got != d { + t.Errorf("Jitter(%v) = %v, want it unchanged", d, got) + } + } +} + +// With the real random source every answer is inside its range and they are not +// all the same: a source that returned one number would pass the pinned tests +// and spread nothing. +func TestTheRealSourceStaysInRangeAndActuallySpreads(t *testing.T) { + firsts := map[time.Duration]bool{} + scaled := map[time.Duration]bool{} + for i := 0; i < 2000; i++ { + first := FirstRetry() + if first < time.Second || first >= 6*time.Second { + t.Fatalf("first retry %v is outside [1s, 6s)", first) + } + firsts[first] = true + wait := Jitter(16 * time.Second) + if wait < 12*time.Second || wait >= 20*time.Second { + t.Fatalf("a 16s wait came back %v, outside [12s, 20s)", wait) + } + scaled[wait] = true + } + if len(firsts) < 100 || len(scaled) < 100 { + t.Fatalf("2000 draws gave %d distinct first retries and %d distinct waits: nothing is being spread", len(firsts), len(scaled)) + } +} diff --git a/internal/relay/mux.go b/internal/relay/mux.go index daba8b3d0f..285dee7107 100644 --- a/internal/relay/mux.go +++ b/internal/relay/mux.go @@ -359,12 +359,23 @@ func (c *carrier) send(op byte, stream uint64, payload []byte) error { // open mints a stream on this carrier and tells the far end about it. Only the // relay side calls it; a machine never dials a surface. -func (c *carrier) open() (*muxStream, error) { +// +// THE CLASS IS HELD AGAINST THE TOTAL. A live dial is refused once the machine +// has [LiveStreams] streams attached, whoever holds them, so live dials can +// never push the total past it and the last MaxStreams-LiveStreams slots are +// always free for a move. Every other dial, which is every dial from a build +// that predates the class, is held to [MaxStreams] exactly as it always was: +// the reservation takes nothing from an older client. +func (c *carrier) open(class string) (*muxStream, error) { c.mu.Lock() if c.gone { c.mu.Unlock() return nil, errCarrierGone } + if class == DoorLive && len(c.streams) >= LiveStreams { + c.mu.Unlock() + return nil, fmt.Errorf("that machine already has %d live connections open; the last %d are kept for moving a chat", LiveStreams, MaxStreams-LiveStreams) + } if len(c.streams) >= MaxStreams { c.mu.Unlock() return nil, fmt.Errorf("that machine already has %d connections open, which is as many as the relay carries at once", MaxStreams) diff --git a/internal/relay/relay.go b/internal/relay/relay.go index 902b7f1511..f0664a88c4 100644 --- a/internal/relay/relay.go +++ b/internal/relay/relay.go @@ -68,6 +68,31 @@ const ( HeaderKey = "Aforge-Key" // legacy-name: persisted on the wire. ) +// HeaderDoor carries the class of a dial: what the surface asking for the machine +// means to do with the stream. It is a request header for the reason the +// registration's are, an operator's logs and limiters all read headers, and it +// is the one thing a dialer volunteers about itself. A relay that has never +// heard of it ignores it, and a dial that does not send it is an UNCLASSIFIED +// dial, which is every dial from a build older than the class. +const HeaderDoor = "Codeaf-Door" + +// The classes a dial may claim in [HeaderDoor]. THE CLASS IS A CLAIM AND NOT AN +// AUTHENTICATION: a dialer can say "move" when it is not, which is why it only +// ever decides how the machine's streams are shared and never who may speak on +// one. Who may speak is settled above this package, by the handshake the host +// runs against a pinned key. A value that is neither of these is read as no +// class at all, so a later class does not turn an older relay's answer into a +// refusal. +const ( + // DoorLive is a surface watching or driving a chat as it happens, one + // stream per viewing computer, held open for as long as the view is. + DoorLive = "live" + // DoorMove is a surface that has to be able to reach the machine whenever + // anything else is attached: moving a chat to another computer must not be + // refused because viewers filled the machine's streams. + DoorMove = "move" +) + // The tuning, all in one place so that a relay operator changes a number here // and every sentence in this package that quotes it changes with it. ONE SOURCE // OF TRUTH: nothing below re-states a limit as a literal, and the hosted Worker @@ -88,6 +113,27 @@ const ( // the number the pipe will carry. MaxStreams = 16 + // LiveStreams is how many of those streams a [DoorLive] dial may leave + // attached (LIVE_STREAMS in relay/hosted/src/engine/carrier.js). It is + // compared with the machine's TOTAL stream count, whoever holds the + // others, so live dials can never push the total past it and the last + // MaxStreams-LiveStreams slots are always free for a [DoorMove] dial. A + // dial that claims no class is held to MaxStreams exactly as before: the + // reservation costs an older client nothing. + LiveStreams = 14 + + // BreakerRate and BreakerWindow are the ceiling on how fast one LIVE stream + // may send, in either direction (BREAKER_BYTES_PER_SECOND and + // BREAKER_WINDOW_MS in relay/hosted/src/engine/carrier.js): more than + // BreakerRate sustained across BreakerWindow ends the stream. It is four + // times the pace a correct host holds a live view to, so it never meets a + // correct host, and it is an ABUSE control and nothing finer: the relay + // cannot read what it carries, so it cannot batch or slow it, and cutting is + // all it can do. It is counted when a message arrives and never from a + // timer, which is what keeps an idle live view free on the hosted relay. + BreakerRate = 4 << 20 + BreakerWindow = 5 * time.Second + // PingEvery is how often the relay pokes an idle carrier, and IdleAfter is // how long it will wait for any byte before it decides the machine is gone. // A NAT that has forgotten a mapping is silent rather than closed, so a diff --git a/internal/relay/retry_after_test.go b/internal/relay/retry_after_test.go new file mode 100644 index 0000000000..0b68c37cec --- /dev/null +++ b/internal/relay/retry_after_test.go @@ -0,0 +1,55 @@ +package relay + +import ( + "net/http" + "net/http/httptest" + "strconv" + "testing" + "time" +) + +// Both rate limits' refusals say how long is left in the minute they are +// counted in, so a client waits for its window and not for a guess. The wait is +// never under a second, because a client told to come back at once is refused +// again, and the refusal for a full machine, which has no window, says nothing. +func TestARefusedCallerIsToldWhenToComeBack(t *testing.T) { + zero := time.Unix(100_000, 0) // 40 s into a minute, so 20 s of it are left + for _, door := range []struct { + name string + path string + limit int + }{{"registrations", EnginePath, RegistrationsPerMinute}, {"dials", DialPrefix + "otter-lamp-42", DialsPerMinute}} { + for _, at := range []struct { + into time.Duration + want int + }{{0, 20}, {19*time.Second + 500*time.Millisecond, 1}, {-40 * time.Second, 60}, {-39*time.Second - 500*time.Millisecond, 60}} { + t.Run(door.name+"/"+at.into.String(), func(t *testing.T) { + now := zero.Add(at.into) + server := &Server{Now: func() time.Time { return now }} + for i := 0; i <= door.limit; i++ { + req := httptest.NewRequest(http.MethodGet, door.path, nil) + req.RemoteAddr = "192.0.2.1:1234" + req.Header.Set("Upgrade", Protocol) + out := httptest.NewRecorder() + server.ServeHTTP(out, req) + if i < door.limit { + if out.Code == http.StatusTooManyRequests { + t.Fatalf("request %d was refused inside its allowance", i+1) + } + if out.Header().Get("Retry-After") != "" { + t.Fatalf("request %d, which was not refused, carried a Retry-After", i+1) + } + continue + } + if out.Code != http.StatusTooManyRequests { + t.Fatalf("request %d status=%d, want 429", i+1, out.Code) + } + got, err := strconv.Atoi(out.Header().Get("Retry-After")) + if err != nil || got != at.want { + t.Fatalf("Retry-After %q, want %d", out.Header().Get("Retry-After"), at.want) + } + } + }) + } + } +} diff --git a/internal/relay/server.go b/internal/relay/server.go index 86f15a7892..c14c1e49e0 100644 --- a/internal/relay/server.go +++ b/internal/relay/server.go @@ -24,6 +24,7 @@ import ( "io" "net" "net/http" + "strconv" "strings" "sync" "time" @@ -144,6 +145,7 @@ func (s *Server) serveEngine(w http.ResponseWriter, r *http.Request) { } from := s.callerAddress(r) if !s.allow(&s.regs, from, RegistrationsPerMinute) { + w.Header().Set("Retry-After", s.retryAfter()) http.Error(w, "too many registrations from here — wait a minute", http.StatusTooManyRequests) return } @@ -250,6 +252,7 @@ func (s *Server) serveDial(w http.ResponseWriter, r *http.Request, name string) return } if !s.allow(&s.dials, s.callerAddress(r), DialsPerMinute) { + w.Header().Set("Retry-After", s.retryAfter()) http.Error(w, "too many connections from here — wait a minute", http.StatusTooManyRequests) return } @@ -270,7 +273,8 @@ func (s *Server) serveDial(w http.ResponseWriter, r *http.Request, name string) return } - stream, err := reg.carrier.open() + class := doorOf(r) + stream, err := reg.carrier.open(class) if err != nil { // 429, as a rate limit is: the machine is full now, and a surface // that tries again in a minute may find room. @@ -290,23 +294,94 @@ func (s *Server) serveDial(w http.ResponseWriter, r *http.Request, name string) // THE SPLICE, WHICH IS THE WHOLE SERVICE. Bytes from the surface go to the // machine and bytes from the machine go to the surface, and this function // counts them and looks at nothing. There is no branch here on what a byte - // is, because there is nothing in this package that could tell. + // is, because there is nothing in this package that could tell. The only + // branch is on the CLASS the surface claimed, and that decides whether the + // copy is also held to a rate (see [Server.carry]). done := make(chan struct{}, 2) go func() { - n, _ := io.Copy(stream, conn) + n, over := s.carry(stream, conn, class) reg.add(n, 0) + if over { + s.note(name, "a live surface was cut for its rate") + cutForRate(conn) + } _ = stream.Close() done <- struct{}{} }() go func() { - n, _ := io.Copy(conn, stream) + n, over := s.carry(conn, stream, class) reg.add(0, n) + if over { + s.note(name, "a live surface was cut for its rate") + cutForRate(conn) + } _ = conn.Close() done <- struct{}{} }() <-done } +// doorOf is the class a dial claimed. ONLY THE TWO KNOWN CLASSES ARE CLASSES: +// anything else, an absent header included, is no class at all, so an older +// client and a class a later build adds are held to the full [MaxStreams] exactly +// as every dial was before the header existed. +func doorOf(r *http.Request) string { + switch said := r.Header.Get(HeaderDoor); said { + case DoorLive, DoorMove: + return said + } + return "" +} + +// carry copies src to dst and says how many bytes it moved and whether it +// stopped because the stream went over its rate. A stream that did not claim the +// live class is copied exactly as it always was, with no counting: a move's +// large answers and every older client's traffic are never held to a rate. +func (s *Server) carry(dst io.Writer, src io.Reader, class string) (moved int64, over bool) { + if class != DoorLive { + moved, _ = io.Copy(dst, src) + return moved, false + } + var rate breaker + buf := make([]byte, 32<<10) + for { + n, err := src.Read(buf) + if n > 0 { + if rate.charge(n, s.now()) { + return moved, true + } + written, werr := dst.Write(buf[:n]) + moved += int64(written) + if werr != nil { + return moved, false + } + } + if err != nil { + return moved, false + } + } +} + +// cutForRate ends a surface's connection because its stream went over its rate. +// A WebSocket surface is told why, with close code 1008 (policy violation); a +// raw one has no close code to carry and is simply closed. +func cutForRate(conn net.Conn) { + if ws, ok := conn.(*wsConn); ok { + _ = ws.socket.Close(websocket.StatusPolicyViolation, breakerReason) + return + } + _ = conn.Close() +} + +// retryAfter is how long a refused caller should wait, in whole seconds: what +// is left of the minute its allowance is counted in, and never less than one, so +// nobody is told to come back at once and be refused again. +func (s *Server) retryAfter() string { + now := s.now() + left := now.Truncate(time.Minute).Add(time.Minute).Sub(now) + return strconv.Itoa(max(1, int((left+time.Second-1)/time.Second))) +} + func (r *registration) add(up, down int64) { r.mu.Lock() r.up += up diff --git a/internal/relayserve/compatibility_refusal_test.go b/internal/relayserve/compatibility_refusal_test.go index 1e59eb641f..a33163f92e 100644 --- a/internal/relayserve/compatibility_refusal_test.go +++ b/internal/relayserve/compatibility_refusal_test.go @@ -13,7 +13,7 @@ func TestR25CompatibilityRefusalSentences(t *testing.T) { for _, one := range []struct{ got, want string }{ {cs.EnrollmentMessage(cs.UpdateRequired), "this codeaf build must be updated before it can join this cluster; your saved chats are still here"}, {cs.LeadershipUnavailable, "this cluster cannot coordinate right now; reconnect enough of its voting computers and try again; your saved chats are still here"}, - {directory.ErrConditionalTake.Error(), "taking an open chat from another computer waits for a sync service update; all else works, so close it there and continue here"}, + {directory.ErrConditionalTake.Error(), "taking an open chat from another computer waits for a relay update; all else works, so close it there and move it here"}, {clusterctl.CommittedRefusal{Code: cs.Conflict, Sequence: 1}.Error(), "the leadership request could not complete; refresh cluster status and try again"}, } { if one.got != one.want { diff --git a/internal/relayserve/main.go b/internal/relayserve/main.go index 14fef83784..9ec6bcdede 100644 --- a/internal/relayserve/main.go +++ b/internal/relayserve/main.go @@ -74,7 +74,7 @@ func Main(args []string) error { func RelayHelp(out io.Writer) { fmt.Fprintln(out, `usage: codeaf relay [--listen host:port] [--store path] -Run your own sync service. +Run your own relay. --listen host:port address to listen on (default :8787) --store path keep your devices and saved chats here; empty connects machines only diff --git a/internal/remote/client.go b/internal/remote/client.go index 05e5d0e7ef..81a223f7a2 100644 --- a/internal/remote/client.go +++ b/internal/remote/client.go @@ -1,6 +1,8 @@ package remote import ( + "bufio" + "bytes" "context" "crypto/rand" "encoding/hex" @@ -18,6 +20,7 @@ import ( "sync/atomic" "time" + "github.com/Agent-Field/codeaf/internal/chatlist" "github.com/Agent-Field/codeaf/internal/devname" "github.com/Agent-Field/codeaf/internal/executor" "github.com/Agent-Field/codeaf/internal/session" @@ -105,8 +108,11 @@ type Client struct { // it is read under mu and never cached by anything that outlives a frame. conn io.ReadWriteCloser // lines is the decoder over the read half, owned by the reader goroutine - // after the handshake and touched by nothing else. - lines *json.Decoder + // after the handshake and touched by nothing else. When maxLine is set, + // bounded replaces it with a line-capped buffered reader. + lines *json.Decoder + bounded *bufio.Reader + maxLine int // welcome is what the engine said at the door, and what the door in // cmd/codeaf reads its Options out of. @@ -132,6 +138,10 @@ type Client struct { // which is the whole of what [Client.LinkNote] reports and the reason a call // made in that gap is refused rather than written onto a dead pipe. reconnecting bool + // noteAt is the first moment [Client.LinkNote] may say `reconnecting` for the + // redial in progress. Zero says it at once; a planned road swap sets it a + // moment ahead so that a swap which takes milliseconds says nothing. + noteAt time.Time // notice is one sentence the surface should show once — the two facts a // redial can discover that a person must not be left to guess at. See // [Client.TakeNotice]. @@ -175,6 +185,7 @@ type Client struct { // their ids belong to this connection and never enter turn replay cursors. sideAsks map[uint64]func(string) calls map[uint64]chan result + pendingSends map[uint64]Frame streams map[uint64]*stream observers map[uint64]*stream replayCursor session.ReplayCursor @@ -270,6 +281,33 @@ type result struct { answered bool } +// ClientOption configures optional client reader behavior before attaching. +type ClientOption func(*Client) + +// WithMaxLine caps each inbound newline-delimited frame line to max bytes. +// Zero keeps the default unbounded decoder used for local pipes and sockets. +func WithMaxLine(max int) ClientOption { + return func(c *Client) { + c.maxLine = max + } +} + +// SetMaxLine sets the inbound frame line ceiling on c before or across dials. +func (c *Client) SetMaxLine(max int) { + c.mu.Lock() + defer c.mu.Unlock() + c.maxLine = max + if c.conn != nil { + if max > 0 { + c.bounded = bufio.NewReaderSize(c.conn, max+1) + c.lines = nil + } else { + c.lines = json.NewDecoder(c.conn) + c.bounded = nil + } + } +} + // Dial performs the handshake on an already-open pipe pair and returns the live // client. It is separate from spawning ssh on purpose: the spawning belongs to // the door (cmd/codeaf, which owns processes and flags), and a test drives this @@ -279,8 +317,8 @@ type result struct { // order the door runs things in: the handshake happens while the terminal is // still the person's, so ssh's own passphrase and host-key questions, and the // sentence below about a version mismatch, are plain text on a plain screen. -func Dial(conn io.ReadWriteCloser, host string, hello Hello) (*Client, error) { - c := newClient(host, hello) +func Dial(conn io.ReadWriteCloser, host string, hello Hello, opts ...ClientOption) (*Client, error) { + c := newClient(host, hello, opts...) if _, err := c.attach(conn); err != nil { return nil, err } @@ -290,7 +328,7 @@ func Dial(conn io.ReadWriteCloser, host string, hello Hello) (*Client, error) { // newClient is the empty client both doors build — [Dial] and [Roam] — before // anything has been said on a pipe. -func newClient(host string, hello Hello) *Client { +func newClient(host string, hello Hello, opts ...ClientOption) *Client { hello.Version = Version hello.LocalSavingReceipts = true hello.SyncNoticeWords = true @@ -306,21 +344,28 @@ func newClient(host string, hello Hello) *Client { hello.ClientID = newClientID() } hello.Encodings = []string{frameEncodingGzip} - return &Client{ + c := &Client{ clientTools: clientToolLink{owner: rand.Text()}, - host: strings.TrimSpace(host), - hello: hello, - calls: map[uint64]chan result{}, - streams: map[uint64]*stream{}, - done: make(chan struct{}), - stop: make(chan struct{}), + host: strings.TrimSpace(host), + hello: hello, + calls: map[uint64]chan result{}, + pendingSends: map[uint64]Frame{}, + streams: map[uint64]*stream{}, + done: make(chan struct{}), + stop: make(chan struct{}), driver: Driver{Yours: true}, driverWake: make(chan struct{}), following: make(chan Following, followingRoom), passes: make(chan session.Event, passRoom), } + for _, opt := range opts { + if opt != nil { + opt(c) + } + } + return c } // newClientID gives one surface a stable identity to carry through every @@ -350,19 +395,22 @@ func (c *Client) attach(conn io.ReadWriteCloser) (Welcome, error) { if err != nil { return Welcome{}, err } - lines := json.NewDecoder(conn) c.mu.Lock() - c.conn, c.lines = conn, lines + c.conn = conn + if c.maxLine > 0 { + c.bounded = bufio.NewReaderSize(conn, c.maxLine+1) + c.lines = nil + } else { + c.lines = json.NewDecoder(conn) + c.bounded = nil + } c.mu.Unlock() if err := c.write(Frame{Kind: "hello", Payload: payload}); err != nil { return Welcome{}, c.gone(err) } var frame Frame - if err := lines.Decode(&frame); err != nil { - return Welcome{}, c.gone(err) - } - if err := expandFrame(&frame); err != nil { + if err := c.readFrame(&frame); err != nil { return Welcome{}, c.gone(err) } switch frame.Kind { @@ -700,7 +748,7 @@ func (c *Client) Ping() (time.Duration, error) { func (c *Client) LinkNote() string { c.mu.Lock() defer c.mu.Unlock() - if c.dead != nil || !c.reconnecting { + if c.dead != nil || !c.reconnecting || time.Now().Before(c.noteAt) { return "" } return c.roamingNote() @@ -827,6 +875,12 @@ func (c *Client) SendRefusal() string { // again. A sentence that only reported the failure would leave a person // wondering whether their work survived. func (c *Client) gone(cause error) error { + // A view the far end ended on purpose already has its one true sentence, + // and "run the same command" would be wrong advice for it: the same command + // asks the same computer, which has just said no. + if reason, ended := endedByFarEnd(cause); ended { + return errors.New(chatlist.LiveSaid(reason, c.where())) + } sentence := fmt.Sprintf("the connection to %s is gone — run the same command to pick the conversation back up", c.where()) // A cause worth repeating is one the FAR END chose to say (a "fatal" frame's // reason). Transport errors are not: "read |0: file already closed" tells a @@ -878,15 +932,91 @@ func (c *Client) write(frame Frame) error { return flushFrame(conn) } +// readFrame decodes and expands one inbound frame from the active link. When +// maxLine is zero it uses the unbounded json.Decoder; when maxLine is positive +// it reads a single newline-delimited line from the bounded bufio.Reader so an +// oversized line never allocates past maxLine+1 bytes. +func (c *Client) readFrame(frame *Frame) error { + c.mu.Lock() + lines := c.lines + bounded := c.bounded + maxLine := c.maxLine + c.mu.Unlock() + + if maxLine <= 0 { + if err := lines.Decode(frame); err != nil { + return err + } + if err := expandFrame(frame); err != nil { + return buriedError{err} + } + return nil + } + + raw, err := bounded.ReadSlice('\n') + if errors.Is(err, bufio.ErrBufferFull) { + return c.tooLargeError() + } + if err != nil { + if errors.Is(err, io.EOF) && len(raw) > 0 { + if len(raw) > maxLine { + return c.tooLargeError() + } + } else { + return err + } + } + raw = bytes.TrimSuffix(raw, []byte{'\n'}) + raw = bytes.TrimSuffix(raw, []byte{'\r'}) + if len(raw) > maxLine { + return c.tooLargeError() + } + if err := json.Unmarshal(raw, frame); err != nil { + return err + } + if err := expandFrameCap(frame, maxLine); err != nil { + if errors.Is(err, errExpandedFrameTooLarge) { + return c.tooLargeError() + } + return buriedError{err} + } + return nil +} + +// buriedError marks a frame that arrived whole but could not be expanded. The +// link is fine and the stream is not, so the client is buried with the cause +// rather than treated as a dropped link that a roaming client would redial. +type buriedError struct{ err error } + +func (e buriedError) Error() string { return e.err.Error() } +func (e buriedError) Unwrap() error { return e.err } + +func (c *Client) tooLargeError() error { + c.mu.Lock() + conn := c.conn + c.mu.Unlock() + if conn != nil { + _ = conn.Close() + } + return spokenError{reason: fmt.Sprintf("%s sent a message too large to read", c.where())} +} + // read is the reader goroutine: the only thing that decodes frames, and the // only thing that writes to the routing maps. func (c *Client) read() { for { - c.mu.Lock() - lines := c.lines - c.mu.Unlock() var frame Frame - if err := lines.Decode(&frame); err != nil { + if err := c.readFrame(&frame); err != nil { + var spoken spokenError + if errors.As(err, &spoken) { + c.bury(err) + return + } + var buried buriedError + if errors.As(err, &buried) { + c.bury(buried.err) + return + } // The link under this reader stopped. On a roaming client that is a // pause and not an ending, so [Client.lost] is what decides which of // the two this was, and it comes back true holding a live pipe. @@ -895,10 +1025,6 @@ func (c *Client) read() { } return } - if err := expandFrame(&frame); err != nil { - c.bury(err) - return - } switch frame.Kind { case clientToolCallKind, clientToolEndedKind: c.clientToolFrame(frame) @@ -916,6 +1042,8 @@ func (c *Client) read() { c.deliver(frame) case "event": c.stream(frame.ID).push(frame.Seq, frame.Payload) + case "gap": + c.gapFrame(frame) case "closed": c.stream(frame.ID).finish() case "turn": @@ -1009,6 +1137,7 @@ func (c *Client) deliver(frame Frame) { c.mu.Lock() waiting, ok := c.calls[frame.ID] delete(c.calls, frame.ID) + delete(c.pendingSends, frame.ID) c.mu.Unlock() if !ok { // A result for a call that has already given up (its deadline passed). @@ -1099,6 +1228,7 @@ func (c *Client) bury(cause error) { dead := c.dead calls, streams := c.calls, c.streams c.calls, c.streams = map[uint64]chan result{}, map[uint64]*stream{} + c.pendingSends = map[uint64]Frame{} // AND THE TAKE-BACK'S RECEIPTS GO WITH THEM: a stream id from the // connection that just died names nothing on the one that follows, and a // stale receipt would match a queued message it was never handed @@ -1252,11 +1382,19 @@ func (c *Client) callAnswered(ctx context.Context, method string, args any, dead return nil, true, errors.New(c.roamingRefusal()) } c.calls[id] = waiting + frame := Frame{Kind: "call", ID: id, Method: method, Payload: payload} + if hasRepeatClientID(method, payload) { + if c.pendingSends == nil { + c.pendingSends = map[uint64]Frame{} + } + c.pendingSends[id] = frame + } c.mu.Unlock() - if err := c.write(Frame{Kind: "call", ID: id, Method: method, Payload: payload}); err != nil { + if err := c.write(frame); err != nil { c.mu.Lock() delete(c.calls, id) + delete(c.pendingSends, id) roaming := c.roam != nil && !c.closing c.mu.Unlock() // A WRITE THAT FAILED IS NOT A CALL THAT DID NOT HAPPEN. The frame may @@ -1279,20 +1417,26 @@ func (c *Client) callAnswered(ctx context.Context, method string, args any, dead } timer := time.NewTimer(deadline) defer timer.Stop() - select { - case answer := <-waiting: - return answer.payload, answer.answered, answer.err - case <-ctx.Done(): - // The caller walked away from a call that is still out there. - c.forget(id) - return nil, false, ctx.Err() - case <-timer.C: - // AND THE DEADLINE IS THE UNKNOWN ITSELF. The engine may be working on - // this call right now; what ran out is this end's patience. A live - // connection is not declared gone for that — [Client.late] is the - // honest sentence, and the rest of the room stays up. - c.forget(id) - return nil, false, c.late() + for { + select { + case answer := <-waiting: + return answer.payload, answer.answered, answer.err + case <-ctx.Done(): + // The caller walked away from a call that is still out there. + c.forget(id) + return nil, false, ctx.Err() + case <-timer.C: + if c.isHeldForResend(id) { + timer.Reset(deadline) + continue + } + // AND THE DEADLINE IS THE UNKNOWN ITSELF. The engine may be working on + // this call right now; what ran out is this end's patience. A live + // connection is not declared gone for that — [Client.late] is the + // honest sentence, and the rest of the room stays up. + c.forget(id) + return nil, false, c.late() + } } } @@ -1333,9 +1477,69 @@ func (e lateError) Is(target error) bool { return target == ErrLate } func (c *Client) forget(id uint64) { c.mu.Lock() delete(c.calls, id) + delete(c.pendingSends, id) c.mu.Unlock() } +func (c *Client) isHeldForResend(id uint64) bool { + c.mu.Lock() + defer c.mu.Unlock() + _, ok := c.pendingSends[id] + return c.reconnecting && ok +} + +func (c *Client) resendUnanswered() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.roam != nil && c.roam.ResendUnanswered +} + +func newSendClientID() string { + return "rc-" + newClientID() +} + +func hasRepeatClientID(method string, payload json.RawMessage) bool { + switch method { + case MethodSubmit, MethodFollowUp, MethodSteer: + default: + return false + } + if len(payload) == 0 { + return false + } + var args struct { + ClientID string `json:"clientId"` + } + return json.Unmarshal(payload, &args) == nil && args.ClientID != "" +} + +func (c *Client) gapFrame(frame Frame) { + var gap Gap + if err := json.Unmarshal(frame.Payload, &gap); err != nil { + return + } + if gap.Stream == 0 { + gap.Stream = frame.ID + } + c.mu.Lock() + s := c.streams[gap.Stream] + var onGap func(Gap) + if c.roam != nil { + onGap = c.roam.OnGap + } + c.mu.Unlock() + if s != nil && gap.First > 1 { + s.mu.Lock() + if s.seen < gap.First-1 { + s.seen = gap.First - 1 + } + s.mu.Unlock() + } + if onGap != nil { + onGap(gap) + } +} + // ── the typed doors ───────────────────────────────────────────────────────── // Recent is this workspace's past conversations, as the engine's disk holds @@ -1875,7 +2079,11 @@ func (a *Agent) Client() *Client { return a.c } // nothing a person can press is lost — but a caller reading this method's // signature should know which of the two it is holding. func (a *Agent) Submit(ctx context.Context, text string) (<-chan session.Event, error) { - return a.open(ctx, MethodSubmit, SubmitArgs{Text: text}) + args := SubmitArgs{Text: text} + if a.c.resendUnanswered() { + args.ClientID = newSendClientID() + } + return a.open(ctx, MethodSubmit, args) } // SubmitMessage is Submit with what the door knows about the message beyond its @@ -1896,10 +2104,17 @@ func (a *Agent) SubmitMessage(ctx context.Context, message session.Submission) ( } mark := argsOf(message) mark.Queued = false + if a.MessageRepeatKnown() { + mark.ClientID = "" + } if mark.marked() && !a.MessageMarksKnown() { return nil, errors.New("engine: this engine cannot keep a message's description; update it before sending") } - return a.open(ctx, MethodSubmit, argsOf(message)) + args := argsOf(message) + if args.ClientID == "" && a.c.resendUnanswered() { + args.ClientID = newSendClientID() + } + return a.open(ctx, MethodSubmit, args) } // SubmitComposed is Submit for a message that carries pictures and what the @@ -1951,13 +2166,24 @@ func (a *Agent) SteerMessage(message session.Submission) (<-chan session.Event, if argsOf(message).composed() { return nil, errors.New("engine: a correction carries no pictures; send them as a message") } - if !argsOf(message).marked() { + mark := argsOf(message) + if a.MessageRepeatKnown() { + mark.ClientID = "" + } + if !mark.marked() { + if message.ClientID != "" { + return a.open(nil, MethodSteer, argsOf(message)) + } return a.Steer(message.Text) } if !a.SteerMarksKnown() { return nil, errors.New("engine: this engine cannot keep a correction's description; update it before sending") } - return a.open(nil, MethodSteer, argsOf(message)) + args := argsOf(message) + if args.ClientID == "" && a.c.resendUnanswered() { + args.ClientID = newSendClientID() + } + return a.open(nil, MethodSteer, args) } // FollowUpMessage is FollowUp with what the door knows about the message beyond @@ -1971,10 +2197,14 @@ func (a *Agent) FollowUpMessage(message session.Submission) (<-chan session.Even if argsOf(message).composed() { return nil, errors.New("engine: a queued message carries no pictures; send them as a message") } - if !argsOf(message).marked() { + mark := argsOf(message) + if a.MessageRepeatKnown() { + mark.ClientID = "" + } + if !mark.marked() { // A creation context alone goes to an engine that keeps marks, and is // left behind by one that does not: the team is then unknown there. - if message.Creation != nil && a.FollowUpMarksKnown() { + if (message.Creation != nil && a.FollowUpMarksKnown()) || message.ClientID != "" { return a.followUp(argsOf(message)) } return a.FollowUp(message.Text) @@ -2040,6 +2270,9 @@ func (a *Agent) FollowUp(text string) (<-chan session.Event, error) { // followUp is the FollowUp call's one body, plain or marked. func (a *Agent) followUp(args SubmitArgs) (<-chan session.Event, error) { + if args.ClientID == "" && a.c.resendUnanswered() { + args.ClientID = newSendClientID() + } payload, err := a.c.call(nil, MethodFollowUp, args) if err != nil { return nil, err @@ -2048,6 +2281,11 @@ func (a *Agent) followUp(args SubmitArgs) (<-chan session.Event, error) { if err := json.Unmarshal(payload, &ref); err != nil { return nil, err } + if ref.Stream == 0 { + done := make(chan session.Event) + close(done) + return done, nil + } s := a.c.stream(ref.Stream) s.keepFollowRef(&a.c.followRefs, ref.Stream) return s.events(), nil @@ -2130,7 +2368,11 @@ func (f *followRefs) forget() { // one; making the far end infer which was meant would erase the person's // intent at the wire. func (a *Agent) Steer(text string) (<-chan session.Event, error) { - return a.open(nil, MethodSteer, SubmitArgs{Text: text}) + args := SubmitArgs{Text: text} + if a.c.resendUnanswered() { + args.ClientID = newSendClientID() + } + return a.open(nil, MethodSteer, args) } // open is the stream-opening calls' one body: the call, the [StreamRef] it @@ -2144,6 +2386,11 @@ func (a *Agent) open(ctx context.Context, method string, args any) (<-chan sessi if err := json.Unmarshal(payload, &ref); err != nil { return nil, err } + if ref.Stream == 0 { + done := make(chan session.Event) + close(done) + return done, nil + } return a.c.stream(ref.Stream).events(), nil } @@ -2538,6 +2785,25 @@ func (a *Agent) Transcript() []session.DisplayEntry { return a.entries(MethodTranscript, nil) } +// TranscriptPage reads one bounded page of the conversation's transcript ending +// before the absolute entry index before (zero for the tail). An older engine +// without the door answers "no such method", which comes back unchanged so the +// caller can fall back to the whole-transcript read. +func (a *Agent) TranscriptPage(ctx context.Context, before, limit int) (Page, error) { + payload, err := a.c.call(ctx, MethodTranscriptPage, TranscriptPageArgs{ + Before: before, + Limit: limit, + }) + if err != nil { + return Page{}, err + } + var page Page + if err := json.Unmarshal(payload, &page); err != nil { + return Page{}, err + } + return page, nil +} + // EarlierHistory is the conversation above the session's latest compaction and // where the pass's rewritten copy of it ends, which is what the surface scrolls // back into. Empty for a session that has never been compacted, and empty for a @@ -3082,6 +3348,12 @@ func (a *Agent) MessageClientIDsKnown() bool { return a.welcomeSays(func(w Welcome) bool { return w.MessageClientIDs }) } +// MessageRepeatKnown is whether the holder deduplicates remote sends by device +// and ClientID ([Welcome.MessageRepeat]). +func (a *Agent) MessageRepeatKnown() bool { + return a.welcomeSays(func(w Welcome) bool { return w.MessageRepeat }) +} + // MessageFromKnown is whether the engine keeps who sent a message on the // person's behalf ([Welcome.MessageFrom]). func (a *Agent) MessageFromKnown() bool { @@ -3092,7 +3364,7 @@ func (a *Agent) MessageFromKnown() bool { // sender or an attachment source this engine cannot keep, and nil for one that // carries none or whose engine can. func (a *Agent) refuseUnkeptMarks(message session.Submission) error { - if message.ClientID != "" && !a.MessageClientIDsKnown() { + if message.ClientID != "" && !a.MessageClientIDsKnown() && !a.MessageRepeatKnown() { return errors.New("engine: this engine cannot keep a message's client id; update it before sending") } if message.From != "" && !a.MessageFromKnown() { diff --git a/internal/remote/compat_test.go b/internal/remote/compat_test.go new file mode 100644 index 0000000000..2f8301fbd6 --- /dev/null +++ b/internal/remote/compat_test.go @@ -0,0 +1,121 @@ +package remote + +import ( + "regexp" + "strings" + "sync/atomic" + "testing" +) + +// sessionInstanceJSON matches the random per-Session instance identifier so a +// byte-level golden comparison normalises that per-run token. +var sessionInstanceJSON = regexp.MustCompile(`"sessionInstance":"[A-Z2-7]+"`) + +// machineJSON matches the name of the computer the test happens to run on. It +// is the one other value in a welcome that depends on where the test runs, so it +// is normalised too and nothing else is: every other byte is pinned. +var machineJSON = regexp.MustCompile(`"machine":"[^"]*"`) + +// TestAnOldViewerGetsTheSameBytesAsBefore verifies V14: a local hello without +// a remote viewer stamp receives the exact welcome payload bytes captured on +// the untouched tree, with no remote key present. +func TestAnOldViewerGetsTheSameBytesAsBefore(t *testing.T) { + sess := heldSession(&fakeAgent{}) + viewer := dialSession(t, sess) + frame := viewer.hello(Hello{Version: Version, Surface: "macbook"}) + if frame.Kind != "welcome" { + t.Fatalf("handshake answered %q: %s", frame.Kind, frame.Error) + } + if strings.Contains(string(frame.Payload), `"remote"`) { + t.Fatalf("local welcome carried a remote key: %s", frame.Payload) + } + got := sessionInstanceJSON.ReplaceAllString(string(frame.Payload), `"sessionInstance":""`) + got = machineJSON.ReplaceAllString(got, `"machine":""`) + const golden = `{"machine":"","sessionInstance":"","version":22,"workspace":"/home/somebody/api","sessionFile":"/home/somebody/.codeaf/v3/sessions/-home-somebody-api/one.jsonl","resumed":true,"model":"","build":"dev","note":"session open elsewhere — started a new one","bashBackgroundAfterSeconds":47,"profileDir":"/srv/profile","facts":{"rev":1,"facts":{}},"persistent":true,"driver":{"yours":true},"steerOwner":true,"teams":true,"team_membership_version":1,"delegation":true,"team_settings":true,"wrap_up":true}` + if got != golden { + t.Fatalf("welcome payload changed:\ngot: %s\nwant: %s", got, golden) + } +} + +// TestARemoteWelcomeEchoesTheStampedViewer verifies W1: a remote hello has its +// stamp copied onto the connection and echoed back in Welcome.Remote. +func TestARemoteWelcomeEchoesTheStampedViewer(t *testing.T) { + sess := heldSession(&fakeAgent{}) + viewer := dialSession(t, sess) + stamped := RemoteViewer{ + Device: "dev-laptop", + Label: "laptop", + Watch: true, + Drive: true, + Road: "relay", + } + frame := viewer.hello(Hello{ + Version: Version, + Surface: "spoofed", + Session: sess.engine.SessionFile, + Join: true, + Remote: &stamped, + }) + if frame.Kind != "welcome" { + t.Fatalf("handshake answered %q: %s", frame.Kind, frame.Error) + } + welcome := decode[Welcome](t, frame.Payload) + if welcome.Remote == nil { + t.Fatal("remote welcome omitted Remote") + } + if *welcome.Remote != stamped { + t.Fatalf("welcome echoed %+v, want %+v", *welcome.Remote, stamped) + } +} + +// TestARemoteHelloMustJoinAnOpenChatAndNeverStartOne verifies W1: a remote +// connection whose hello has Join false or New true is refused at the +// handshake before the session opener is ever reached. +func TestARemoteHelloMustJoinAnOpenChatAndNeverStartOne(t *testing.T) { + sess := heldSession(&fakeAgent{}) + stamp := &RemoteViewer{Device: "dev-phone", Label: "phone", Watch: true, Drive: true, Road: "relay"} + + for _, tc := range []struct { + name string + hello Hello + }{ + { + name: "join false is refused", + hello: Hello{ + Version: Version, + Session: sess.engine.SessionFile, + Join: false, + Remote: stamp, + }, + }, + { + name: "new true is refused even with join true", + hello: Hello{ + Version: Version, + Session: sess.engine.SessionFile, + Join: true, + New: true, + Remote: stamp, + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + var opened atomic.Int64 + conn := dialOpening(t, func(Hello) (*Session, error) { + opened.Add(1) + return sess, nil + }) + frame := conn.hello(tc.hello) + if frame.Kind != "fatal" { + t.Fatalf("handshake answered %q, want fatal refusal", frame.Kind) + } + const want = "remote control opens a chat that is already running; it never starts one" + if frame.Error != want { + t.Fatalf("refusal = %q, want %q", frame.Error, want) + } + if got := opened.Load(); got != 0 { + t.Fatalf("refused remote hello called open %d times", got) + } + }) + } +} diff --git a/internal/remote/compress.go b/internal/remote/compress.go index 451b1b3dd2..b7e24103c3 100644 --- a/internal/remote/compress.go +++ b/internal/remote/compress.go @@ -4,11 +4,16 @@ import ( "bytes" "compress/gzip" "encoding/base64" + "encoding/json" "errors" "fmt" "io" ) +// errExpandedFrameTooLarge reports that a compressed frame inflated past the +// caller's bounded line ceiling. +var errExpandedFrameTooLarge = errors.New("remote: expanded frame exceeds the line limit") + // frameEncodingGzip is the capability name exchanged at the version door. const frameEncodingGzip = "gzip" @@ -59,30 +64,67 @@ func compressFrame(frame *Frame, encoding string) error { // encodings before json.Unmarshal can allocate from an untrusted compressed // body. frameCap is already the wire's one ceiling, so it governs both forms. func expandFrame(frame *Frame) error { + return expandFrameCap(frame, 0) +} + +// expandFrameCap restores an encoded frame payload while enforcing an optional +// decoded line limit when maxLine is above zero. +func expandFrameCap(frame *Frame, maxLine int) error { if frame.Encoding == "" { return nil } if frame.Encoding != frameEncodingGzip { return fmt.Errorf("remote: unsupported frame encoding %q", frame.Encoding) } + limit := frameCap + if maxLine > 0 && maxLine < limit { + limit = maxLine + } reader, err := gzip.NewReader(bytes.NewReader(frame.Data)) if err != nil { return fmt.Errorf("remote: compressed frame: %w", err) } defer reader.Close() - payload, err := io.ReadAll(io.LimitReader(reader, frameCap+1)) + payload, err := io.ReadAll(io.LimitReader(reader, int64(limit)+1)) if err != nil { return fmt.Errorf("remote: compressed frame: %w", err) } - if len(payload) > frameCap { + if len(payload) > limit { + if maxLine > 0 && limit == maxLine { + return errExpandedFrameTooLarge + } return errors.New("remote: expanded frame exceeds the frame limit") } frame.Payload = payload frame.Encoding = "" frame.Data = nil + if maxLine > 0 { + size, err := plainFrameLineLen(*frame) + if err != nil { + return err + } + if size > maxLine { + return errExpandedFrameTooLarge + } + } return nil } +// plainFrameLineLen returns the byte length of frame's serialised JSON line +// after decompression, which is the representation a viewer holds in memory. +func plainFrameLineLen(frame Frame) (int, error) { + if frame.Encoding != "" { + if err := expandFrame(&frame); err != nil { + return 0, err + } + } + line, err := json.Marshal(frame) + if err != nil { + return 0, err + } + return len(line), nil +} + // flushFrame makes a frame visible when a caller deliberately supplied a // buffered writer. Pipes and sockets have nothing to flush, but accepting an // io.Writer means the protocol must finish the frame for writers that do. diff --git a/internal/remote/deltawindow.go b/internal/remote/deltawindow.go index 0fb3f193cd..81d4023c16 100644 --- a/internal/remote/deltawindow.go +++ b/internal/remote/deltawindow.go @@ -22,6 +22,20 @@ import ( // cannot fold the desktop's text deltas arriving 25 milliseconds apart. const DefaultDeltaWindow = 33 * time.Millisecond +// DeltaWindowFor returns the engine's streamed-text folding window for a home's +// remote-control posture: [DefaultDeltaWindow] when remote control is on, and +// zero — one frame per event — when it is off. +func DeltaWindowFor(remoteControlOn bool) time.Duration { + return deltaWindowFor(remoteControlOn) +} + +func deltaWindowFor(on bool) time.Duration { + if on { + return DefaultDeltaWindow + } + return 0 +} + // DeltaBytes is the flush threshold for a pending run, not a frame size cap. // Folding a chunk can cross it; a chunk already at or above it travels alone. const DeltaBytes = 4 << 10 diff --git a/internal/remote/deltawindow_test.go b/internal/remote/deltawindow_test.go index 38d63a466a..879da5a8f3 100644 --- a/internal/remote/deltawindow_test.go +++ b/internal/remote/deltawindow_test.go @@ -803,3 +803,96 @@ func TestDeltaWindowStreamsAreIndependent(t *testing.T) { } deltaClose(t, l, firstID, firstSeq) } + +// TestTokenFramesAreFoldedAtTheEngineWindowOnlyWhenRemoteControlIsOn verifies +// V20: when remote control is off the engine's delta window stays zero and +// every token delta travels in its own frame; when remote control is on the +// engine uses the 33 ms default delta window, folding token deltas that arrive +// within the window into one event, one sequence number and one replay ring +// entry so Resume replays the folded run exactly. +func TestTokenFramesAreFoldedAtTheEngineWindowOnlyWhenRemoteControlIsOn(t *testing.T) { + if got := deltaWindowFor(false); got != 0 { + t.Fatalf("deltaWindowFor(false) = %v, want 0", got) + } + if got := DeltaWindowFor(false); got != 0 { + t.Fatalf("DeltaWindowFor(false) = %v, want 0", got) + } + if got := deltaWindowFor(true); got != DefaultDeltaWindow { + t.Fatalf("deltaWindowFor(true) = %v, want %v", got, DefaultDeltaWindow) + } + if got := DeltaWindowFor(true); got != DefaultDeltaWindow { + t.Fatalf("DeltaWindowFor(true) = %v, want %v", got, DefaultDeltaWindow) + } + + chunks := []string{"hel", "lo", " ", "world"} + + // With remote control OFF the engine window is zero: each token delta is + // framed on its own with its own sequence number. + { + agent, _, l, id, stream := deltaSession(t, DeltaWindowFor(false)) + for _, chunk := range chunks { + stream <- session.Event{Kind: session.EventTextDelta, Text: chunk} + } + agent.finish(stream) + var seq uint64 + for _, want := range chunks { + ev := deltaEvent(t, l, id, &seq) + if ev.Kind != session.EventTextDelta || ev.Text != want { + t.Fatalf("off window seq %d = %+v, want text %q", seq, ev, want) + } + } + if seq != uint64(len(chunks)) { + t.Fatalf("off window sent %d events, want %d", seq, len(chunks)) + } + deltaClose(t, l, id, seq) + } + + // With remote control ON the engine window is 33 ms: the leading token delta + // goes out immediately as seq 1, and token deltas arriving within the 33 ms + // window are folded into a single event at seq 2 and a single ring entry + // that Resume replays verbatim. + { + agent, sess, first, id, stream := deltaSession(t, DeltaWindowFor(true)) + for _, chunk := range chunks { + stream <- session.Event{Kind: session.EventTextDelta, Text: chunk} + } + var seq uint64 + if ev := deltaEvent(t, first, id, &seq); ev.Kind != session.EventTextDelta || ev.Text != "hel" || seq != 1 { + t.Fatalf("on window leading event = %+v at seq %d, want \"hel\" at seq 1", ev, seq) + } + if ev := deltaEvent(t, first, id, &seq); ev.Kind != session.EventTextDelta || ev.Text != "lo world" || seq != 2 { + t.Fatalf("on window folded event = %+v at seq %d, want \"lo world\" at seq 2", ev, seq) + } + + resumedAfterFirst := dialSession(t, sess) + resumedAfterFirst.hello(Hello{ + Version: Version, + Watch: true, + Resume: []StreamCursor{{Stream: id, Seq: 1}}, + }) + resumedFromZero := dialSession(t, sess) + resumedFromZero.hello(Hello{ + Version: Version, + Watch: true, + Resume: []StreamCursor{{Stream: id, Seq: 0}}, + }) + + agent.finish(stream) + deltaClose(t, first, id, seq) + + resumeSeq := uint64(1) + if ev := deltaEvent(t, resumedAfterFirst, id, &resumeSeq); ev.Kind != session.EventTextDelta || ev.Text != "lo world" || resumeSeq != 2 { + t.Fatalf("resume after seq 1 replayed %+v at seq %d, want folded \"lo world\" at seq 2", ev, resumeSeq) + } + deltaClose(t, resumedAfterFirst, id, resumeSeq) + + fullSeq := uint64(0) + if ev := deltaEvent(t, resumedFromZero, id, &fullSeq); ev.Kind != session.EventTextDelta || ev.Text != "hel" || fullSeq != 1 { + t.Fatalf("resume from 0 first event = %+v at seq %d, want \"hel\" at seq 1", ev, fullSeq) + } + if ev := deltaEvent(t, resumedFromZero, id, &fullSeq); ev.Kind != session.EventTextDelta || ev.Text != "lo world" || fullSeq != 2 { + t.Fatalf("resume from 0 second event = %+v at seq %d, want \"lo world\" at seq 2", ev, fullSeq) + } + deltaClose(t, resumedFromZero, id, fullSeq) + } +} diff --git a/internal/remote/driver.go b/internal/remote/driver.go index e2c8320496..e7ed039b5d 100644 --- a/internal/remote/driver.go +++ b/internal/remote/driver.go @@ -36,6 +36,7 @@ package remote import ( "errors" "strings" + "time" "github.com/Agent-Field/codeaf/internal/devname" "github.com/Agent-Field/codeaf/internal/home" @@ -90,6 +91,9 @@ func machineLabel(said string) string { // room means writing to other connections and no session lock may be held across // a write to a pipe that might be slow. func (sess *Session) takeLocked(s *server) bool { + // A TAKE, OF ANY KIND, ENDS A KEPT KEYBOARD: whoever holds it now holds it + // because somebody chose that, and no returning viewer may undo a choice. + sess.kept = nil if sess.driver == s { return false } @@ -97,6 +101,59 @@ func (sess *Session) takeLocked(s *server) bool { return true } +// keyboardKeepFor is how long a remote viewer's keyboard is held for it after +// its link ends. It is longer than the road-fallback bound (five seconds, with a +// relay dial on top) and short enough that a viewer coming back after a real +// absence finds the keyboard where the person left it. +const keyboardKeepFor = 30 * time.Second + +// keptKeyboard is who held the keyboard when a remote link ended. The identity +// is the AUTHENTICATED device the door stamped plus the window's own client id: +// the viewer supplies only the second, so no viewer can claim another device's +// keyboard by choosing its id. +type keptKeyboard struct { + device string + clientID string + at time.Time +} + +// keepKeyboardLocked remembers the keyboard of a remote viewer whose link has +// just ended, before it is handed on. A DELIBERATE LEAVE KEEPS NOTHING: a person +// who closed the view has said they are done typing there. +func (sess *Session) keepKeyboardLocked(s *server, deliberate bool) { + if deliberate || s.remote == nil || !s.remote.Drive || s.remote.Device == "" || s.clientID == "" { + return + } + sess.kept = &keptKeyboard{device: s.remote.Device, clientID: s.clientID, at: time.Now()} +} + +// remoteKeepsKeyboardLocked answers whether a remote viewer arriving now is the +// one that holds the keyboard, or held it when its last link ended and nobody +// has used or taken it since (W15, D13). Two shapes of one fact: +// +// - THE NEW LINK ARRIVES BEFORE THE OLD ONE HAS DETACHED (a redial after a +// path went silent): the current driver is the same device and window, and +// the new connection replaces it, so the old pipe's late detach cannot hand +// the keyboard on again. +// - THE OLD LINK ENDED FIRST (a planned road swap closes it before it dials +// the next): the detach handed the keyboard on, to a window of the host or to +// nobody, and [Session.kept] remembers whose it was. +// +// A DIFFERENT DEVICE NEVER MATCHES, however it names itself: the comparison is +// on the device the door authenticated, never on a client id alone. Everything +// else about arrival is unchanged, and a viewer arriving for the first time +// still has to press the key to take the keyboard. +func (sess *Session) remoteKeepsKeyboardLocked(s *server) bool { + if s.remote == nil || s.remote.Device == "" || s.clientID == "" { + return false + } + if d := sess.driver; d != nil && d.remote != nil && d.remote.Device == s.remote.Device && d.clientID == s.clientID { + return true + } + k := sess.kept + return k != nil && k.device == s.remote.Device && k.clientID == s.clientID && time.Since(k.at) < keyboardKeepFor +} + // handOnLocked gives the keyboard to the newest surface still in the room, and // to nobody when the room is empty. // @@ -188,7 +245,7 @@ func (s *server) take() Driver { sess.mu.Lock() // EXCEPT FOR A WATCHER, which is the one surface that asked not to be given // this. It is told who does drive, and nothing moves ([Hello.Watch]). - if s.watching { + if s.watching || (s.remote != nil && !s.remote.Drive) { mine := sess.driverForLocked(s) sess.mu.Unlock() return mine @@ -223,10 +280,13 @@ func (s *server) mayDrive() error { // held it and an empty seat is not an invitation ([Hello.Watch]). The sentence // is its own: `press enter to take it back` would be advice about a key this // surface deliberately does not have. - if s.watching { + if s.watching || (s.remote != nil && !s.remote.Drive) { return errors.New(watchingWord) } if sess.driver == nil || sess.driver == s { + // A window that is allowed to type is using the keyboard, and a kept one + // is a keyboard nobody has used: using it ends the keeping. + sess.kept = nil return nil } return errors.New(notDrivingWord(sess.driverForLocked(s))) @@ -335,7 +395,7 @@ func notDrivingWord(driver Driver) string { // that does not know the frame is simply left attached and reading, which is // what every build before version 13 does and is not broken. func (sess *Session) tellMoved(arriving *server, hello Hello) { - if arriving == nil || arriving.watching || hello.Back { + if arriving == nil || arriving.watching || arriving.remote != nil || hello.Back { return } sess.mu.Lock() diff --git a/internal/remote/driver_remote_test.go b/internal/remote/driver_remote_test.go new file mode 100644 index 0000000000..1ec3f7745b --- /dev/null +++ b/internal/remote/driver_remote_test.go @@ -0,0 +1,370 @@ +package remote + +import ( + "testing" + "time" +) + +// TestTwoRemoteViewersOneHoldsTheKeyboardAndTheOtherIsToldWho verifies V6 (W2, +// W11): remote viewers arrive passively without displacing the current driver +// or sending moved frames, report the authenticated Remote.Label rather than +// Hello.Surface, refuse typing without the keyboard using the not-driving +// sentence naming the holder's label, move the keyboard only via MethodTake +// when Remote.Drive is true, and never move it for a watch-only remote viewer. +func TestTwoRemoteViewersOneHoldsTheKeyboardAndTheOtherIsToldWho(t *testing.T) { + agent := &fakeAgent{} + sess := heldSession(agent) + + // A local window opens the conversation and holds the keyboard. + desk := dialSession(t, sess) + deskWelcome := decode[Welcome](t, desk.hello(Hello{ + Version: Version, + Surface: "macbook", + }).Payload) + if !deskWelcome.Driver.Yours { + t.Fatalf("local window did not start with the keyboard: %+v", deskWelcome.Driver) + } + + // First remote-drive viewer ("laptop") arrives; it carries a spoofed Surface + // and Back=false, yet must not displace the local window or fire moved. + laptop := dialSession(t, sess) + laptopWelcome := decode[Welcome](t, laptop.hello(Hello{ + Version: Version, + Surface: "spoofed-desk", + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-laptop", + Label: "laptop", + Watch: true, + Drive: true, + Road: "relay", + }, + }).Payload) + if laptopWelcome.Driver.Yours { + t.Fatalf("remote viewer took the keyboard from the local window on arrival: %+v", laptopWelcome.Driver) + } + if laptopWelcome.Driver.Machine != "macbook" { + t.Fatalf("remote viewer was told the keyboard is on %q, want macbook", laptopWelcome.Driver.Machine) + } + if told := driverOf(desk); !told.Yours { + t.Fatalf("local window lost the keyboard on remote arrival: %+v", told) + } + for _, frame := range drain(desk) { + if frame.Kind == "moved" { + t.Fatalf("remote viewer arrival sent a moved frame to the local window: %+v", frame) + } + } + + // Laptop takes the keyboard explicitly via MethodTake. + took := decode[Driver](t, laptop.ok(1, MethodTake, nil).Payload) + if !took.Yours { + t.Fatalf("laptop did not receive the keyboard on MethodTake: %+v", took) + } + // The local window is told the keyboard moved to "laptop" (Remote.Label), + // never "spoofed-desk" (Hello.Surface). + deskTold := driverSaying(desk, "laptop") + if deskTold.Yours { + t.Fatalf("local window still believes it holds the keyboard: %+v", deskTold) + } + + // Second remote-drive viewer ("phone") arrives; it does not move the + // keyboard from "laptop" nor send a moved frame. + phone := dialSession(t, sess) + phoneWelcome := decode[Welcome](t, phone.hello(Hello{ + Version: Version, + Surface: "spoofed-phone", + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-phone", + Label: "phone", + Watch: true, + Drive: true, + Road: "relay", + }, + }).Payload) + if phoneWelcome.Driver.Yours { + t.Fatalf("second remote viewer took the keyboard on arrival: %+v", phoneWelcome.Driver) + } + if phoneWelcome.Driver.Machine != "laptop" { + t.Fatalf("second remote viewer was told the keyboard is on %q, want laptop", phoneWelcome.Driver.Machine) + } + if told := driverOf(laptop); !told.Yours { + t.Fatalf("first remote viewer lost the keyboard when the second arrived: %+v", told) + } + for _, frame := range append(drain(laptop), drain(desk)...) { + if frame.Kind == "moved" { + t.Fatalf("second remote viewer arrival sent a moved frame: %+v", frame) + } + } + + // Phone does not hold the keyboard, so MethodSubmit is refused with the + // existing notDrivingWord sentence naming "laptop". + refused := phone.call(1, MethodSubmit, SubmitArgs{Text: "from phone without keyboard"}) + wantRefusal := "the keyboard is on laptop right now — press enter here to move it here" + if refused.Error != wantRefusal { + t.Fatalf("phone Submit without keyboard answered %q, want %q", refused.Error, wantRefusal) + } + + // Phone takes the keyboard with MethodTake; laptop is told "phone" now drives. + phoneTook := decode[Driver](t, phone.ok(2, MethodTake, nil).Payload) + if !phoneTook.Yours { + t.Fatalf("phone did not receive the keyboard on MethodTake: %+v", phoneTook) + } + laptopTold := driverSaying(laptop, "phone") + if laptopTold.Yours || laptopTold.Machine != "phone" { + t.Fatalf("laptop was told %+v after phone took the keyboard, want Machine=phone", laptopTold) + } + laptopRefused := laptop.call(2, MethodSubmit, SubmitArgs{Text: "from laptop after losing keyboard"}) + wantLaptopRefusal := "the keyboard is on phone right now — press enter here to move it here" + if laptopRefused.Error != wantLaptopRefusal { + t.Fatalf("laptop Submit without keyboard answered %q, want %q", laptopRefused.Error, wantLaptopRefusal) + } + phone.ok(3, MethodSubmit, SubmitArgs{Text: "from phone with keyboard"}) + + // A remote watch-only viewer arrives carrying Watch:false, Back:true, + // Surface:"desk"; it still arrives watch-only and its MethodTake moves nothing. + watcher := dialSession(t, sess) + watcherWelcome := decode[Welcome](t, watcher.hello(Hello{ + Version: Version, + Surface: "desk", + Watch: false, + Back: true, + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-watch", + Label: "tablet", + Watch: true, + Drive: false, + Road: "relay", + }, + }).Payload) + if watcherWelcome.Driver.Yours { + t.Fatalf("watch-only remote viewer was given the keyboard on arrival: %+v", watcherWelcome.Driver) + } + if watcherWelcome.Driver.Machine != "phone" { + t.Fatalf("watch-only remote viewer was told the keyboard is on %q, want phone", watcherWelcome.Driver.Machine) + } + watchTake := watcher.call(1, MethodTake, nil) + if watchTake.Error == "" { + t.Fatalf("watch-only remote viewer MethodTake succeeded over the wire: %+v", watchTake) + } + // Phone still holds the keyboard and can submit. + phone.ok(4, MethodSubmit, SubmitArgs{Text: "still driving on phone"}) +} + +// TestARemoteViewerCannotSpoofItsGrantOrItsLabel verifies W2 and W11: a remote +// hello carrying Watch:false, Back:true, Surface:"desk" still arrives +// watch-only when the stamp says Drive:false, and a drive viewer's label is +// sanitised from Remote.Label rather than Hello.Surface. +func TestARemoteViewerCannotSpoofItsGrantOrItsLabel(t *testing.T) { + agent := &fakeAgent{} + sess := heldSession(agent) + + // Watch-only viewer arrives into an empty room trying to claim Watch:false. + watchOnly := dialSession(t, sess) + watchWelcome := decode[Welcome](t, watchOnly.hello(Hello{ + Version: Version, + Surface: "desk", + Watch: false, + Back: true, + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-1", + Label: "watch-pad", + Watch: true, + Drive: false, + Road: "relay", + }, + }).Payload) + if watchWelcome.Driver.Yours { + t.Fatalf("watch-only viewer arrived with Yours=true in an empty room: %+v", watchWelcome.Driver) + } + + // Drive viewer arrives with an escape sequence in Remote.Label and + // Surface:"desk"; after it takes the keyboard, others see the sanitised + // Remote.Label and never "desk". + driver := dialSession(t, sess) + driver.hello(Hello{ + Version: Version, + Surface: "desk", + Watch: false, + Back: true, + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-2", + Label: " la\x1b[2Jptop\n ", + Watch: true, + Drive: true, + Road: "relay", + }, + }) + if arrivalNote := driverOf(watchOnly); arrivalNote.Yours || arrivalNote.Machine != "" { + t.Fatalf("remote drive arrival took the keyboard before MethodTake: %+v", arrivalNote) + } + driver.ok(1, MethodTake, nil) + + told := driverOf(watchOnly) + if told.Machine != "la[2Jptop" { + t.Fatalf("watch-only viewer was told the driver is %q, want sanitised Remote.Label %q", told.Machine, "la[2Jptop") + } +} + +// ── the keyboard across a road swap (phase 2, D13, W15) ───────────────────── + +// remoteArrival is a viewer's hello as the door writes it: Back is ALWAYS true +// on a remote connection, the stamp names the authenticated device, and the +// surface's own client id is the only part the viewer chooses. +func remoteArrival(sess *Session, device, label, clientID string) Hello { + return Hello{ + Version: Version, + Surface: "ignored", + Session: sess.engine.SessionFile, + Join: true, + Back: true, + ClientID: clientID, + Remote: &RemoteViewer{Device: device, Label: label, Watch: true, Drive: true, Road: "relay"}, + } +} + +// TestARoadSwapKeepsTheKeyboardWithTheSameDeviceAndNeverGivesItToAnother pins +// W15 and D13: a remote viewer that holds the keyboard and comes back through a +// different link (a road swap closes the old link first, a silent path leaves it +// attached) still holds it, and that is true only for the SAME authenticated +// device and window. A first arrival still has to ask for the keyboard. +func TestARoadSwapKeepsTheKeyboardWithTheSameDeviceAndNeverGivesItToAnother(t *testing.T) { + // holder sets up the room: the host's own window, then a remote viewer that + // has taken the keyboard by asking for it. + holder := func(t *testing.T) (*Session, *link, *link) { + t.Helper() + sess := heldSession(&fakeAgent{}) + desk := dialSession(t, sess) + desk.hello(Hello{Version: Version, Surface: "macbook"}) + laptop := dialSession(t, sess) + laptop.hello(remoteArrival(sess, "dev-laptop", "laptop", "window-1")) + laptop.ok(1, MethodTake, nil) + driverSaying(desk, "laptop") + return sess, desk, laptop + } + waitDetached := func(t *testing.T, sess *Session, left int) { + t.Helper() + waitFor(t, "the host to see the link end", func() bool { return sess.Attached() == left }) + } + + t.Run("the old link ended first", func(t *testing.T) { + sess, desk, laptop := holder(t) + _ = laptop.end() + waitDetached(t, sess, 1) + // The detach handed the keyboard to the host's own window, as it always did. + if told := driverOf(desk); !told.Yours { + t.Fatalf("the host's window was not handed the keyboard when the link ended: %+v", told) + } + back := dialSession(t, sess) + welcome := decode[Welcome](t, back.hello(remoteArrival(sess, "dev-laptop", "laptop", "window-1")).Payload) + if !welcome.Driver.Yours { + t.Fatalf("the same device and window came back without the keyboard: %+v", welcome.Driver) + } + if told := driverSaying(desk, "laptop"); told.Yours { + t.Fatalf("the host's window still believes it types: %+v", told) + } + back.ok(1, MethodSubmit, SubmitArgs{Text: "after the swap"}) + }) + + t.Run("the new link arrives before the old one has detached", func(t *testing.T) { + sess, desk, laptop := holder(t) + back := dialSession(t, sess) + welcome := decode[Welcome](t, back.hello(remoteArrival(sess, "dev-laptop", "laptop", "window-1")).Payload) + if !welcome.Driver.Yours { + t.Fatalf("the replacing link did not take the keyboard from its own stale one: %+v", welcome.Driver) + } + // The stale link ending later must not hand the keyboard to anyone. + _ = laptop.end() + waitDetached(t, sess, 2) + for _, frame := range drain(desk) { + if frame.Kind == "driver" && decode[Driver](t, frame.Payload).Machine != "laptop" { + t.Fatalf("the stale link's late end moved the keyboard: %+v", frame) + } + } + back.ok(1, MethodSubmit, SubmitArgs{Text: "still the viewer's"}) + }) + + t.Run("another device never gets it, whatever id it claims", func(t *testing.T) { + sess, desk, laptop := holder(t) + _ = laptop.end() + waitDetached(t, sess, 1) + _ = driverOf(desk) + other := dialSession(t, sess) + welcome := decode[Welcome](t, other.hello(remoteArrival(sess, "dev-phone", "phone", "window-1")).Payload) + if welcome.Driver.Yours { + t.Fatalf("another device took the keyboard by repeating a client id: %+v", welcome.Driver) + } + }) + + t.Run("the same device in another window never gets it", func(t *testing.T) { + sess, desk, laptop := holder(t) + _ = laptop.end() + waitDetached(t, sess, 1) + _ = driverOf(desk) + second := dialSession(t, sess) + welcome := decode[Welcome](t, second.hello(remoteArrival(sess, "dev-laptop", "laptop", "window-2")).Payload) + if welcome.Driver.Yours { + t.Fatalf("a second window of the same device took the keyboard: %+v", welcome.Driver) + } + }) + + t.Run("a viewer that arrives for the first time still has to ask", func(t *testing.T) { + sess := heldSession(&fakeAgent{}) + desk := dialSession(t, sess) + desk.hello(Hello{Version: Version, Surface: "macbook"}) + first := dialSession(t, sess) + welcome := decode[Welcome](t, first.hello(remoteArrival(sess, "dev-laptop", "laptop", "window-1")).Payload) + if welcome.Driver.Yours { + t.Fatalf("a first arrival took the keyboard: %+v", welcome.Driver) + } + }) + + t.Run("a viewer that left on purpose does not get it back", func(t *testing.T) { + sess, desk, laptop := holder(t) + laptop.ok(2, MethodDetach, nil) + _ = laptop.end() + waitDetached(t, sess, 1) + _ = driverOf(desk) + back := dialSession(t, sess) + welcome := decode[Welcome](t, back.hello(remoteArrival(sess, "dev-laptop", "laptop", "window-1")).Payload) + if welcome.Driver.Yours { + t.Fatalf("a viewer that closed the view took the keyboard back: %+v", welcome.Driver) + } + }) + + t.Run("a keyboard somebody used in the meantime stays with them", func(t *testing.T) { + sess, desk, laptop := holder(t) + _ = laptop.end() + waitDetached(t, sess, 1) + _ = driverOf(desk) + desk.ok(1, MethodSubmit, SubmitArgs{Text: "typed on the host while the link was down"}) + back := dialSession(t, sess) + welcome := decode[Welcome](t, back.hello(remoteArrival(sess, "dev-laptop", "laptop", "window-1")).Payload) + if welcome.Driver.Yours { + t.Fatalf("a returning viewer took the keyboard back from a window that had used it: %+v", welcome.Driver) + } + }) + + t.Run("a keyboard kept too long is let go", func(t *testing.T) { + sess, desk, laptop := holder(t) + _ = laptop.end() + waitDetached(t, sess, 1) + _ = driverOf(desk) + sess.mu.Lock() + sess.kept.at = time.Now().Add(-2 * keyboardKeepFor) + sess.mu.Unlock() + back := dialSession(t, sess) + welcome := decode[Welcome](t, back.hello(remoteArrival(sess, "dev-laptop", "laptop", "window-1")).Payload) + if welcome.Driver.Yours { + t.Fatalf("a viewer back after the keeping window took the keyboard: %+v", welcome.Driver) + } + }) +} diff --git a/internal/remote/gap_test.go b/internal/remote/gap_test.go new file mode 100644 index 0000000000..7c24aab935 --- /dev/null +++ b/internal/remote/gap_test.go @@ -0,0 +1,299 @@ +package remote + +import ( + "encoding/json" + "io" + "reflect" + "strings" + "sync" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/session" +) + +// TestATruncatedReplayIsSignalledAndNeverLoopsTheResume verifies W7: when a +// running stream's ring evicts old events (by byte bound or event count) and a +// resuming surface presents a cursor with seq+1 < ring.first, the server sends +// exactly one "gap" frame with {stream, have, first} ahead of the retained +// events; a second resume from the updated cursor sends no gap; a cursor at or +// after first-1 receives no gap; the ring never holds more than ringBytes plus +// the newest event; and an older reader that ignores unknown frame kinds still +// decodes the retained events. +func TestATruncatedReplayIsSignalledAndNeverLoopsTheResume(t *testing.T) { + savedBackoff := firstBackoff + firstBackoff = 5 * time.Millisecond + t.Cleanup(func() { firstBackoff = savedBackoff }) + + savedByteLimit := ringByteLimit + savedEventLimit := ringEventLimit + ringByteLimit = 240 + t.Cleanup(func() { + ringByteLimit = savedByteLimit + ringEventLimit = savedEventLimit + }) + + // 1. Unit invariant on ring: never holds more than ringBytes plus the newest + // event, always keeps the newest event even when larger than ringBytes, and + // keeps first exact. + t.Run("ring byte bound keeps newest event and exact first", func(t *testing.T) { + r := &ring{first: 1} + for i := 1; i <= 10; i++ { + payload := mustJSON(WireEvent(session.Event{ + Kind: session.EventTextDelta, + Text: strings.Repeat("x", 60), + })) + seq := r.add(payload) + if seq != uint64(i) { + t.Fatalf("seq = %d, want %d", seq, i) + } + newest := len(payload) + if r.bytes > ringByteLimit+newest { + t.Fatalf("ring bytes %d exceeded cap %d + newest %d", r.bytes, ringByteLimit, newest) + } + if len(r.events) > 1 && r.bytes > ringByteLimit { + t.Fatalf("ring with %d events held %d bytes > cap %d", len(r.events), r.bytes, ringByteLimit) + } + if wantFirst := r.last - uint64(len(r.events)) + 1; r.first != wantFirst { + t.Fatalf("ring.first = %d, want %d", r.first, wantFirst) + } + } + if r.first <= 1 { + t.Fatalf("ring did not evict under byte cap: first=%d", r.first) + } + + // A single oversized event larger than ringByteLimit is still kept as the sole entry. + huge := mustJSON(WireEvent(session.Event{ + Kind: session.EventTextDelta, + Text: strings.Repeat("H", ringByteLimit*3), + })) + r.add(huge) + if len(r.events) != 1 || r.first != r.last { + t.Fatalf("oversized newest event not kept alone: len=%d first=%d last=%d", len(r.events), r.first, r.last) + } + }) + + // 2. End-to-end roaming client + real Session: gap frame on first resume, no + // gap on second resume from the new cursor, and no gap for cursor >= first-1. + t.Run("roaming resume receives one gap frame then retained events and second resume gets no gap", func(t *testing.T) { + agent := &fakeAgent{model: "a/b"} + sess := NewSession(engineOn(agent), true) + + var mu sync.Mutex + var surfaces []io.ReadWriteCloser + dialer := func() (io.ReadWriteCloser, error) { + surface, engine := Pipe() + guard.Go("remote/test-w7-serve", func() { + _ = ServeAttach(engine, engine, AttachOptions{ + Open: func(Hello) (*Session, error) { return sess, nil }, + }) + _ = engine.Close() + }) + mu.Lock() + surfaces = append(surfaces, surface) + mu.Unlock() + return surface, nil + } + + var gapsMu sync.Mutex + var gaps []Gap + client, err := Roam("devbox", Hello{Workspace: "app"}, Roaming{ + Dial: dialer, + Window: time.Second, + OnGap: func(g Gap) { + gapsMu.Lock() + gaps = append(gaps, g) + gapsMu.Unlock() + }, + }) + if err != nil { + t.Fatalf("roam: %v", err) + } + t.Cleanup(func() { _ = client.Close() }) + + events, err := client.Agent().Submit(nil, "stream a long reply") + if err != nil { + t.Fatalf("submit: %v", err) + } + waitFor(t, "turn to open", func() bool { return agent.stream(0) != nil }) + turn := agent.stream(0) + + // Deliver seq 1 and seq 2 to the connected client. + turn <- session.Event{Kind: session.EventTextDelta, Text: "e1"} + turn <- session.Event{Kind: session.EventTextDelta, Text: "e2"} + for _, want := range []string{"e1", "e2"} { + if ev, ok := nextEvent(t, events); !ok || ev.Text != want { + t.Fatalf("got %q (ok=%v), want %q", ev.Text, ok, want) + } + } + + // Cut link 0 so the client is offline with cursor Have=2. + // Hold a dial gate so we can overflow the ring while the client is disconnected. + mu.Lock() + firstConn := surfaces[0] + mu.Unlock() + + // Overflow the ring on the server while no surface is reading. + // Emit 6 events of ~80 bytes each so under ringByteLimit=240 the oldest + // events (seqs 1..6) are evicted and only the tail remains. + sess.mu.Lock() + delete(sess.surfaces, sess.driver) + sess.mu.Unlock() + + for _, tok := range []string{ + "e3-" + strings.Repeat("a", 50), + "e4-" + strings.Repeat("b", 50), + "e5-" + strings.Repeat("c", 50), + "e6-" + strings.Repeat("d", 50), + "e7-" + strings.Repeat("e", 50), + "e8-" + strings.Repeat("f", 50), + } { + turn <- session.Event{Kind: session.EventTextDelta, Text: tok} + } + waitFor(t, "ring to reach seq 8 and evict older events", func() bool { + sess.mu.Lock() + defer sess.mu.Unlock() + r := sess.rings[1] + return r != nil && r.last == 8 && r.first > 3 + }) + sess.mu.Lock() + wantFirst := sess.rings[1].first + sess.mu.Unlock() + + // Verify directly at wire level that cursor at first-1 and cursor at first get NO gap frame. + sess.mu.Lock() + atBoundary := sess.replayLocked([]StreamCursor{{Stream: 1, Seq: wantFirst - 1}}) + afterBoundary := sess.replayLocked([]StreamCursor{{Stream: 1, Seq: wantFirst}}) + sess.mu.Unlock() + for _, f := range append(atBoundary, afterBoundary...) { + if f.Kind == "gap" { + t.Fatalf("cursor at/after first-1 (first=%d) received unexpected gap frame: %+v", wantFirst, f) + } + } + + // Now close the client's first pipe to trigger redial from Have=2 (< wantFirst-1). + _ = firstConn.Close() + + // Read the retained events from seq=wantFirst..8 off the resumed turn. + wantCount := int(8 - wantFirst + 1) + var received []string + for i := 0; i < wantCount; i++ { + ev, ok := nextEvent(t, events) + if !ok { + t.Fatalf("stream closed early after %d events", i) + } + received = append(received, ev.Text[:2]) + } + if len(received) != wantCount || received[len(received)-1] != "e8" { + t.Fatalf("retained replay delivered %v (want %d events ending in e8)", received, wantCount) + } + + gapsMu.Lock() + gotGaps := append([]Gap(nil), gaps...) + gapsMu.Unlock() + if !reflect.DeepEqual(gotGaps, []Gap{{Stream: 1, Have: 2, First: wantFirst}}) { + t.Fatalf("OnGap received %+v, want [{Stream:1 Have:2 First:%d}]", gotGaps, wantFirst) + } + + // Cut the second pipe and let the client redial a SECOND time from its + // updated cursor (seq=8). No second gap frame may be sent. + waitFor(t, "second connection to settle", func() bool { + mu.Lock() + n := len(surfaces) + mu.Unlock() + return n >= 2 && client.LinkNote() == "" + }) + mu.Lock() + secondConn := surfaces[1] + mu.Unlock() + _ = secondConn.Close() + + waitFor(t, "third connection to settle", func() bool { + mu.Lock() + n := len(surfaces) + mu.Unlock() + return n >= 3 && client.LinkNote() == "" + }) + + turn <- session.Event{Kind: session.EventTextDelta, Text: "e9"} + agent.finish(turn) + if ev, ok := nextEvent(t, events); !ok || ev.Text != "e9" { + t.Fatalf("after second resume got %q (ok=%v), want e9", ev.Text, ok) + } + for range events { + } + + gapsMu.Lock() + finalGaps := append([]Gap(nil), gaps...) + gapsMu.Unlock() + if len(finalGaps) != 1 { + t.Fatalf("second resume produced extra gap frames: %+v", finalGaps) + } + }) + + // 3. An old-style client (nil OnGap / Dial reader that ignores unknown frame + // kinds) still decodes all retained events after a gap frame. + t.Run("old reader ignoring gap frame decodes the retained events", func(t *testing.T) { + agent := &fakeAgent{model: "a/b"} + sess := NewSession(engineOn(agent), true) + + firstViewer := dialSession(t, sess) + if frame := firstViewer.hello(Hello{Version: Version}); frame.Kind != "welcome" { + t.Fatalf("hello: %s", frame.Error) + } + ref := decode[StreamRef](t, firstViewer.ok(1, MethodSubmit, SubmitArgs{Text: "go"}).Payload) + waitFor(t, "turn to open", func() bool { return agent.stream(0) != nil }) + turn := agent.stream(0) + _ = firstViewer.toward.Close() + + for _, tok := range []string{ + "m1-" + strings.Repeat("a", 80), + "m2-" + strings.Repeat("b", 80), + "m3-" + strings.Repeat("c", 80), + "m4-" + strings.Repeat("d", 80), + } { + turn <- session.Event{Kind: session.EventTextDelta, Text: tok} + } + waitFor(t, "ring to evict m1", func() bool { + sess.mu.Lock() + defer sess.mu.Unlock() + r := sess.rings[ref.Stream] + return r != nil && r.last == 4 && r.first > 1 + }) + + // Connect a standard Dial client (no Roaming / no OnGap) resuming from seq 0. + surface, engine := Pipe() + guard.Go("remote/test-w7-old-client", func() { + _ = ServeAttach(engine, engine, AttachOptions{ + Open: func(Hello) (*Session, error) { return sess, nil }, + }) + _ = engine.Close() + }) + oldClient, err := Dial(surface, "devbox", Hello{ + Resume: []StreamCursor{{Stream: ref.Stream, Seq: 0}}, + }) + if err != nil { + t.Fatalf("Dial: %v", err) + } + t.Cleanup(func() { _ = oldClient.Close() }) + + _, liveEvents := oldClient.Live() + if liveEvents == nil { + t.Fatal("expected live stream on welcome") + } + agent.finish(turn) + + var got []string + for ev := range liveEvents { + if ev.Kind == session.EventTextDelta { + got = append(got, ev.Text[:2]) + } + } + if len(got) == 0 || got[len(got)-1] != "m4" { + t.Fatalf("old client decoded %v, want retained events ending in m4", got) + } + }) +} + +var _ = json.Unmarshal diff --git a/internal/remote/guest.go b/internal/remote/guest.go new file mode 100644 index 0000000000..cd1a92e3cb --- /dev/null +++ b/internal/remote/guest.go @@ -0,0 +1,95 @@ +package remote + +import "github.com/Agent-Field/codeaf/internal/chatlist" + +// HostName returns this machine's own short name for guest refusal sentences. +// It defaults to [MachineName] so the holder and every refusal sentence name +// the computer the same way the window bar does. +var HostName = MachineName + +// guestWatchMay is the complete allow-list of wire methods a watch-only remote +// viewer may call. Everything not on this list is refused by default so a +// method added later cannot leak host files or mutate a conversation unless it +// is explicitly granted here. +var guestWatchMay = map[string]bool{ + MethodTaskRoom: true, + MethodTaskWatch: true, + MethodQuestionWatch: true, + MethodPlanTaskPage: true, + MethodAppTasks: true, + MethodAppTask: true, + MethodAppQuickTasks: true, + MethodAppProgramActions: true, + MethodRenderList: true, + MethodRenderGet: true, + MethodDetach: true, + MethodPing: true, + MethodCheckWork: true, + MethodTranscriptPage: true, + MethodModel: true, + MethodUsage: true, + MethodTitle: true, + MethodContextTokens: true, + MethodHeldQuestions: true, + MethodObserve: true, + MethodUnobserve: true, + MethodAutonomy: true, + MethodSpendRail: true, + MethodResolvedEffort: true, + MethodEffort: true, + MethodResolvedApproval: true, + MethodHarness: true, + MethodAttachedSkills: true, +} + +// guestDriveMay is the complete allow-list of wire methods a drive-permitted +// remote viewer may call. It extends [guestWatchMay] with the conversation +// input, stop, keyboard, and one-turn approval doors while keeping host shell, +// file, posture, and session lifecycle doors closed. +var guestDriveMay = func() map[string]bool { + allowed := make(map[string]bool, len(guestWatchMay)+10) + for method := range guestWatchMay { + allowed[method] = true + } + for _, method := range []string{ + MethodSubmit, + MethodFollowUp, + MethodSteer, + MethodUnqueueFollowUp, + MethodInterrupt, + MethodStopWork, + MethodTake, + MethodTyping, + MethodConsent, + MethodQuestionResolve, + } { + allowed[method] = true + } + return allowed +}() + +// GuestMay reports whether a remote viewer with the given drive grant is +// permitted to invoke method on the holder. +func GuestMay(method string, drive bool) bool { + if drive { + return guestDriveMay[method] + } + return guestWatchMay[method] +} + +func guestMay(method string, drive bool) bool { + return GuestMay(method, drive) +} + +// GuestRefusal returns the person-facing sentence explaining why method is +// refused to a remote viewer on host, or the empty string when the allow-list +// permits the call. +func GuestRefusal(host, method string, drive bool) string { + if GuestMay(method, drive) { + return "" + } + if !drive && guestDriveMay[method] { + return chatlist.LiveWatchOnly(host) + } + return chatlist.LiveNotAllowedHere(host) +} diff --git a/internal/remote/guest_test.go b/internal/remote/guest_test.go new file mode 100644 index 0000000000..6d17853d43 --- /dev/null +++ b/internal/remote/guest_test.go @@ -0,0 +1,511 @@ +package remote + +import ( + "go/ast" + "go/token" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/session" +) + +type countingGuestAgent struct { + *fakeAgent + mu sync.Mutex + stopWorks int + questions []session.Answer +} + +func (c *countingGuestAgent) StopWork() error { + c.mu.Lock() + defer c.mu.Unlock() + c.stopWorks++ + return nil +} + +func (c *countingGuestAgent) ResolveQuestion(answer session.Answer) error { + c.mu.Lock() + defer c.mu.Unlock() + c.questions = append(c.questions, answer) + return nil +} + +// TestAWatchOnlyViewerCannotSendSteerOrAnswer verifies V11: a remote watch-only +// connection gets exactly chatlist.LiveWatchOnly(host) for Submit, FollowUp, +// Steer, Interrupt, StopWork, Consent, QuestionResolve, and Take (which +// answers and moves nothing), and the agent sees none of them. +func TestAWatchOnlyViewerCannotSendSteerOrAnswer(t *testing.T) { + base := &fakeAgent{} + agent := &countingGuestAgent{fakeAgent: base} + engine := engineOn(base) + engine.Agent = agent + sess := NewSession(engine, true) + + // A local window holds the keyboard so we can also prove Take moves nothing. + owner := dialSession(t, sess) + owner.hello(Hello{Version: Version, Surface: "macbook"}) + + viewer := dialSession(t, sess) + welcomeFrame := viewer.hello(Hello{ + Version: Version, + Surface: "viewer", + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-watch", + Label: "tablet", + Watch: true, + Drive: false, + Road: "relay", + }, + }) + if welcomeFrame.Kind != "welcome" { + t.Fatalf("watch-only handshake answered %q: %s", welcomeFrame.Kind, welcomeFrame.Error) + } + + want := chatlist.LiveWatchOnly(HostName()) + for id, call := range []struct { + method string + payload any + }{ + {MethodSubmit, SubmitArgs{Text: "hello"}}, + {MethodFollowUp, SubmitArgs{Text: "more"}}, + {MethodSteer, SubmitArgs{Text: "change direction"}}, + {MethodInterrupt, InterruptArgs{}}, + {MethodStopWork, nil}, + {MethodConsent, ConsentArgs{ID: 1, Allow: true}}, + {MethodQuestionResolve, QuestionArgs{Answer: session.Answer{Key: "k"}}}, + {MethodTake, nil}, + } { + result := viewer.call(uint64(id+1), call.method, call.payload) + if result.Error != want { + t.Fatalf("%s on watch-only viewer answered error %q, want %q", call.method, result.Error, want) + } + } + + if len(base.sent) != 0 { + t.Fatalf("agent saw Submit: %v", base.sent) + } + if len(base.follows) != 0 { + t.Fatalf("agent saw FollowUp: %v", base.follows) + } + if len(base.steered) != 0 { + t.Fatalf("agent saw Steer: %v", base.steered) + } + if base.interrupts != 0 { + t.Fatalf("agent saw %d Interrupt calls", base.interrupts) + } + if len(base.consents) != 0 { + t.Fatalf("agent saw Consent: %v", base.consents) + } + agent.mu.Lock() + stopWorks := agent.stopWorks + questions := len(agent.questions) + agent.mu.Unlock() + if stopWorks != 0 { + t.Fatalf("agent saw %d StopWork calls", stopWorks) + } + if questions != 0 { + t.Fatalf("agent saw %d ResolveQuestion calls", questions) + } + + // Take moved nothing: the owner still holds the keyboard and can submit. + owner.ok(99, MethodSubmit, SubmitArgs{Text: "owner still drives"}) +} + +// TestEveryMethodIsRefusedToAGuestUnlessItsListSaysOtherwise verifies W3: every +// wire method constant in internal/remote is checked against the literal guest +// watch and drive allow-lists from the specification contract. +func TestEveryMethodIsRefusedToAGuestUnlessItsListSaysOtherwise(t *testing.T) { + contractWatchMay := map[string]bool{ + // Every key of watcherReads: + "Task.Room": true, + "Task.Watch": true, + "Question.Watch": true, + "PlanTaskPage": true, + "App.Tasks": true, + "App.Task": true, + "App.QuickTasks": true, + "App.ProgramActions": true, + "Render.List": true, + "Render.Get": true, + "Detach": true, + "Ping": true, + "CheckWork": true, + // Plus the conversation read and observer doors: + "Transcript.Page": true, + "Model": true, + "Usage": true, + "Title": true, + "ContextTokens": true, + "Held.Questions": true, + "Observe": true, + "Unobserve": true, + "Autonomy": true, + "SpendRail": true, + "ResolvedEffort": true, + "Effort": true, + "ResolvedApproval": true, + "ResolveHarness": true, + "AttachedSkills": true, + } + + contractDriveMay := map[string]bool{} + for method := range contractWatchMay { + contractDriveMay[method] = true + } + for _, method := range []string{ + "Submit", + "FollowUp", + "Steer", + "UnqueueFollowUp", + "Interrupt", + "StopWork", + "Take", + "Typing", + "ResolveConsent", + "ResolveQuestion", + } { + contractDriveMay[method] = true + } + + allMethods := []struct { + name string + method string + }{ + {"MethodAnswerLaneOffer", MethodAnswerLaneOffer}, + {"MethodAppContinueInterrupted", MethodAppContinueInterrupted}, + {"MethodAppMoveToTask", MethodAppMoveToTask}, + {"MethodAppProgramActions", MethodAppProgramActions}, + {"MethodAppQuickTaskAction", MethodAppQuickTaskAction}, + {"MethodAppQuickTasks", MethodAppQuickTasks}, + {"MethodAppRename", MethodAppRename}, + {"MethodAppResumeAfterClose", MethodAppResumeAfterClose}, + {"MethodAppResumeAfterQuit", MethodAppResumeAfterQuit}, + {"MethodAppTask", MethodAppTask}, + {"MethodAppTaskAction", MethodAppTaskAction}, + {"MethodAppTaskRouting", MethodAppTaskRouting}, + {"MethodAppTaskRoutingAct", MethodAppTaskRoutingAct}, + {"MethodAppTaskRoutingOptions", MethodAppTaskRoutingOptions}, + {"MethodAppTasks", MethodAppTasks}, + {"MethodAttachSkills", MethodAttachSkills}, + {"MethodAttachedSkills", MethodAttachedSkills}, + {"MethodAutomationsActive", MethodAutomationsActive}, + {"MethodAutomationsChanges", MethodAutomationsChanges}, + {"MethodAutomationsClaim", MethodAutomationsClaim}, + {"MethodAutomationsCreate", MethodAutomationsCreate}, + {"MethodAutomationsCursor", MethodAutomationsCursor}, + {"MethodAutomationsDelete", MethodAutomationsDelete}, + {"MethodAutomationsList", MethodAutomationsList}, + {"MethodAutomationsRunNow", MethodAutomationsRunNow}, + {"MethodAutomationsRuns", MethodAutomationsRuns}, + {"MethodAutomationsSetStatus", MethodAutomationsSetStatus}, + {"MethodAutomationsStopRun", MethodAutomationsStopRun}, + {"MethodAutomationsUpdate", MethodAutomationsUpdate}, + {"MethodAutomationsWindows", MethodAutomationsWindows}, + {"MethodAutonomy", MethodAutonomy}, + {"MethodCheckWork", MethodCheckWork}, + {"MethodClaimChatStart", MethodClaimChatStart}, + {"MethodClearSkills", MethodClearSkills}, + {"MethodClientToolAnswer", MethodClientToolAnswer}, + {"MethodClientToolsSet", MethodClientToolsSet}, + {"MethodClose", MethodClose}, + {"MethodCompact", MethodCompact}, + {"MethodConnect", MethodConnect}, + {"MethodConnectKey", MethodConnectKey}, + {"MethodConsent", MethodConsent}, + {"MethodConsentRemember", MethodConsentRemember}, + {"MethodContextTokens", MethodContextTokens}, + {"MethodDelegateList", MethodDelegateList}, + {"MethodDelegateStart", MethodDelegateStart}, + {"MethodDepositFile", MethodDepositFile}, + {"MethodDesignWatch", MethodDesignWatch}, + {"MethodDetachSkill", MethodDetachSkill}, + {"MethodEarlier", MethodEarlier}, + {"MethodEffort", MethodEffort}, + {"MethodFetchFile", MethodFetchFile}, + {"MethodFollowUp", MethodFollowUp}, + {"MethodHarness", MethodHarness}, + {"MethodHeldQuestions", MethodHeldQuestions}, + {"MethodInterrupt", MethodInterrupt}, + {"MethodListDir", MethodListDir}, + {"MethodMemoryAlways", MethodMemoryAlways}, + {"MethodMemoryApplies", MethodMemoryApplies}, + {"MethodMemoryChanged", MethodMemoryChanged}, + {"MethodMemoryForget", MethodMemoryForget}, + {"MethodMemoryMemories", MethodMemoryMemories}, + {"MethodMemoryMove", MethodMemoryMove}, + {"MethodMemoryProject", MethodMemoryProject}, + {"MethodMemoryProvenance", MethodMemoryProvenance}, + {"MethodMemoryRemember", MethodMemoryRemember}, + {"MethodMemoryRememberAlways", MethodMemoryRememberAlways}, + {"MethodMemoryRestore", MethodMemoryRestore}, + {"MethodMemorySelection", MethodMemorySelection}, + {"MethodMemorySnapshot", MethodMemorySnapshot}, + {"MethodMemoryUpdate", MethodMemoryUpdate}, + {"MethodModel", MethodModel}, + {"MethodNoteConnected", MethodNoteConnected}, + {"MethodObserve", MethodObserve}, + {"MethodOpenPlanTaskWork", MethodOpenPlanTaskWork}, + {"MethodPing", MethodPing}, + {"MethodPlacesArchive", MethodPlacesArchive}, + {"MethodPlacesDelete", MethodPlacesDelete}, + {"MethodPlacesLedger", MethodPlacesLedger}, + {"MethodPlacesRefer", MethodPlacesRefer}, + {"MethodPlacesRemove", MethodPlacesRemove}, + {"MethodPlacesSearch", MethodPlacesSearch}, + {"MethodPlacesTask", MethodPlacesTask}, + {"MethodPlacesTaskDelete", MethodPlacesTaskDelete}, + {"MethodPlacesWorld", MethodPlacesWorld}, + {"MethodPlanAmend", MethodPlanAmend}, + {"MethodPlanCancel", MethodPlanCancel}, + {"MethodPlanNote", MethodPlanNote}, + {"MethodPlanPause", MethodPlanPause}, + {"MethodPlanPriority", MethodPlanPriority}, + {"MethodPlanResume", MethodPlanResume}, + {"MethodPlanRunSummary", MethodPlanRunSummary}, + {"MethodPlanSpend", MethodPlanSpend}, + {"MethodPlanTaskPage", MethodPlanTaskPage}, + {"MethodPlanTaskWork", MethodPlanTaskWork}, + {"MethodPlanTasks", MethodPlanTasks}, + {"MethodPlannerStart", MethodPlannerStart}, + {"MethodProcessActions", MethodProcessActions}, + {"MethodProcessList", MethodProcessList}, + {"MethodProcessPage", MethodProcessPage}, + {"MethodProcessRecord", MethodProcessRecord}, + {"MethodProcessRerun", MethodProcessRerun}, + {"MethodProcessRerunAt", MethodProcessRerunAt}, + {"MethodProcessStopAll", MethodProcessStopAll}, + {"MethodProcessStopAt", MethodProcessStopAt}, + {"MethodQuestionClock", MethodQuestionClock}, + {"MethodQuestionDismiss", MethodQuestionDismiss}, + {"MethodQuestionHold", MethodQuestionHold}, + {"MethodQuestionReplace", MethodQuestionReplace}, + {"MethodQuestionResolve", MethodQuestionResolve}, + {"MethodQuestionWatch", MethodQuestionWatch}, + {"MethodReasoningFor", MethodReasoningFor}, + {"MethodRefreshRunSummary", MethodRefreshRunSummary}, + {"MethodRenderCancel", MethodRenderCancel}, + {"MethodRenderGet", MethodRenderGet}, + {"MethodRenderList", MethodRenderList}, + {"MethodResolvedApproval", MethodResolvedApproval}, + {"MethodResolvedEffort", MethodResolvedEffort}, + {"MethodRewindAt", MethodRewindAt}, + {"MethodRewindPoints", MethodRewindPoints}, + {"MethodRunHarness", MethodRunHarness}, + {"MethodSessionNew", MethodSessionNew}, + {"MethodSessionOpen", MethodSessionOpen}, + {"MethodSessionsRecent", MethodSessionsRecent}, + {"MethodSetApproval", MethodSetApproval}, + {"MethodSetAutomaticModels", MethodSetAutomaticModels}, + {"MethodSetAutonomy", MethodSetAutonomy}, + {"MethodSetContext", MethodSetContext}, + {"MethodSetConversationModels", MethodSetConversationModels}, + {"MethodSetEffort", MethodSetEffort}, + {"MethodSetModel", MethodSetModel}, + {"MethodSetReasoningFor", MethodSetReasoningFor}, + {"MethodSetSpendRail", MethodSetSpendRail}, + {"MethodSetupPlan", MethodSetupPlan}, + {"MethodSideAsk", MethodSideAsk}, + {"MethodSideAskStream", MethodSideAskStream}, + {"MethodSkillFolders", MethodSkillFolders}, + {"MethodSkillShelf", MethodSkillShelf}, + {"MethodSpendRail", MethodSpendRail}, + {"MethodStatPaths", MethodStatPaths}, + {"MethodSteer", MethodSteer}, + {"MethodStopWork", MethodStopWork}, + {"MethodSubharnessResolve", MethodSubharnessResolve}, + {"MethodSubmit", MethodSubmit}, + {"MethodSubmitBash", MethodSubmitBash}, + {"MethodSubmitFiles", MethodSubmitFiles}, + {"MethodSubmitImage", MethodSubmitImage}, + {"MethodSubmitSetup", MethodSubmitSetup}, + {"MethodTake", MethodTake}, + {"MethodTaskEffort", MethodTaskEffort}, + {"MethodTaskHold", MethodTaskHold}, + {"MethodTaskModel", MethodTaskModel}, + {"MethodTaskPending", MethodTaskPending}, + {"MethodTaskRedoStronger", MethodTaskRedoStronger}, + {"MethodTaskResolve", MethodTaskResolve}, + {"MethodTaskRetry", MethodTaskRetry}, + {"MethodTaskRoom", MethodTaskRoom}, + {"MethodTaskRunHere", MethodTaskRunHere}, + {"MethodTaskSetEffort", MethodTaskSetEffort}, + {"MethodTaskSettle", MethodTaskSettle}, + {"MethodTaskStart", MethodTaskStart}, + {"MethodTaskStartOn", MethodTaskStartOn}, + {"MethodTaskSteer", MethodTaskSteer}, + {"MethodTaskStop", MethodTaskStop}, + {"MethodTaskWatch", MethodTaskWatch}, + {"MethodTaskWorkspaceApply", MethodTaskWorkspaceApply}, + {"MethodTaskWorkspaceCancel", MethodTaskWorkspaceCancel}, + {"MethodTaskWorkspaceReview", MethodTaskWorkspaceReview}, + {"MethodTeamsAcceptClosing", MethodTeamsAcceptClosing}, + {"MethodTeamsApplyDefault", MethodTeamsApplyDefault}, + {"MethodTeamsDecide", MethodTeamsDecide}, + {"MethodTeamsDefaults", MethodTeamsDefaults}, + {"MethodTeamsDelete", MethodTeamsDelete}, + {"MethodTeamsEscalate", MethodTeamsEscalate}, + {"MethodTeamsName", MethodTeamsName}, + {"MethodTeamsPackets", MethodTeamsPackets}, + {"MethodTeamsPropose", MethodTeamsPropose}, + {"MethodTeamsRaise", MethodTeamsRaise}, + {"MethodTeamsRead", MethodTeamsRead}, + {"MethodTeamsSpend", MethodTeamsSpend}, + {"MethodTeamsTraffic", MethodTeamsTraffic}, + {"MethodTeamsUpdate", MethodTeamsUpdate}, + {"MethodTeamsWrapUp", MethodTeamsWrapUp}, + {"MethodTitle", MethodTitle}, + {"MethodTitleWatch", MethodTitleWatch}, + {"MethodTranscript", MethodTranscript}, + {"MethodTranscriptPage", MethodTranscriptPage}, + {"MethodTyping", MethodTyping}, + {"MethodUnobserve", MethodUnobserve}, + {"MethodUnqueueFollowUp", MethodUnqueueFollowUp}, + {"MethodUsage", MethodUsage}, + {"MethodUseModelForNow", MethodUseModelForNow}, + // MethodDetach is placed last because it detaches the connection it runs on. + {"MethodDetach", MethodDetach}, + } + + // Ensure every exported Method* constant in internal/remote is listed in allMethods. + listed := make(map[string]bool, len(allMethods)) + for _, entry := range allMethods { + listed[entry.name] = true + } + walkGo(t, filepath.Join(repoRoot(t), "internal", "remote"), func(_ string, file *ast.File) { + for _, decl := range file.Decls { + gen, ok := decl.(*ast.GenDecl) + if !ok || gen.Tok != token.CONST { + continue + } + for _, spec := range gen.Specs { + val, ok := spec.(*ast.ValueSpec) + if !ok { + continue + } + for _, ident := range val.Names { + if strings.HasPrefix(ident.Name, "Method") && !listed[ident.Name] { + t.Errorf("wire method constant %s is missing from allMethods table", ident.Name) + } + } + } + } + }) + + // Explicit contract assertions for forbidden methods. + for _, forbidden := range []string{ + MethodTranscript, + MethodSubmitBash, + MethodSubmitSetup, + MethodSubmitImage, + MethodSubmitFiles, + MethodSetApproval, + MethodConsentRemember, + MethodSessionsRecent, + MethodSessionNew, + MethodSessionOpen, + MethodRewindPoints, + MethodRewindAt, + MethodDepositFile, + MethodFetchFile, + MethodListDir, + MethodStatPaths, + MethodClose, + MethodSetupPlan, + MethodPlanSpend, + MethodPlanTasks, + MethodOpenPlanTaskWork, + MethodPlanTaskWork, + MethodPlanNote, + MethodPlanPause, + MethodPlanResume, + MethodPlanCancel, + MethodPlanAmend, + MethodPlanPriority, + MethodPlanRunSummary, + MethodRefreshRunSummary, + } { + if contractWatchMay[forbidden] || contractDriveMay[forbidden] { + t.Fatalf("forbidden method %q is present in a guest allow-list", forbidden) + } + } + + agent := &fakeAgent{prefill: []session.Event{}} + sess := heldSession(agent) + t.Cleanup(func() { _ = agent.Close() }) + + dialGuest := func(t *testing.T, label string, drive bool) *link { + t.Helper() + l := dialSession(t, sess) + frame := l.hello(Hello{ + Version: Version, + Surface: label, + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-" + label, + Label: label, + Watch: true, + Drive: drive, + Road: "relay", + }, + }) + if frame.Kind != "welcome" { + t.Fatalf("guest %s handshake answered %q: %s", label, frame.Kind, frame.Error) + } + return l + } + + watchLink := dialGuest(t, "watch-guest", false) + driveLink := dialGuest(t, "drive-guest", true) + + host := HostName() + watchOnlySentence := chatlist.LiveWatchOnly(host) + notAllowedSentence := chatlist.LiveNotAllowedHere(host) + isGuestSentence := func(errText string) bool { + return errText == watchOnlySentence || errText == notAllowedSentence + } + + var callSeq uint64 + for _, entry := range allMethods { + t.Run(entry.name, func(t *testing.T) { + callSeq++ + wLink := watchLink + dLink := driveLink + if entry.method == MethodDetach { + wLink = dialGuest(t, "watch-detach", false) + dLink = dialGuest(t, "drive-detach", true) + } + + watchRes := wLink.call(callSeq, entry.method, nil) + if contractWatchMay[entry.method] { + if isGuestSentence(watchRes.Error) { + t.Fatalf("watch guest calling allowed %s (%q) was refused by guest guard: %q", entry.name, entry.method, watchRes.Error) + } + } else { + want := notAllowedSentence + if contractDriveMay[entry.method] { + want = watchOnlySentence + } + if watchRes.Error != want { + t.Fatalf("watch guest calling disallowed %s (%q) answered %q, want %q", entry.name, entry.method, watchRes.Error, want) + } + } + + driveRes := dLink.call(callSeq, entry.method, nil) + if contractDriveMay[entry.method] { + if isGuestSentence(driveRes.Error) { + t.Fatalf("drive guest calling allowed %s (%q) was refused by guest guard: %q", entry.name, entry.method, driveRes.Error) + } + } else { + if driveRes.Error != notAllowedSentence { + t.Fatalf("drive guest calling disallowed %s (%q) answered %q, want %q", entry.name, entry.method, driveRes.Error, notAllowedSentence) + } + } + }) + } +} diff --git a/internal/remote/idle_r10_retry_test.go b/internal/remote/idle_r10_retry_test.go index bf02b67f29..88f2a55b2c 100644 --- a/internal/remote/idle_r10_retry_test.go +++ b/internal/remote/idle_r10_retry_test.go @@ -8,7 +8,7 @@ import ( ) func TestIdleRelease_R10_RemoteKeepsRetryableOwnershipRefusal(t *testing.T) { - want := &executor.WorkRefusal{Line: "couldn't confirm taking this chat back from the sync service; try again", Retryable: true} + want := &executor.WorkRefusal{Line: "couldn't confirm taking this chat back from the relay; try again", Retryable: true} far := &viewerAdmissionAgent{fakeAgent: &fakeAgent{}, refusal: want} loop, err := Loopback(Hello{Version: Version}, Options{Boot: func(Hello) (*Engine, error) { return &Engine{Agent: far}, nil }}) if err != nil { diff --git a/internal/remote/inputid_test.go b/internal/remote/inputid_test.go new file mode 100644 index 0000000000..8c7726b0aa --- /dev/null +++ b/internal/remote/inputid_test.go @@ -0,0 +1,622 @@ +package remote + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "reflect" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/session" +) + +// persistedFakeAgent wraps fakeAgent with the marked submission doors and +// appends accepted person messages (including their ClientID) to a shared +// persisted transcript slice so a restarted holder (a new Session) can scan the +// transcript tail. +type persistedFakeAgent struct { + *fakeAgent + transcriptMu *sync.Mutex + persisted *[]session.DisplayEntry + submissions []session.Submission +} + +func newPersistedFakeAgent(sharedMu *sync.Mutex, shared *[]session.DisplayEntry) *persistedFakeAgent { + if sharedMu == nil { + sharedMu = &sync.Mutex{} + } + if shared == nil { + var list []session.DisplayEntry + shared = &list + } + return &persistedFakeAgent{ + fakeAgent: &fakeAgent{model: "a/b"}, + transcriptMu: sharedMu, + persisted: shared, + } +} + +func (p *persistedFakeAgent) recordSubmission(message session.Submission) { + p.mu.Lock() + p.submissions = append(p.submissions, message) + p.mu.Unlock() + p.transcriptMu.Lock() + var mark *session.PersonMark + if message.ClientID != "" || message.From != "" || message.Queued { + mark = &session.PersonMark{ + ClientID: message.ClientID, + From: message.From, + Queued: message.Queued, + } + } + *p.persisted = append(*p.persisted, session.DisplayEntry{ + Role: "user", + Text: message.Text, + Person: mark, + }) + p.transcriptMu.Unlock() +} + +func (p *persistedFakeAgent) SubmitMessage(ctx context.Context, message session.Submission) (<-chan session.Event, error) { + p.recordSubmission(message) + return p.fakeAgent.Submit(ctx, message.Text) +} + +func (p *persistedFakeAgent) FollowUpMessage(message session.Submission) (<-chan session.Event, error) { + p.recordSubmission(message) + return p.fakeAgent.FollowUp(message.Text) +} + +func (p *persistedFakeAgent) SteerMessage(message session.Submission) (<-chan session.Event, error) { + p.recordSubmission(message) + return p.fakeAgent.Steer(message.Text) +} + +func (p *persistedFakeAgent) Transcript() []session.DisplayEntry { + p.transcriptMu.Lock() + defer p.transcriptMu.Unlock() + out := make([]session.DisplayEntry, len(*p.persisted)) + copy(out, *p.persisted) + return out +} + +// swallowNextResultConn wraps the server side of a Pipe. When swallow is armed +// and the server writes a "result" frame, the wrapper drops that frame and +// closes both halves of the pipe so the client never receives the result. +type swallowNextResultConn struct { + io.Reader + out io.WriteCloser + peer io.Closer + swallow *atomic.Bool + cut chan struct{} + cutOnce sync.Once +} + +func (c *swallowNextResultConn) Write(p []byte) (int, error) { + if c.swallow != nil && c.swallow.Load() { + var frame Frame + if json.Unmarshal(bytes.TrimSpace(p), &frame) == nil && frame.Kind == "result" { + c.swallow.Store(false) + _ = c.out.Close() + _ = c.peer.Close() + c.cutOnce.Do(func() { close(c.cut) }) + return 0, io.ErrClosedPipe + } + } + return c.out.Write(p) +} + +func (c *swallowNextResultConn) Close() error { + return c.out.Close() +} + +// TestAnInputSentBeforeADropIsNeverAppliedTwiceAfterResume verifies V23: a +// remote guest send (Submit, FollowUp, or Steer) carrying a ClientID whose +// result frame is lost to a dropped link is resent on resume and answered from +// the holder's repeat table (or from the persisted transcript tail after a +// holder restart) without delivering a second message or starting a second +// turn. +func TestAnInputSentBeforeADropIsNeverAppliedTwiceAfterResume(t *testing.T) { + savedBackoff := firstBackoff + firstBackoff = 5 * time.Millisecond + t.Cleanup(func() { firstBackoff = savedBackoff }) + + const sessionFile = "/home/somebody/.codeaf/v3/sessions/one.jsonl" + guestStamp := &RemoteViewer{ + Device: "dev-phone", + Label: "phone", + Watch: true, + Drive: true, + Road: "relay", + } + + t.Run("scenario A: Submit dropped before result is resent and applied once", func(t *testing.T) { + agent := &fakeAgent{model: "a/b"} + eng := engineOn(agent) + eng.SessionFile = sessionFile + sess := NewSession(eng, true) + + var swallow atomic.Bool + var dials atomic.Int32 + cut := make(chan struct{}) + dialer := func() (io.ReadWriteCloser, error) { + n := dials.Add(1) + surface, engine := Pipe() + var serverOut io.ReadWriteCloser = engine + if n == 1 { + serverOut = &swallowNextResultConn{ + Reader: engine, + out: engine, + peer: surface, + swallow: &swallow, + cut: cut, + } + } + guard.Go("remote/test-v23-a", func() { + _ = ServeAttach(serverOut, serverOut, AttachOptions{ + Open: func(Hello) (*Session, error) { return sess, nil }, + }) + _ = engine.Close() + }) + return surface, nil + } + + client, err := Roam("devbox", Hello{ + Session: sessionFile, + Join: true, + Remote: guestStamp, + }, Roaming{ + Dial: dialer, + Window: time.Second, + ResendUnanswered: true, + }) + if err != nil { + t.Fatalf("roam: %v", err) + } + t.Cleanup(func() { _ = client.Close() }) + if !client.Welcome().MessageRepeat { + t.Fatal("holder welcome did not advertise MessageRepeat") + } + + swallow.Store(true) + events, err := client.Agent().SubmitMessage(context.Background(), session.Submission{ + Text: "deploy once", + ClientID: "client-id-a", + }) + if err != nil { + t.Fatalf("SubmitMessage after drop and resend failed: %v", err) + } + <-cut + if got := dials.Load(); got < 2 { + t.Fatalf("expected redial after cut, got %d dials", got) + } + + agent.mu.Lock() + sent := append([]string(nil), agent.sent...) + streamsCount := len(agent.streams) + turn := agent.streams[0] + agent.mu.Unlock() + + if !reflect.DeepEqual(sent, []string{"deploy once"}) { + t.Fatalf("agent received messages %q, want exactly one delivery", sent) + } + if streamsCount != 1 { + t.Fatalf("agent opened %d streams, want 1", streamsCount) + } + + turn <- session.Event{Kind: session.EventTextDelta, Text: "deployed"} + agent.finish(turn) + var text []string + for ev := range events { + if ev.Kind == session.EventTextDelta { + text = append(text, ev.Text) + } + } + if strings.Join(text, "") != "deployed" { + t.Fatalf("caller stream received %q, want %q", strings.Join(text, ""), "deployed") + } + }) + + t.Run("scenario B: FollowUp and Steer dropped before result are resent and applied once", func(t *testing.T) { + agent := &fakeAgent{model: "a/b"} + eng := engineOn(agent) + eng.SessionFile = sessionFile + sess := NewSession(eng, true) + + var swallow atomic.Bool + dialer := func() (io.ReadWriteCloser, error) { + surface, engine := Pipe() + serverOut := &swallowNextResultConn{ + Reader: engine, + out: engine, + peer: surface, + swallow: &swallow, + cut: make(chan struct{}), + } + guard.Go("remote/test-v23-b", func() { + _ = ServeAttach(serverOut, serverOut, AttachOptions{ + Open: func(Hello) (*Session, error) { return sess, nil }, + }) + _ = engine.Close() + }) + return surface, nil + } + + client, err := Roam("devbox", Hello{ + Session: sessionFile, + Join: true, + Remote: guestStamp, + }, Roaming{ + Dial: dialer, + Window: time.Second, + ResendUnanswered: true, + }) + if err != nil { + t.Fatalf("roam: %v", err) + } + t.Cleanup(func() { _ = client.Close() }) + + // FollowUp with empty ClientID mints an rc- id and survives a drop before result. + swallow.Store(true) + followEvents, err := client.Agent().FollowUp("queue this once") + if err != nil { + t.Fatalf("FollowUp after drop and resend: %v", err) + } + if followEvents == nil { + t.Fatal("FollowUp returned nil stream") + } + + // Steer with empty ClientID mints an rc- id and survives a drop before result. + swallow.Store(true) + steerEvents, err := client.Agent().Steer("turn left once") + if err != nil { + t.Fatalf("Steer after drop and resend: %v", err) + } + if steerEvents == nil { + t.Fatal("Steer returned nil stream") + } + + agent.mu.Lock() + follows := append([]string(nil), agent.follows...) + steered := append([]string(nil), agent.steered...) + streamsCount := len(agent.streams) + agent.mu.Unlock() + + if !reflect.DeepEqual(follows, []string{"queue this once"}) { + t.Fatalf("agent received follow-ups %q, want 1", follows) + } + if !reflect.DeepEqual(steered, []string{"turn left once"}) { + t.Fatalf("agent received steers %q, want 1", steered) + } + if streamsCount != 2 { + t.Fatalf("agent opened %d streams for FollowUp+Steer, want 2", streamsCount) + } + }) + + t.Run("scenario C: holder replaced between send and resume finds ClientID in persisted transcript tail", func(t *testing.T) { + var sharedMu sync.Mutex + var persisted []session.DisplayEntry + + agent1 := newPersistedFakeAgent(&sharedMu, &persisted) + eng1 := engineOn(agent1.fakeAgent) + eng1.Agent = agent1 + eng1.SessionFile = sessionFile + sess1 := NewSession(eng1, true) + + agent2 := newPersistedFakeAgent(&sharedMu, &persisted) + eng2 := engineOn(agent2.fakeAgent) + eng2.Agent = agent2 + eng2.SessionFile = sessionFile + sess2 := NewSession(eng2, true) + + var swallow atomic.Bool + var dials atomic.Int32 + dialer := func() (io.ReadWriteCloser, error) { + n := dials.Add(1) + surface, engine := Pipe() + target := sess1 + var serverOut io.ReadWriteCloser = engine + if n == 1 { + serverOut = &swallowNextResultConn{ + Reader: engine, + out: engine, + peer: surface, + swallow: &swallow, + cut: make(chan struct{}), + } + } else { + target = sess2 + } + guard.Go("remote/test-v23-c", func() { + _ = ServeAttach(serverOut, serverOut, AttachOptions{ + Open: func(Hello) (*Session, error) { return target, nil }, + }) + _ = engine.Close() + }) + return surface, nil + } + + client, err := Roam("devbox", Hello{ + Session: sessionFile, + Join: true, + Remote: guestStamp, + }, Roaming{ + Dial: dialer, + Window: time.Second, + ResendUnanswered: true, + }) + if err != nil { + t.Fatalf("roam: %v", err) + } + t.Cleanup(func() { _ = client.Close() }) + + swallow.Store(true) + events, err := client.Agent().SubmitMessage(context.Background(), session.Submission{ + Text: "survive holder restart", + ClientID: "durable-id-c", + }) + if err != nil { + t.Fatalf("SubmitMessage across holder restart: %v", err) + } + for range events { + } + + agent1.mu.Lock() + sent1 := append([]string(nil), agent1.sent...) + agent1.mu.Unlock() + agent2.mu.Lock() + sent2 := append([]string(nil), agent2.sent...) + agent2.mu.Unlock() + + if !reflect.DeepEqual(sent1, []string{"survive holder restart"}) { + t.Fatalf("first holder received %q, want 1 delivery", sent1) + } + if len(sent2) != 0 { + t.Fatalf("restarted holder delivered repeat again: %q", sent2) + } + }) + + t.Run("scenario D: two different devices with the same ClientID deliver two messages", func(t *testing.T) { + agent := &fakeAgent{model: "a/b"} + eng := engineOn(agent) + eng.SessionFile = sessionFile + sess := NewSession(eng, true) + + for i, dev := range []string{"dev-one", "dev-two"} { + conn := dialSession(t, sess) + welcome := conn.hello(Hello{ + Version: Version, + Session: sessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: dev, + Label: dev, + Watch: true, + Drive: true, + Road: "relay", + }, + }) + if welcome.Kind != "welcome" { + t.Fatalf("device %s hello: %s", dev, welcome.Error) + } + conn.ok(uint64(i+1), MethodTake, nil) + res := conn.ok(uint64(i+10), MethodSubmit, SubmitArgs{ + Text: "from " + dev, + ClientID: "same-client-id", + }) + ref := decode[StreamRef](t, res.Payload) + if ref.Stream == 0 { + t.Fatalf("device %s got zero stream", dev) + } + } + + agent.mu.Lock() + sent := append([]string(nil), agent.sent...) + agent.mu.Unlock() + if !reflect.DeepEqual(sent, []string{"from dev-one", "from dev-two"}) { + t.Fatalf("agent received %q, want both deliveries", sent) + } + }) + + t.Run("scenario E: with ResendUnanswered false the in-flight send fails on drop", func(t *testing.T) { + agent := &fakeAgent{model: "a/b"} + eng := engineOn(agent) + eng.SessionFile = sessionFile + sess := NewSession(eng, true) + + var swallow atomic.Bool + dialer := func() (io.ReadWriteCloser, error) { + surface, engine := Pipe() + serverOut := &swallowNextResultConn{ + Reader: engine, + out: engine, + peer: surface, + swallow: &swallow, + cut: make(chan struct{}), + } + guard.Go("remote/test-v23-e", func() { + _ = ServeAttach(serverOut, serverOut, AttachOptions{ + Open: func(Hello) (*Session, error) { return sess, nil }, + }) + _ = engine.Close() + }) + return surface, nil + } + + client, err := Roam("devbox", Hello{ + Session: sessionFile, + Join: true, + Remote: guestStamp, + }, Roaming{ + Dial: dialer, + Window: time.Second, + ResendUnanswered: false, + }) + if err != nil { + t.Fatalf("roam: %v", err) + } + t.Cleanup(func() { _ = client.Close() }) + + swallow.Store(true) + _, err = client.Agent().SubmitMessage(context.Background(), session.Submission{ + Text: "no resend", + ClientID: "id-e", + }) + if err == nil || !strings.Contains(err.Error(), "reconnecting to devbox") { + t.Fatalf("expected roaming refusal when ResendUnanswered is false, got %v", err) + } + }) + + t.Run("concurrency: 20 goroutines repeating one (device, id) produce one delivery", func(t *testing.T) { + agent := &fakeAgent{model: "a/b"} + eng := engineOn(agent) + eng.SessionFile = sessionFile + sess := NewSession(eng, true) + sess.mu.Lock() + // Leave driver nil so every concurrent connection from this device may send. + sess.driver = nil + sess.mu.Unlock() + + const workers = 20 + start := make(chan struct{}) + refs := make([]StreamRef, workers) + errs := make([]error, workers) + var wg sync.WaitGroup + wg.Add(workers) + for i := 0; i < workers; i++ { + i := i + guard.Go("remote/test-v23-concurrent", func() { + defer wg.Done() + s := &server{ + out: io.Discard, + session: sess, + remote: &RemoteViewer{ + Device: "dev-concurrent", + Label: "phone", + Watch: true, + Drive: true, + Road: "relay", + }, + } + <-start + raw, err := s.invoke(Frame{ + Kind: "call", + ID: uint64(i + 1), + Method: MethodSubmit, + Payload: mustJSON(SubmitArgs{ + Text: "concurrent send", + ClientID: "shared-key", + }), + }) + if err != nil { + errs[i] = err + return + } + var ref StreamRef + if err := json.Unmarshal(raw, &ref); err != nil { + errs[i] = err + return + } + refs[i] = ref + }) + } + close(start) + wg.Wait() + + for i, err := range errs { + if err != nil { + t.Fatalf("worker %d failed: %v", i, err) + } + } + wantStream := refs[0].Stream + if wantStream == 0 { + t.Fatal("expected non-zero stream id") + } + for i, ref := range refs { + if ref.Stream != wantStream { + t.Fatalf("worker %d got stream %d, want %d", i, ref.Stream, wantStream) + } + } + agent.mu.Lock() + sent := append([]string(nil), agent.sent...) + streamsCount := len(agent.streams) + agent.mu.Unlock() + if !reflect.DeepEqual(sent, []string{"concurrent send"}) || streamsCount != 1 { + t.Fatalf("agent got %d deliveries (%q) and %d streams, want 1", len(sent), sent, streamsCount) + } + }) + + t.Run("table bound: 256 entries evicts the oldest and transcript scan bounds to last 200", func(t *testing.T) { + var sharedMu sync.Mutex + var persisted []session.DisplayEntry + // Place an ancient entry before 200 newer entries so it sits outside the 200-entry tail scan. + persisted = append(persisted, session.DisplayEntry{ + Role: "user", + Text: "ancient", + Person: &session.PersonMark{ClientID: "ancient-id"}, + }) + for i := 0; i < messageRepeatTailScan; i++ { + persisted = append(persisted, session.DisplayEntry{ + Role: "assistant", + Text: fmt.Sprintf("reply-%d", i), + }) + } + + agent := newPersistedFakeAgent(&sharedMu, &persisted) + eng := engineOn(agent.fakeAgent) + eng.Agent = agent + eng.SessionFile = sessionFile + sess := NewSession(eng, true) + s := &server{ + out: io.Discard, + session: sess, + remote: guestStamp, + } + + // Fill the 256-entry table with id-0 .. id-255. + for i := 0; i < messageRepeatCap; i++ { + id := fmt.Sprintf("id-%d", i) + if _, err := s.invoke(Frame{ + Kind: "call", + ID: uint64(i + 1), + Method: MethodSteer, + Payload: mustJSON(SubmitArgs{Text: "steer", ClientID: id}), + }); err != nil { + t.Fatalf("steer %d: %v", i, err) + } + } + // Adding one more evicts id-0 from the in-memory table. + if _, err := s.invoke(Frame{ + Kind: "call", + ID: 999, + Method: MethodSteer, + Payload: mustJSON(SubmitArgs{Text: "steer-new", ClientID: "id-256"}), + }); err != nil { + t.Fatalf("steer 256: %v", err) + } + sess.repeatMu.Lock() + tableLen := len(sess.repeats) + _, hasOldest := sess.repeats[messageRepeatKey{device: guestStamp.Device, clientID: "id-0"}] + _, hasSecond := sess.repeats[messageRepeatKey{device: guestStamp.Device, clientID: "id-1"}] + sess.repeatMu.Unlock() + if tableLen != messageRepeatCap || hasOldest || !hasSecond { + t.Fatalf("repeat table len=%d hasOldest=%v hasSecond=%v", tableLen, hasOldest, hasSecond) + } + + // And an entry older than the last 200 transcript entries is not treated as a recent repeat. + if sess.transcriptHasClientID(agent, "ancient-id") { + t.Fatal("transcript scan looked past the last 200 entries") + } + // While an entry inside the last 200 entries is found. + if !sess.transcriptHasClientID(agent, "id-256") { + t.Fatal("transcript scan missed an entry inside the last 200 entries") + } + }) +} diff --git a/internal/remote/modelsource_wire_law_test.go b/internal/remote/modelsource_wire_law_test.go index 50aef89308..fb55e1c8c4 100644 --- a/internal/remote/modelsource_wire_law_test.go +++ b/internal/remote/modelsource_wire_law_test.go @@ -23,6 +23,10 @@ var helloFields = map[string]bool{ // Window says the connection is a person's window, so the far machine holds // automations presence for it (wire_automations.go). A boolean, not a credential. "Window": true, + // Remote is the stamp a door puts on a viewer that reached this chat through + // another computer: a device id, a label, two booleans and the name of the road. + // It carries no key or address. + "Remote": true, // LocalSavingReceipts is a boolean capability, with no key or address. "LocalSavingReceipts": true, // SyncNoticeWords is a boolean vocabulary capability, with no key or address. diff --git a/internal/remote/permit_law_test.go b/internal/remote/permit_law_test.go new file mode 100644 index 0000000000..9b8d0d523e --- /dev/null +++ b/internal/remote/permit_law_test.go @@ -0,0 +1,58 @@ +package remote + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" + "testing" +) + +// TestNoWireMethodCanWriteThePermitBook enforces the local-only boundary on the +// permit book: no wire handler or non-test file in internal/remote may import +// internal/pair or call PermitBook.Set, Permits, PermitsAt or write +// permits.json. Only this computer's own operator doors may change who can +// watch or type here. +func TestNoWireMethodCanWriteThePermitBook(t *testing.T) { + entries, err := os.ReadDir(".") + if err != nil { + t.Fatalf("ReadDir: %v", err) + } + fset := token.NewFileSet() + for _, entry := range entries { + name := entry.Name() + if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + path := filepath.Clean(name) + raw, err := os.ReadFile(path) + if err != nil { + t.Fatalf("ReadFile(%s): %v", path, err) + } + if strings.Contains(string(raw), "permits.json") { + t.Errorf("%s references permits.json", path) + } + file, err := parser.ParseFile(fset, path, raw, 0) + if err != nil { + t.Fatalf("ParseFile(%s): %v", path, err) + } + for _, imp := range file.Imports { + if strings.Trim(imp.Path.Value, `"`) == "github.com/Agent-Field/codeaf/internal/pair" { + t.Errorf("%s imports internal/pair; wire methods must never reach the permit book", path) + } + } + ast.Inspect(file, func(n ast.Node) bool { + sel, ok := n.(*ast.SelectorExpr) + if !ok { + return true + } + switch sel.Sel.Name { + case "Permits", "PermitsAt", "PermitBook": + t.Errorf("%s:%d references %s", path, fset.Position(sel.Pos()).Line, sel.Sel.Name) + } + return true + }) + } +} diff --git a/internal/remote/redial.go b/internal/remote/redial.go index 07578f7d60..8bd769d4b6 100644 --- a/internal/remote/redial.go +++ b/internal/remote/redial.go @@ -35,10 +35,12 @@ import ( "errors" "fmt" "io" + "sort" "strings" "time" "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/relay" ) const ( @@ -55,19 +57,54 @@ const ( // opens it again. Roaming buys the person not having to type it. RoamWindow = 5 * time.Minute - // firstBackoff is the pause before the first retry and slowestBackoff the - // ceiling it doubles up to. The first is short because most drops are a - // blip and the pipe is there a second later; the ceiling exists because - // every attempt spawns an ssh process on this machine and a hundred of them - // against a machine that is switched off is a person's laptop working for - // nothing. - firstBackoff = 1 * time.Second slowestBackoff = 15 * time.Second + defaultFirstBackoff = 1 * time.Second + firstRetrySpread = 5 * time.Second + jitterLow = 0.75 + jitterSpan = 0.5 + // resumeTail is how long a resumed stream may stay silent before it is // treated as a turn that ended while nobody was watching. See // [Client.watchTail] for the whole of why it exists. resumeTail = 3 * time.Second + + // defaultPlannedNoteAfter is how long a PLANNED redial may take before the screen + // says `reconnecting`. A swap between two roads the viewer itself chose is + // over in milliseconds on a network that works, and a sentence about a link + // that was never lost would be the screen inventing a fault; an attempt that + // outlasts this is no longer a swap, and the same sentence an unplanned drop + // says is the true one. It is the default of [plannedNoteAfter]. + defaultPlannedNoteAfter = 750 * time.Millisecond +) + +// plannedNoteAfter is a variable so that a test can ask the question without +// sleeping for most of a second. +var plannedNoteAfter = defaultPlannedNoteAfter + +// firstBackoff is the floor of the pause before the first retry and +// slowestBackoff the ceiling the base wait doubles up to. The first retry +// draws from [1 s, 6 s) via [relay.FirstRetry] and each doubled wait is +// spread into [0.75, 1.25) via [relay.Jitter] so a dropped relay does not +// see every surface return in the same second; the ceiling exists because +// every attempt spawns an ssh process or a dial on this machine and a +// hundred of them against a machine that is switched off is a person's +// laptop working for nothing. +var ( + firstBackoff = defaultFirstBackoff + retryFirst = relay.FirstRetry + retryJitter = relay.Jitter + retryRand func() float64 + redialSleep = func(stop <-chan struct{}, d time.Duration) bool { + timer := time.NewTimer(d) + select { + case <-stop: + timer.Stop() + return false + case <-timer.C: + return true + } + } ) // Dialer opens ONE fresh transport to the engine. It is the seam the redial @@ -82,6 +119,27 @@ type Roaming struct { Dial Dialer // Window is how long to keep trying, and zero is [RoamWindow]. Window time.Duration + // MaxLine bounds one inbound line on every link this client reads (see + // [WithMaxLine]). Zero keeps the unbounded reader local pipes and sockets use. + MaxLine int + // ResendUnanswered resends in-flight Submit, FollowUp and Steer calls that + // carry a ClientID when a redial lands on a host advertising + // [Welcome.MessageRepeat], and mints an id for sends that left it empty. + ResendUnanswered bool + // OnGap is called when the engine reports that a resumed stream's ring + // evicted events older than its first retained sequence number. Nil ignores + // the frame and continues reading the retained events. + OnGap func(Gap) + // SpreadReturns says this road is dialled through a relay, which can drop + // every viewer in the same instant, so the first retry waits one second plus + // a random spread of up to five and each later wait is scaled by a random + // 0.75 to 1.25 (V22, W10). IT IS OPT-IN BECAUSE A FIX KEEPS DEFAULTS: an ssh + // `--host` pipe, a local socket and an engine on a pipe are reached by one + // person's own dial, nobody returns with them, and spreading their first + // retry over six seconds would have made every one of those slower to come + // back for a reason that is not theirs. Left false, a road keeps the schedule + // it always had, a fixed first pause and then the doubling. + SpreadReturns bool } func (r *Roaming) window() time.Duration { @@ -107,7 +165,7 @@ func Roam(host string, hello Hello, roam Roaming) (*Client, error) { if err != nil { return nil, err } - c := newClient(host, hello) + c := newClient(host, hello, WithMaxLine(roam.MaxLine)) c.roam = &roam if _, err := c.attach(conn); err != nil { _ = conn.Close() @@ -161,6 +219,45 @@ func plural(n int, word string) string { // ── the loop ──────────────────────────────────────────────────────────────── +// farEndEnded is what an error says when the link under a reader ended because +// the far end CLOSED THE VIEW ON PURPOSE and said why (livedoor's +// `remote-control-off`), as opposed to the link failing. It is an interface for +// the reason [plannedRedial] is: this package cannot import livedoor, and the +// reason itself is read through the `Reason() string` every channel error of a +// live door already has. +type farEndEnded interface{ EndsView() bool } + +// endedByFarEnd answers the closed reason the far end ended the view with, and +// whether the cause is one of those. +func endedByFarEnd(cause error) (reason string, ended bool) { + var ender farEndEnded + if !errors.As(cause, &ender) || !ender.EndsView() { + return "", false + } + var spoken interface{ Reason() string } + if errors.As(cause, &spoken) { + return spoken.Reason(), true + } + return "", false +} + +// plannedRedial is what an error says when the link under a reader ended +// because the road that carries it was CHANGED ON PURPOSE (livedoor's +// `road-change`), not because anything failed. It is an interface so that this +// package, which cannot import livedoor, can still tell the two apart. +// +// A planned redial has nothing to wait for: the far end is up, the new road is +// already open, and the pause an unplanned drop takes exists to let a relay that +// restarted breathe. +type plannedRedial interface{ PlannedRedial() bool } + +// isPlannedRedial reports whether the cause of a lost link asked for the +// immediate redial. +func isPlannedRedial(cause error) bool { + var planned plannedRedial + return errors.As(cause, &planned) && planned.PlannedRedial() +} + // lost is what the reader does when the link under it stops, and it answers // whether reading may carry on. True means a live pipe is in place and the // stream state has been reconciled with what the engine says; false means this @@ -176,6 +273,15 @@ func (c *Client) lost(cause error) bool { c.bury(cause) return false } + // A FAR END THAT ENDED THIS VIEW ON PURPOSE IS NOT A BLIP. It is up, it + // answered, and what it said was that it will not carry the view, so thirty + // minutes of redials would only be thirty minutes of a screen claiming the + // connection is being repaired. The client is buried at once, and what it says + // is the far end's own sentence ([Client.gone]). + if _, ended := endedByFarEnd(cause); ended { + c.bury(cause) + return false + } // THE CALLS IN FLIGHT FAIL AND THE STREAMS DO NOT. A call is a round trip // whose answer was on the pipe that just died, and its caller is waiting on @@ -183,19 +289,46 @@ func (c *Client) lost(cause error) bool { // has not stopped because this laptop's wifi did. That difference is the // whole reason the surface can be redialled under a person without the // conversation noticing. + planned := isPlannedRedial(cause) c.mu.Lock() c.reconnecting = true - waiting := c.calls - c.calls = map[uint64]chan result{} + // THE NOTE IS LATE AND THE REFUSAL IS NOT. Calls are refused for the whole + // gap, because between the new pipe being handed over and its welcome being + // read a call written onto it would arrive before the hello; that part is + // protocol and cannot wait. What a planned redial delays is only the SENTENCE + // ([Client.LinkNote]), so a road swap that takes a few milliseconds shows the + // person nothing at all. + if planned { + c.noteAt = time.Now().Add(plannedNoteAfter) + } else { + c.noteAt = time.Time{} + } + var waiting []chan result + if roam.ResendUnanswered { + for id, answer := range c.calls { + if _, ok := c.pendingSends[id]; ok { + continue + } + delete(c.calls, id) + waiting = append(waiting, answer) + } + } else { + for _, answer := range c.calls { + waiting = append(waiting, answer) + } + c.calls = map[uint64]chan result{} + c.pendingSends = map[uint64]Frame{} + } c.mu.Unlock() refusal := errors.New(c.roamingRefusal()) for _, answer := range waiting { answer <- result{err: refusal} } - welcome, err := c.redial(roam) + welcome, err := c.redial(roam, planned) c.mu.Lock() c.reconnecting = false + c.noteAt = time.Time{} c.mu.Unlock() if err != nil { // A refusal the far end MADE is worth repeating; a redial that simply @@ -212,9 +345,47 @@ func (c *Client) lost(cause error) bool { c.reconcile(left, welcome) c.retakeLanes(left, welcome) c.resendClientTools() + c.resendUnansweredSends(left, welcome, refusal) return true } +func (c *Client) resendUnansweredSends(left string, welcome Welcome, refusal error) { + c.mu.Lock() + if c.roam == nil || !c.roam.ResendUnanswered || !welcome.MessageRepeat || conversationSwitched(left, welcome.SessionFile) { + var failed []chan result + for id := range c.pendingSends { + if answer, ok := c.calls[id]; ok { + delete(c.calls, id) + failed = append(failed, answer) + } + } + c.pendingSends = map[uint64]Frame{} + c.mu.Unlock() + for _, answer := range failed { + answer <- result{err: refusal} + } + return + } + var frames []Frame + for id, frame := range c.pendingSends { + if _, ok := c.calls[id]; ok { + frames = append(frames, frame) + } else { + delete(c.pendingSends, id) + } + } + c.mu.Unlock() + if len(frames) == 0 { + return + } + sort.Slice(frames, func(i, j int) bool { return frames[i].ID < frames[j].ID }) + guard.Go("remote/resend-unanswered", func() { + for _, frame := range frames { + _ = c.write(frame) + } + }) +} + // conversationSwitched reports whether the engine came back with a DIFFERENT // conversation open than the one this window left. // @@ -295,11 +466,35 @@ func (c *Client) retakeLanes(left string, welcome Welcome) { } } +// redialPause is how long to wait before an attempt. A road that does not +// spread its returns ([Roaming.SpreadReturns]) keeps the schedule it always had: +// the base wait, which the loop doubles up to [slowestBackoff]. +func redialPause(first bool, wait time.Duration, spread bool) time.Duration { + if !spread { + return wait + } + if first { + if wait != defaultFirstBackoff { + return wait + } + if retryRand != nil { + return defaultFirstBackoff + time.Duration(retryRand()*float64(firstRetrySpread)) + } + return retryFirst() + } + if retryRand != nil { + return time.Duration(float64(wait) * (jitterLow + retryRand()*jitterSpan)) + } + return retryJitter(wait) +} + // redial is the backoff loop: a pause, an attempt, a longer pause, until the -// engine answers or the window runs out. -func (c *Client) redial(roam *Roaming) (Welcome, error) { +// engine answers or the window runs out. A PLANNED redial makes its first +// attempt with no pause at all; the attempts after it keep the schedule. +func (c *Client) redial(roam *Roaming, planned bool) (Welcome, error) { deadline := time.Now().Add(roam.window()) wait := firstBackoff + first := true for { if c.stopped() { return Welcome{}, errors.New("this connection is closed") @@ -307,13 +502,13 @@ func (c *Client) redial(roam *Roaming) (Welcome, error) { if time.Now().After(deadline) { return Welcome{}, errors.New("the redialling ran out of time") } - timer := time.NewTimer(wait) - select { - case <-c.stop: - timer.Stop() - return Welcome{}, errors.New("this connection is closed") - case <-timer.C: + if !(first && planned) { + pause := redialPause(first, wait, roam.SpreadReturns) + if !redialSleep(c.stop, pause) { + return Welcome{}, errors.New("this connection is closed") + } } + first = false conn, err := roam.Dial() if err == nil { diff --git a/internal/remote/redial_test.go b/internal/remote/redial_test.go index f7fbb2a1a2..d047f8bb28 100644 --- a/internal/remote/redial_test.go +++ b/internal/remote/redial_test.go @@ -15,9 +15,11 @@ import ( "net" "strings" "sync" + "sync/atomic" "testing" "time" + "github.com/Agent-Field/codeaf/internal/guard" "github.com/Agent-Field/codeaf/internal/session" ) @@ -738,3 +740,508 @@ func TestTheWindowIsSpelledTheWayASentenceWantsIt(t *testing.T) { } } } + +// TestTheFirstRetryAfterADropWaitsAJitteredSecond verifies V22 on a road that +// is dialled through a relay ([Roaming.SpreadReturns]): the first retry after a +// dropped link waits 1 s + U[0, 5 s) and each later doubled wait up to the 15 s +// cap is scaled by U[0.75, 1.25), while a drop followed by an immediate success +// still redials once. A road that is not dialled through a relay keeps its old +// schedule, which TestAnSshRoamingClientKeepsItsOldFirstRetryAndSchedule pins. +func TestTheFirstRetryAfterADropWaitsAJitteredSecond(t *testing.T) { + wasRand := retryRand + wasSleep := redialSleep + t.Cleanup(func() { + retryRand = wasRand + redialSleep = wasSleep + }) + + recordSchedule := func(t *testing.T, failuresBeforeSuccess int) ([]time.Duration, int) { + t.Helper() + var mu sync.Mutex + var waits []time.Duration + redialSleep = func(stop <-chan struct{}, d time.Duration) bool { + select { + case <-stop: + return false + default: + mu.Lock() + waits = append(waits, d) + mu.Unlock() + return true + } + } + + dials := 0 + var firstSurface io.ReadWriteCloser + dialer := func() (io.ReadWriteCloser, error) { + mu.Lock() + attempt := dials + dials++ + mu.Unlock() + if attempt > 0 && attempt <= failuresBeforeSuccess { + return nil, errors.New("no route to host") + } + ours, theirs := net.Pipe() + engine := &scripted{ + t: t, + conn: theirs, + said: Welcome{Version: Version, SessionFile: "/j.jsonl", Persistent: true}, + } + guard.Go("remote/test-redial-jitter", func() { engine.serve(nil) }) + if attempt == 0 { + firstSurface = ours + } + return ours, nil + } + + client, err := Roam("devbox", Hello{Workspace: "app"}, Roaming{Dial: dialer, Window: RoamWindow, SpreadReturns: true}) + if err != nil { + t.Fatalf("roam: %v", err) + } + defer func() { _ = client.Close() }() + + _ = firstSurface.Close() + wantDials := 2 + failuresBeforeSuccess + waitFor(t, "the redial schedule to finish", func() bool { + mu.Lock() + got := dials + mu.Unlock() + return got == wantDials && client.LinkNote() == "" + }) + if err := client.Err(); err != nil { + t.Fatalf("client failed after redial: %v", err) + } + mu.Lock() + defer mu.Unlock() + return append([]time.Duration(nil), waits...), dials + } + + // Low extreme: U = 0 gives exactly 1 s on the first retry, then 0.75 of + // each doubled wait (2 s, 4 s, 8 s, and 15 s at the cap). + retryRand = func() float64 { return 0 } + lowWaits, _ := recordSchedule(t, 5) + wantLow := []time.Duration{ + time.Second, + 1500 * time.Millisecond, + 3 * time.Second, + 6 * time.Second, + 11250 * time.Millisecond, + 11250 * time.Millisecond, + } + if len(lowWaits) != len(wantLow) { + t.Fatalf("low-extreme schedule length = %d, want %d (%v)", len(lowWaits), len(wantLow), lowWaits) + } + for i, want := range wantLow { + if lowWaits[i] != want { + t.Fatalf("low-extreme wait %d = %v, want %v", i+1, lowWaits[i], want) + } + } + + // High extreme: U just under 1 gives just under 6 s on the first retry, + // then just under 1.25 of each doubled wait. + retryRand = func() float64 { return 0.9999999 } + highWaits, _ := recordSchedule(t, 5) + highCeilings := []time.Duration{ + 6 * time.Second, + 2500 * time.Millisecond, + 5 * time.Second, + 10 * time.Second, + 18750 * time.Millisecond, + 18750 * time.Millisecond, + } + if len(highWaits) != len(highCeilings) { + t.Fatalf("high-extreme schedule length = %d, want %d (%v)", len(highWaits), len(highCeilings), highWaits) + } + for i, ceiling := range highCeilings { + if highWaits[i] >= ceiling || highWaits[i] < ceiling-time.Millisecond { + t.Fatalf("high-extreme wait %d = %v, want just under %v", i+1, highWaits[i], ceiling) + } + } + + // Default source: ten samples all fall in [1 s, 6 s) on the first retry and + // within [0.75, 1.25) of each doubled wait thereafter, and are not all equal. + retryRand = nil + bands := []struct { + low, high time.Duration + }{ + {time.Second, 6 * time.Second}, + {1500 * time.Millisecond, 2500 * time.Millisecond}, + {3 * time.Second, 5 * time.Second}, + {6 * time.Second, 10 * time.Second}, + {11250 * time.Millisecond, 18750 * time.Millisecond}, + {11250 * time.Millisecond, 18750 * time.Millisecond}, + } + firstSeen := map[time.Duration]bool{} + secondSeen := map[time.Duration]bool{} + for sample := 0; sample < 10; sample++ { + waits, _ := recordSchedule(t, 5) + if len(waits) != len(bands) { + t.Fatalf("sample %d recorded %d waits, want %d", sample, len(waits), len(bands)) + } + for i, band := range bands { + if waits[i] < band.low || waits[i] >= band.high { + t.Fatalf("sample %d wait %d = %v, outside [%v, %v)", sample, i+1, waits[i], band.low, band.high) + } + } + firstSeen[waits[0]] = true + secondSeen[waits[1]] = true + } + if len(firstSeen) < 2 { + t.Fatalf("ten default-source first waits were all identical: %v", firstSeen) + } + if len(secondSeen) < 2 { + t.Fatalf("ten default-source second waits were all identical: %v", secondSeen) + } + + // A drop followed by an immediate success still redials once. + waits, dials := recordSchedule(t, 0) + if dials != 2 || len(waits) != 1 { + t.Fatalf("immediate recovery made %d dials with %d waits (%v), want 2 dials and 1 wait", dials, len(waits), waits) + } + if waits[0] < time.Second || waits[0] >= 6*time.Second { + t.Fatalf("immediate recovery wait = %v, outside [1s, 6s)", waits[0]) + } +} + +// ── planned redials and the roads that spread their returns (phase 2, lane C) ─ + +// endedOnPurpose is the error livedoor's channel returns when the viewer closed +// it for a road swap. It lives here because this package cannot import livedoor +// and the contract between them is only the PlannedRedial method. +type endedOnPurpose struct{} + +func (endedOnPurpose) Error() string { return "road-change" } +func (endedOnPurpose) PlannedRedial() bool { return true } + +// swappable is a pipe that can be ended two ways: dropped, as a network does, +// or closed on purpose by the viewer for a road swap. +type swappable struct { + io.ReadWriteCloser + planned atomic.Bool + // said is what the far end ended the link with, when it ended it by saying + // something: the error [swappable.endWith] stored. + said atomic.Pointer[error] +} + +func (s *swappable) Read(p []byte) (int, error) { + n, err := s.ReadWriteCloser.Read(p) + if err != nil { + if said := s.said.Load(); said != nil { + return n, *said + } + if s.planned.Load() { + return n, endedOnPurpose{} + } + } + return n, err +} + +// endWith closes the link the way a far end that ANSWERED does: the reader gets +// the error the far end's own words are carried by, not a bare end of file. +func (s *swappable) endWith(err error) { + s.said.Store(&err) + _ = s.ReadWriteCloser.Close() +} + +func (s *swappable) endOnPurpose() { + s.planned.Store(true) + _ = s.ReadWriteCloser.Close() +} + +// timeline records, in order, every pause the redial loop asked for and every +// dial it made, so a test reads the schedule instead of sleeping through it. +type timeline struct { + mu sync.Mutex + events []string + pauses []time.Duration +} + +func (tl *timeline) add(kind string, d time.Duration) { + tl.mu.Lock() + defer tl.mu.Unlock() + tl.events = append(tl.events, kind) + if kind == "pause" { + tl.pauses = append(tl.pauses, d) + } +} + +func (tl *timeline) snapshot() ([]string, []time.Duration) { + tl.mu.Lock() + defer tl.mu.Unlock() + return append([]string(nil), tl.events...), append([]time.Duration(nil), tl.pauses...) +} + +// redialRig is a roaming client whose first link can be ended on purpose or +// dropped, whose next `failures` dials fail, and whose pauses are recorded and +// not slept. +func redialRig(t *testing.T, roaming Roaming, failures int) (*Client, *swappable, *timeline) { + t.Helper() + was := redialSleep + t.Cleanup(func() { redialSleep = was }) + tl := &timeline{} + redialSleep = func(stop <-chan struct{}, d time.Duration) bool { + select { + case <-stop: + return false + default: + } + tl.add("pause", d) + return true + } + var mu sync.Mutex + dials := 0 + first := &swappable{} + roaming.Dial = func() (io.ReadWriteCloser, error) { + mu.Lock() + attempt := dials + dials++ + mu.Unlock() + if attempt > 0 { + tl.add("dial", 0) + } + if attempt > 0 && attempt <= failures { + return nil, errors.New("no route to host") + } + ours, theirs := net.Pipe() + engine := &scripted{t: t, conn: theirs, said: Welcome{Version: Version, SessionFile: "/j.jsonl", Persistent: true}} + guard.Go("remote/test-planned-redial", func() { engine.serve(nil) }) + if attempt == 0 { + first.ReadWriteCloser = ours + return first, nil + } + return ours, nil + } + roaming.Window = RoamWindow + client, err := Roam("devbox", Hello{Workspace: "app"}, roaming) + if err != nil { + t.Fatalf("roam: %v", err) + } + t.Cleanup(func() { _ = client.Close() }) + waitFor(t, "the first link", func() bool { return first.ReadWriteCloser != nil }) + return client, first, tl +} + +func settled(t *testing.T, client *Client, tl *timeline, dials int) { + t.Helper() + waitFor(t, "the redial to finish", func() bool { + events, _ := tl.snapshot() + n := 0 + for _, e := range events { + if e == "dial" { + n++ + } + } + return n == dials && client.LinkNote() == "" && !client.isReconnecting() + }) + if err := client.Err(); err != nil { + t.Fatalf("the client failed after the redial: %v", err) + } +} + +func (c *Client) isReconnecting() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.reconnecting +} + +// TestAPlannedRedialSkipsTheFirstJitterAndLaterOnesKeepIt verifies V31 (and G1 of +// SPEC-P2): a link closed on purpose for a road swap is redialled at once, with no +// first pause on any road, and the attempts after it keep the schedule the road +// has: spread on a relay-dialled road, the plain doubling on one that is not. +func TestAPlannedRedialSkipsTheFirstJitterAndLaterOnesKeepIt(t *testing.T) { + wasRand := retryRand + t.Cleanup(func() { retryRand = wasRand }) + retryRand = func() float64 { return 0 } + + t.Run("relay road, planned", func(t *testing.T) { + client, first, tl := redialRig(t, Roaming{SpreadReturns: true}, 2) + first.endOnPurpose() + settled(t, client, tl, 3) + events, pauses := tl.snapshot() + if len(events) == 0 || events[0] != "dial" { + t.Fatalf("a planned redial paused before its first attempt: %v", events) + } + // U = 0 scales each later wait by exactly 0.75: 2 s and 4 s doubled from the base. + want := []time.Duration{1500 * time.Millisecond, 3 * time.Second} + if len(pauses) != len(want) || pauses[0] != want[0] || pauses[1] != want[1] { + t.Fatalf("later attempts keep the spread schedule: pauses %v, want %v", pauses, want) + } + }) + t.Run("plain road, planned", func(t *testing.T) { + client, first, tl := redialRig(t, Roaming{}, 2) + first.endOnPurpose() + settled(t, client, tl, 3) + events, pauses := tl.snapshot() + if len(events) == 0 || events[0] != "dial" { + t.Fatalf("a planned redial paused before its first attempt: %v", events) + } + want := []time.Duration{2 * time.Second, 4 * time.Second} + if len(pauses) != len(want) || pauses[0] != want[0] || pauses[1] != want[1] { + t.Fatalf("later attempts keep the plain schedule: pauses %v, want %v", pauses, want) + } + }) + t.Run("a dropped link is not planned", func(t *testing.T) { + client, first, tl := redialRig(t, Roaming{SpreadReturns: true}, 0) + _ = first.ReadWriteCloser.Close() + settled(t, client, tl, 1) + events, pauses := tl.snapshot() + if len(events) < 2 || events[0] != "pause" || len(pauses) != 1 || pauses[0] != time.Second { + t.Fatalf("an unplanned drop waits before its first attempt: events %v pauses %v", events, pauses) + } + }) +} + +// TestAnSshRoamingClientKeepsItsOldFirstRetryAndSchedule pins the default (fixes +// keep defaults): a road that does not set SpreadReturns, which is every ssh +// `--host` client, local socket and engine pipe, keeps the first pause and the +// doubling it had before the relay's returns were spread, whatever the random +// source says. +func TestAnSshRoamingClientKeepsItsOldFirstRetryAndSchedule(t *testing.T) { + wasRand := retryRand + t.Cleanup(func() { retryRand = wasRand }) + retryRand = func() float64 { return 0.5 } // would be 3.5 s and 1.0 x if it were used at all + + client, first, tl := redialRig(t, Roaming{}, 5) + _ = first.ReadWriteCloser.Close() + settled(t, client, tl, 6) + _, pauses := tl.snapshot() + want := []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 15 * time.Second, 15 * time.Second} + if len(pauses) != len(want) { + t.Fatalf("pauses %v, want %v", pauses, want) + } + for i := range want { + if pauses[i] != want[i] { + t.Fatalf("pause %d = %v, want %v (all: %v)", i+1, pauses[i], want[i], pauses) + } + } +} + +// heldRedial is a roaming client whose first link has just been closed on +// purpose and whose next dial blocks until the returned release is called. +func heldRedial(t *testing.T, noteAfter time.Duration) (*Client, func()) { + t.Helper() + was := plannedNoteAfter + plannedNoteAfter = noteAfter + t.Cleanup(func() { plannedNoteAfter = was }) + + hold := make(chan struct{}) + var once sync.Once + release := func() { once.Do(func() { close(hold) }) } + t.Cleanup(release) + + var mu sync.Mutex + dials := 0 + first := &swappable{} + dial := func() (io.ReadWriteCloser, error) { + mu.Lock() + attempt := dials + dials++ + mu.Unlock() + if attempt > 0 { + <-hold + } + ours, theirs := net.Pipe() + engine := &scripted{t: t, conn: theirs, said: Welcome{Version: Version, SessionFile: "/j.jsonl", Persistent: true}} + guard.Go("remote/test-planned-note", func() { engine.serve(nil) }) + if attempt == 0 { + first.ReadWriteCloser = ours + return first, nil + } + return ours, nil + } + client, err := Roam("devbox", Hello{Workspace: "app"}, Roaming{Dial: dial, Window: time.Minute}) + if err != nil { + t.Fatalf("roam: %v", err) + } + t.Cleanup(func() { _ = client.Close() }) + first.endOnPurpose() + waitFor(t, "the redial to be under way", func() bool { return client.isReconnecting() }) + return client, release +} + +// TestAPlannedRedialSaysNothingUntilItTakesLongerThanAMoment verifies the +// delayed `reconnecting` note of G1: a swap that has not yet taken a moment +// shows the person nothing, though a call made in the gap is still refused +// (nothing may be written between the new pipe and its welcome), and one that +// takes longer says it in the words an unplanned drop uses. +func TestAPlannedRedialSaysNothingUntilItTakesLongerThanAMoment(t *testing.T) { + t.Run("within a moment", func(t *testing.T) { + client, release := heldRedial(t, time.Minute) + if note := client.LinkNote(); note != "" { + t.Fatalf("a swap said %q before it had taken a moment", note) + } + if _, err := client.HeldQuestions(); err == nil { + t.Fatalf("a call made in the gap was not refused") + } + release() + waitFor(t, "the link to come back", func() bool { return !client.isReconnecting() }) + if note := client.LinkNote(); note != "" { + t.Fatalf("a link that came back says %q", note) + } + }) + t.Run("longer than a moment", func(t *testing.T) { + client, release := heldRedial(t, 20*time.Millisecond) + waitFor(t, "the note once the swap outlasts a moment", func() bool { return client.LinkNote() != "" }) + if note := client.LinkNote(); !strings.HasPrefix(note, "reconnecting to devbox") { + t.Fatalf("the note reads %q", note) + } + release() + waitFor(t, "the link to come back", func() bool { return !client.isReconnecting() && client.LinkNote() == "" }) + }) +} + +// farEndSaid is the error livedoor's channel returns when the host ended a view +// on purpose and said why (`remote-control-off`). It lives here for the reason +// [endedOnPurpose] does: the contract between the two packages is only the +// EndsView and Reason methods. +type farEndSaid struct{ reason string } + +func (e farEndSaid) Error() string { return "livedoor: channel reset: " + e.reason } +func (e farEndSaid) EndsView() bool { return true } +func (e farEndSaid) Reason() string { return e.reason } + +// TestAViewTheFarEndEndedOnPurposeIsNotRedialled is the viewer half of the +// contract for turning remote control off on the computer being watched: a link +// that ended because the far end said so ends the client at once, with the far +// end's one sentence, and neither pauses nor dials nor says `reconnecting`. A +// link that merely DROPPED still redials (the tests above), which is the default +// this change keeps. +func TestAViewTheFarEndEndedOnPurposeIsNotRedialled(t *testing.T) { + client, first, tl := redialRig(t, Roaming{SpreadReturns: true}, 0) + first.endWith(farEndSaid{reason: "remote-control-off"}) + + waitFor(t, "the client to end", func() bool { return client.Err() != nil }) + if got, want := client.Err().Error(), "devbox turned remote control off."; got != want { + t.Fatalf("the ended view says %q, want exactly %q", got, want) + } + if note := client.LinkNote(); note != "" { + t.Fatalf("nothing is reconnecting, so the note is empty, not %q", note) + } + time.Sleep(100 * time.Millisecond) + if events, _ := tl.snapshot(); len(events) != 0 { + t.Fatalf("the client paused or dialled after the far end ended the view: %v", events) + } +} + +// A far end that ended the view with a reason that is NOT the final one is still +// redialled, and a reason the viewer has no sentence for does not end it either: +// the set that ends a view for good is closed. +func TestAViewEndedWithAnyOtherReasonIsStillRedialled(t *testing.T) { + for _, reason := range []string{"permit-changed", "lagging", "host-closing", "a-reason-from-a-newer-build"} { + t.Run(reason, func(t *testing.T) { + client, first, tl := redialRig(t, Roaming{SpreadReturns: true}, 0) + first.endWith(notFinal{reason: reason}) + settled(t, client, tl, 1) + if events, _ := tl.snapshot(); len(events) == 0 { + t.Fatalf("a %q end was not redialled", reason) + } + }) + } +} + +// notFinal is a reason-bearing channel error that does not end the view for good. +type notFinal struct{ reason string } + +func (e notFinal) Error() string { return "livedoor: channel reset: " + e.reason } +func (e notFinal) EndsView() bool { return false } +func (e notFinal) Reason() string { return e.reason } diff --git a/internal/remote/remote_guest_test.go b/internal/remote/remote_guest_test.go new file mode 100644 index 0000000000..6cb65b1a43 --- /dev/null +++ b/internal/remote/remote_guest_test.go @@ -0,0 +1,252 @@ +package remote + +import ( + "sync" + "testing" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/session" +) + +type consentFromCall struct { + id uint64 + allow bool + remote bool +} + +// guestAnswerAgent extends fakeAgent with the unified question door, the +// remote-aware consent door, and the approval posture door so the wire test can +// observe what the server stamps and what it blocks before reaching the agent. +type guestAnswerAgent struct { + *fakeAgent + + mu sync.Mutex + resolved []session.Answer + resolveErr error + consentsFrom []consentFromCall + consentFromErr error + consentRemembers int + setApprovals int +} + +func (g *guestAnswerAgent) ResolveQuestion(answer session.Answer) error { + g.mu.Lock() + defer g.mu.Unlock() + g.resolved = append(g.resolved, answer) + return g.resolveErr +} + +func (g *guestAnswerAgent) ResolveConsentFrom(id uint64, allow bool, remote bool) error { + g.mu.Lock() + defer g.mu.Unlock() + g.consentsFrom = append(g.consentsFrom, consentFromCall{id: id, allow: allow, remote: remote}) + return g.consentFromErr +} + +func (g *guestAnswerAgent) ResolveConsentRemember(id uint64, allow bool, scope session.ConsentScope) { + g.mu.Lock() + g.consentRemembers++ + g.mu.Unlock() + g.fakeAgent.ResolveConsentRemember(id, allow, scope) +} + +func (g *guestAnswerAgent) ApprovalDial() bool { return true } + +func (g *guestAnswerAgent) ResolvedApprovalPosture() string { return session.PostureAsk } + +func (g *guestAnswerAgent) SetApprovalPosture(string) error { + g.mu.Lock() + defer g.mu.Unlock() + g.setApprovals++ + return nil +} + +// TestARemoteDriverCannotAnswerAnIrreversibleAskRememberAPermissionOrRaiseThePosture +// verifies V26 on the remote wire: the server overwrites Answer.Remote from the +// connection's guest stamp in both directions, translates ErrRemoteIrreversible +// and ErrRemoteWidening into the host-named chatlist refusal sentences without +// dropping the connection, refuses MethodSetApproval and MethodConsentRemember +// before reaching the agent, and routes a remote guest's MethodConsent through +// ResolveConsentFrom with remote=true while keeping a local connection on the +// plain ResolveConsent path. +func TestARemoteDriverCannotAnswerAnIrreversibleAskRememberAPermissionOrRaiseThePosture(t *testing.T) { + base := &fakeAgent{} + agent := &guestAnswerAgent{fakeAgent: base} + engine := engineOn(base) + engine.Agent = agent + sess := NewSession(engine, true) + + local := dialSession(t, sess) + localWelcome := local.hello(Hello{ + Version: Version, + Surface: "macbook", + }) + if localWelcome.Kind != "welcome" { + t.Fatalf("local handshake answered %q: %s", localWelcome.Kind, localWelcome.Error) + } + + guest := dialSession(t, sess) + guestWelcome := guest.hello(Hello{ + Version: Version, + Surface: "laptop", + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-drive", + Label: "laptop", + Watch: true, + Drive: true, + Road: "relay", + }, + }) + if guestWelcome.Kind != "welcome" { + t.Fatalf("remote drive handshake answered %q: %s", guestWelcome.Kind, guestWelcome.Error) + } + + host := HostName() + + // 1. A remote drive guest's MethodQuestionResolve reaches the agent with + // Answer.Remote == true even when the wire arguments said remote:false. + guest.ok(1, MethodQuestionResolve, QuestionArgs{ + Answer: session.Answer{Kind: session.QuestionConsent, ID: 10, Key: "1", Remote: false}, + }) + agent.mu.Lock() + if len(agent.resolved) != 1 || !agent.resolved[0].Remote { + t.Fatalf("remote guest MethodQuestionResolve delivered %+v, want Remote=true", agent.resolved) + } + agent.mu.Unlock() + + // 2. A local connection's MethodQuestionResolve reaches the agent with + // Answer.Remote == false even when the wire arguments said remote:true. + local.ok(1, MethodQuestionResolve, QuestionArgs{ + Answer: session.Answer{Kind: session.QuestionConsent, ID: 11, Key: "1", Remote: true}, + }) + agent.mu.Lock() + if len(agent.resolved) != 2 || agent.resolved[1].Remote { + t.Fatalf("local MethodQuestionResolve delivered %+v, want Remote=false", agent.resolved) + } + agent.mu.Unlock() + + // 3. When the agent returns session.ErrRemoteIrreversible, the remote + // viewer receives chatlist.LiveNeedsItsOwnOK(host) and the connection stays up. + agent.mu.Lock() + agent.resolveErr = session.ErrRemoteIrreversible + agent.mu.Unlock() + irrevRes := guest.call(2, MethodQuestionResolve, QuestionArgs{ + Answer: session.Answer{Kind: session.QuestionConsent, ID: 12, Key: "1"}, + }) + if want := chatlist.LiveNeedsItsOwnOK(host); irrevRes.Error != want { + t.Fatalf("ErrRemoteIrreversible mapped to %q, want %q", irrevRes.Error, want) + } + + // 4. When the agent returns session.ErrRemoteWidening, the remote viewer + // receives chatlist.LiveNotAllowedHere(host) and the connection stays up. + agent.mu.Lock() + agent.resolveErr = session.ErrRemoteWidening + agent.mu.Unlock() + widenRes := guest.call(3, MethodQuestionResolve, QuestionArgs{ + Answer: session.Answer{Kind: session.QuestionConsent, ID: 13, Key: "2"}, + }) + if want := chatlist.LiveNotAllowedHere(host); widenRes.Error != want { + t.Fatalf("ErrRemoteWidening mapped to %q, want %q", widenRes.Error, want) + } + agent.mu.Lock() + agent.resolveErr = nil + agent.mu.Unlock() + + // Prove the guest connection stayed up after both refusals. + guest.ok(4, MethodPing, nil) + + // 5. MethodSetApproval and MethodConsentRemember from a remote drive guest + // are refused with chatlist.LiveNotAllowedHere(host) and the agent's + // counters for both stay 0. + setApprovalRes := guest.call(5, MethodSetApproval, session.PostureAllow) + if want := chatlist.LiveNotAllowedHere(host); setApprovalRes.Error != want { + t.Fatalf("remote drive guest MethodSetApproval answered %q, want %q", setApprovalRes.Error, want) + } + rememberRes := guest.call(6, MethodConsentRemember, ConsentArgs{ + ID: 14, + Allow: true, + Scope: session.ConsentToolSession, + }) + if want := chatlist.LiveNotAllowedHere(host); rememberRes.Error != want { + t.Fatalf("remote drive guest MethodConsentRemember answered %q, want %q", rememberRes.Error, want) + } + agent.mu.Lock() + if agent.setApprovals != 0 { + t.Fatalf("agent SetApprovalPosture counter = %d, want 0", agent.setApprovals) + } + if agent.consentRemembers != 0 { + t.Fatalf("agent ResolveConsentRemember counter = %d, want 0", agent.consentRemembers) + } + agent.mu.Unlock() + + // 6. A remote guest's MethodConsent reaches ResolveConsentFrom(.., remote=true) + // and NOT ResolveConsent, and maps ErrRemoteIrreversible to LiveNeedsItsOwnOK. + guest.ok(7, MethodConsent, ConsentArgs{ID: 21, Allow: true}) + agent.mu.Lock() + if len(agent.consentsFrom) != 1 || agent.consentsFrom[0] != (consentFromCall{id: 21, allow: true, remote: true}) { + t.Fatalf("remote guest MethodConsent recorded %+v, want [{id:21 allow:true remote:true}]", agent.consentsFrom) + } + agent.mu.Unlock() + base.mu.Lock() + if len(base.consents) != 0 { + t.Fatalf("remote guest MethodConsent reached plain ResolveConsent: %v", base.consents) + } + base.mu.Unlock() + + agent.mu.Lock() + agent.consentFromErr = session.ErrRemoteIrreversible + agent.mu.Unlock() + consentIrrev := guest.call(8, MethodConsent, ConsentArgs{ID: 22, Allow: true}) + if want := chatlist.LiveNeedsItsOwnOK(host); consentIrrev.Error != want { + t.Fatalf("remote guest MethodConsent irreversible error = %q, want %q", consentIrrev.Error, want) + } + agent.mu.Lock() + agent.consentFromErr = nil + agent.mu.Unlock() + + // 7. A local connection's MethodConsent reaches the plain ResolveConsent + // exactly as before, without calling ResolveConsentFrom. + local.ok(2, MethodConsent, ConsentArgs{ID: 31, Allow: false}) + agent.mu.Lock() + if len(agent.consentsFrom) != 2 { + t.Fatalf("local MethodConsent called ResolveConsentFrom: %+v", agent.consentsFrom) + } + agent.mu.Unlock() + base.mu.Lock() + if len(base.consents) != 1 || base.consents[0] != "consent:31:no" { + t.Fatalf("local MethodConsent recorded %v, want [consent:31:no]", base.consents) + } + base.mu.Unlock() +} + +// V26: an engine that cannot say whether an ask is one only the host may settle +// is an engine a remote guest may not answer for. A drive guest's consent +// against an engine without the remote-aware door is refused with the sentence +// the question door gives and nothing is delivered, where falling through to the plain +// door would settle even an irreversible ask. +func TestARemoteGuestIsRefusedConsentWhereTheEngineCannotTellWhoMaySettleIt(t *testing.T) { + base := &fakeAgent{} + sess := NewSession(engineOn(base), true) + guest := dialSession(t, sess) + welcome := guest.hello(Hello{ + Version: Version, + Surface: "laptop", + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{Device: "dev-drive", Label: "laptop", Watch: true, Drive: true, Road: "relay"}, + }) + if welcome.Kind != "welcome" { + t.Fatalf("handshake answered %q: %s", welcome.Kind, welcome.Error) + } + got := guest.call(1, MethodConsent, ConsentArgs{ID: 7, Allow: true}) + if want := "engine: this session cannot answer questions from here"; got.Error != want { + t.Fatalf("consent without the remote-aware door answered %q, want %q", got.Error, want) + } + base.mu.Lock() + defer base.mu.Unlock() + if len(base.consents) != 0 { + t.Fatalf("a guest's consent reached the plain door: %v", base.consents) + } +} diff --git a/internal/remote/server.go b/internal/remote/server.go index de45ac9f8f..5ec3b6603a 100644 --- a/internal/remote/server.go +++ b/internal/remote/server.go @@ -62,12 +62,14 @@ import ( "github.com/Agent-Field/codeaf/internal/syncwords" "github.com/Agent-Field/codeaf/internal/wireauth" "io" + "os" "path/filepath" "sort" "strings" "sync" "sync/atomic" "time" + "unicode/utf8" "github.com/Agent-Field/codeaf/internal/buildinfo" "github.com/Agent-Field/codeaf/internal/executor" @@ -374,7 +376,37 @@ const frameCap = 64 << 20 // of the session file, everything that landed is in it, and the surface reads // it anyway. The ring exists for the one thing the journal cannot answer — a // turn that is still being written — and for nothing else. -const ringEvents = 4096 +const ( + ringEvents = 4096 + // ringBytes caps the total payload bytes one running stream's replay ring + // retains beside ringEvents. The newest event is always kept even when it + // exceeds this bound on its own, so first and last remain exact. + ringBytes = 1 << 20 + + // messageRepeatCap bounds the per-Session table of recent remote sends + // keyed by (Remote.Device, SubmitArgs.ClientID). + messageRepeatCap = 256 + // messageRepeatTailScan bounds how many entries at the tail of the + // persisted transcript are checked for a PersonMark.ClientID before a new + // remote send is delivered. + messageRepeatTailScan = 200 +) + +var ( + ringEventLimit = ringEvents + ringByteLimit = ringBytes +) + +type messageRepeatKey struct { + device string + clientID string +} + +type messageRepeatEntry struct { + done chan struct{} + payload json.RawMessage + ok bool +} // Serve runs one engine on one pipe until the pipe dies or the protocol does. // It returns nil for an ordinary hang-up and an error for everything the @@ -525,6 +557,11 @@ type Session struct { // are driver.go's, and that file is the whole of the rule. driver *server arrivals uint64 + // kept is the keyboard a remote viewer held when its link ended, held for + // that same viewer for [keyboardKeepFor] (driver.go's keptKeyboard). It is + // what lets a road swap, which closes the old link BEFORE the new one + // arrives, hand the keyboard back to the viewer that had it. + kept *keptKeyboard // factsRev counts the fact sets this session has stated. It is minted under // mu beside the reading it labels, which is what makes it an ORDER and not // a timestamp: two facts can move in the same instant and the two pushes @@ -550,6 +587,10 @@ type Session struct { // unattended door takes can say which window it believed had gone. It is a // label, never an identity, and empty when nobody was ever here. lastWatch string + + repeatMu sync.Mutex + repeats map[messageRepeatKey]*messageRepeatEntry + repeatOrder []messageRepeatKey } // watchGrace is how long a window goes on counting as somebody watching after @@ -588,6 +629,7 @@ func NewSession(engine *Engine, persistent bool) *Session { tasklanes: map[*server]*taskFeed{}, lanes: map[laneName]map[*server]*laneFeed{}, newsfeeds: map[*server]*newsFeed{}, + repeats: map[messageRepeatKey]*messageRepeatEntry{}, empty: time.Now(), } // The conversation watches its own turns from the moment it exists, so a @@ -1067,14 +1109,30 @@ type ring struct { // zero means "nothing of this stream has been seen" (wire.go's Frame.Seq). first uint64 last uint64 + bytes int events []json.RawMessage } func (r *ring) add(payload json.RawMessage) uint64 { r.last++ r.events = append(r.events, payload) - if len(r.events) > ringEvents { - r.events = r.events[len(r.events)-ringEvents:] + r.bytes += len(payload) + maxEvents := ringEventLimit + if maxEvents < 1 { + maxEvents = 1 + } + maxBytes := ringByteLimit + evicted := 0 + for len(r.events)-evicted > 1 && (len(r.events)-evicted > maxEvents || (maxBytes > 0 && r.bytes > maxBytes)) { + r.bytes -= len(r.events[evicted]) + r.events[evicted] = nil + evicted++ + } + if evicted > 0 { + r.events = r.events[evicted:] + if cap(r.events) > 2*maxEvents && cap(r.events) >= 64 { + r.events = append([]json.RawMessage(nil), r.events...) + } r.first = r.last - uint64(len(r.events)) + 1 } return r.last @@ -1150,7 +1208,15 @@ func (sess *Session) attach(s *server, hello Hello) error { // THE ARRIVAL IS NUMBERED BEFORE THE WELCOME IS BUILT, because the welcome // says which questions THIS surface is owed and the number is how a card // names the surfaces that have already drawn it (held.go). - s.name = machineLabel(hello.Surface) + if hello.Remote != nil && s.remote == nil { + copied := *hello.Remote + s.remote = &copied + } + surface := hello.Surface + if s.remote != nil { + surface = s.remote.Label + } + s.name = machineLabel(surface) s.clientID = strings.TrimSpace(hello.ClientID) // THE ARRIVAL IS AN ACT. A window that has just been welcomed is // watching, and a pipe that tears on the way in — or a getter that @@ -1162,22 +1228,24 @@ func (sess *Session) attach(s *server, hello Hello) error { } sess.arrivals++ s.arrived = sess.arrivals + // THE NEWEST WINDOW DRIVES, and a window that merely lost its link is not a + // new one (driver.go states the whole rule, [Hello.Back] states why the + // difference is load-bearing). A WATCHER IS NEITHER: it never drives, and the + // flag is recorded so no later hand-on can give it the keyboard either. For a + // remote viewer the host decides from the door's stamp rather than trusting + // the viewer's own Watch flag. + s.watching = hello.Watch || (s.remote != nil && !s.remote.Drive) // Attached counts the OTHERS, so it is read before this one is added // (wire.go's Welcome.Attached states why the number is carried at all). welcome := sess.welcomeLocked(s) // The initial capability reads the arrival directly, preserving the machine's // existing point at which a watcher becomes registered. - welcome.TaskComputers = !hello.Watch && sess.engine.SessionFile != "" && taskComputersKnown(sess.agent) + welcome.TaskComputers = !s.watching && sess.engine.SessionFile != "" && taskComputersKnown(sess.agent) welcome.Encoding = s.encoding welcome.Attached = len(sess.surfaces) sess.surfaces[s] = struct{}{} sess.empty = time.Time{} sess.releaseOnIdle = false - // THE NEWEST WINDOW DRIVES, and a window that merely lost its link is not a - // new one (driver.go states the whole rule, [Hello.Back] states why the - // difference is load-bearing). A WATCHER IS NEITHER: it never drives, and the - // flag is recorded so no later hand-on can give it the keyboard either. - s.watching = hello.Watch if hello.Join { // WHAT THIS CONNECTION IS BOUND TO is the conversation it named, confirmed // against the one open under this same lock a few lines above. The engine's @@ -1189,9 +1257,18 @@ func (sess *Session) attach(s *server, hello Hello) error { // window may replace that stale driver, because Attached counts every live // surface and cannot distinguish the returning window from another one. // Replacing the driver pointer makes the old pipe a non-driver immediately; - // its later detach therefore cannot take the keyboard away again. - sameReturningWindow := hello.Back && s.clientID != "" && sess.driver != nil && sess.driver.clientID == s.clientID - if !s.watching && (!hello.Back || sess.driver == nil || sameReturningWindow) { + // its later detach therefore cannot take the keyboard away again. A remote + // viewer never takes the keyboard on arrival; it takes only via MethodTake, + // EXCEPT THAT A REMOTE VIEWER WHICH IS THE ONE THAT HOLDS IT, OR HELD IT A + // MOMENT AGO, keeps it (driver.go's [Session.remoteKeepsKeyboardLocked]). + // A redial, and a swap of the road under a view, are the same viewer coming + // back, and a viewer that lost the keyboard on every one of them could never + // type through a road change. + sameReturningWindow := hello.Back && s.clientID != "" && sess.driver != nil && sess.driver.remote == nil && s.remote == nil && sess.driver.clientID == s.clientID + switch { + case !s.watching && s.remote == nil && (!hello.Back || sess.driver == nil || sameReturningWindow): + sess.takeLocked(s) + case !s.watching && s.remote != nil && sess.remoteKeepsKeyboardLocked(s): sess.takeLocked(s) } welcome.Driver = sess.driverForLocked(s) @@ -1242,6 +1319,7 @@ func (sess *Session) detach(s *server, deliberate bool) { // (driver.go's handOnLocked). moved := false if sess.driver == s { + sess.keepKeyboardLocked(s, deliberate) sess.handOnLocked() moved = true } @@ -1423,6 +1501,7 @@ func (sess *Session) welcomeLocked(s *server) Welcome { Launch: sess.engine.Launch, Facts: sess.factsLocked(), SteerRepeat: steerRepeatKnown(sess.agent), + MessageRepeat: s.remote != nil, QueuedMarks: queuedMarksKnown(sess.agent), AppTaskReceipt: appTaskReceiptKnown(sess.agent), // Whether this engine can hold a folder at all, asked of the agent it has @@ -1484,7 +1563,16 @@ func (sess *Session) welcomeLocked(s *server) Welcome { SideAsk: sideAskKnown(sess.agent), SideAskStream: sideAskStreamKnown(sess.agent), Setup: setupKnown(sess.agent), + Remote: remoteCopy(s.remote), + } +} + +func remoteCopy(r *RemoteViewer) *RemoteViewer { + if r == nil { + return nil } + copied := *r + return &copied } // factsLocked is the fact set as it stands, numbered. @@ -1627,7 +1715,16 @@ func (sess *Session) replayLocked(cursors []StreamCursor) []Frame { var frames []Frame for _, id := range ids { - from, events := sess.rings[id].after(seen[id]) + r := sess.rings[id] + seq := seen[id] + if seq+1 < r.first { + frames = append(frames, Frame{ + Kind: "gap", + ID: id, + Payload: mustJSON(Gap{Stream: id, Have: seq, First: r.first}), + }) + } + from, events := r.after(seq) for offset, payload := range events { frames = append(frames, Frame{ Kind: "event", @@ -1869,10 +1966,17 @@ type server struct { // is not a slow surface, it is a surface that can never parse this stream // again, so every writer on this process goes through here. write sync.Mutex + in io.Reader out io.Writer // dead records that the far end stopped listening. A write error is not // worth reporting twice and there is nowhere left to report it to. dead bool + // lagging records that a remote guest overran GuestWriteDeadline and was + // dropped so it could not stall the holder or other windows. + lagging atomic.Bool + // droppedOversize counts outbound non-result, non-event frames dropped + // because their uncompressed line exceeded DefaultMaxLine on a guest link. + droppedOversize atomic.Uint64 // encoding is selected from the hello before the welcome is sent. Empty is // the old wire, which keeps a new engine compatible with an older surface. encoding string @@ -1909,6 +2013,9 @@ type server struct { // because a welcome proves whose conversation this was at the instant of // arriving and another window can replace it a second later. joined string + // remote is a copy of the viewer stamp from [Hello.Remote], or nil for a + // local or full-machine connection. + remote *RemoteViewer // pending is the stream a call has just opened and dispatch has not yet let // speak. It is one slot rather than a queue, and it needs no lock, because @@ -1961,6 +2068,7 @@ type server struct { } func (s *server) serve(in io.Reader) (err error) { + s.in = in defer func() { if recovered := recover(); recovered != nil { // A panic in a handler must not end the process in silence: the @@ -2055,6 +2163,12 @@ func (s *server) serve(in io.Reader) (err error) { return nil } } + // A GUEST THAT WAS DROPPED FOR LAGGING ENDS HERE LIKE ANY HANG-UP, not as the + // protocol breaking: closing its connection is what made the read fail. A + // local surface keeps reporting the read error it always did. + if s.remote != nil && s.hungUp() { + return nil + } if err := scan.Err(); err != nil { // A line too long or a read that failed is the protocol breaking, not a // person leaving. @@ -2145,6 +2259,13 @@ func (s *server) handshake(line []byte) error { if hello.Version != Version { return s.refuse(wireMismatchSentence(MachineName(), Version, hello.Version, buildinfo.String())) } + if hello.Remote != nil { + if !hello.Join || hello.New { + return s.refuse("remote control opens a chat that is already running; it never starts one") + } + copied := *hello.Remote + s.remote = &copied + } if supportsEncoding(hello.Encodings, frameEncodingGzip) { s.encoding = frameEncodingGzip @@ -2373,7 +2494,11 @@ func (s *server) invoke(call Frame) (out json.RawMessage, err error) { // model, resolving a card, reviving a node, opening another session and // closing this one all change the conversation without a word being said, and // every one of them was open to a reader before this ([Hello.Watch]). - if s.watching && !watcherMay(call.Method) { + if s.remote != nil { + if !GuestMay(call.Method, s.remote.Drive) { + return nil, errors.New(GuestRefusal(HostName(), call.Method, s.remote.Drive)) + } + } else if s.watching && !watcherMay(call.Method) { return nil, fmt.Errorf("%s (%s)", watchingWord, call.Method) } // THE DOORS THAT PUT WORDS INTO THE CONVERSATION ARE THE DRIVER'S, and @@ -2629,7 +2754,17 @@ func (s *server) invoke(call Frame) (out json.RawMessage, err error) { if !ok { return nil, errors.New("engine: this session cannot answer questions from here") } - return nil, door.ResolveQuestion(args.Answer) + args.Answer.Remote = s.remote != nil + if err := door.ResolveQuestion(args.Answer); err != nil { + if errors.Is(err, session.ErrRemoteIrreversible) { + return nil, errors.New(chatlist.LiveNeedsItsOwnOK(HostName())) + } + if errors.Is(err, session.ErrRemoteWidening) { + return nil, errors.New(chatlist.LiveNotAllowedHere(HostName())) + } + return nil, err + } + return nil, nil case MethodQuestionHold: args, err := arg[QuestionHoldArgs](call) if err != nil { @@ -2935,41 +3070,48 @@ func (s *server) invoke(call Frame) (out json.RawMessage, err error) { if err != nil { return nil, err } - // A MESSAGE WITH A MARK IS RECORDED WITH IT OR REFUSED WHOLE. Running - // only its words would silently lose what the person attached or read. - var events <-chan session.Event - door, marked := agent.(interface { - SubmitMessage(context.Context, session.Submission) (<-chan session.Event, error) - }) - hasMark := args.marked() - if args.composed() || args.WantReceipt { - // PICTURES ARE SENT WITH THE MESSAGE OR THE MESSAGE IS NOT SENT, and the - // receipt rides the answer that names the stream. - composer, ok := agent.(composedDoor) - if !ok { - return nil, errors.New("engine: this session cannot take pictures with a message; update the engine before sending it") + return s.deliverIdempotent(agent, args.ClientID, func() (json.RawMessage, error) { + // A MESSAGE WITH A MARK IS RECORDED WITH IT OR REFUSED WHOLE. Running + // only its words would silently lose what the person attached or read. + var events <-chan session.Event + door, marked := agent.(interface { + SubmitMessage(context.Context, session.Submission) (<-chan session.Event, error) + }) + hasMark := args.marked() + if s.remote != nil && !marked { + withoutID := args + withoutID.ClientID = "" + hasMark = withoutID.marked() } - receipt, events, err := composer.SubmitComposed(context.Background(), args.submission()) - if err != nil { - return nil, err + if args.composed() || args.WantReceipt { + // PICTURES ARE SENT WITH THE MESSAGE OR THE MESSAGE IS NOT SENT, and the + // receipt rides the answer that names the stream. + composer, ok := agent.(composedDoor) + if !ok { + return nil, errors.New("engine: this session cannot take pictures with a message; update the engine before sending it") + } + receipt, events, err := composer.SubmitComposed(context.Background(), args.submission()) + if err != nil { + return nil, err + } + if _, err := s.stream(MethodSubmit, args.Text, events, nil); err != nil { + return nil, err + } + return json.Marshal(StreamRef{Stream: s.pending.id, Receipt: &receipt}) } - if _, err := s.stream(MethodSubmit, args.Text, events, nil); err != nil { - return nil, err + if hasMark && !marked { + return nil, errors.New("engine: this session cannot keep a message's description; update the engine before sending it") } - return json.Marshal(StreamRef{Stream: s.pending.id, Receipt: &receipt}) - } - if hasMark && !marked { - return nil, errors.New("engine: this session cannot keep a message's description; update the engine before sending it") - } - // A creation context alone is no mark a door must keep, but a door that - // can take it is handed it; one that cannot runs the words, and the team - // stays unknown there. - if hasMark || (marked && args.Creation != nil) { - events, err = door.SubmitMessage(context.Background(), args.submission()) - } else { - events, err = agent.Submit(context.Background(), args.Text) - } - return s.stream(MethodSubmit, args.Text, events, err) + // A creation context alone is no mark a door must keep, but a door that + // can take it is handed it; one that cannot runs the words, and the team + // stays unknown there. + if hasMark || (marked && (args.Creation != nil || args.ClientID != "")) { + events, err = door.SubmitMessage(context.Background(), args.submission()) + } else { + events, err = agent.Submit(context.Background(), args.Text) + } + return s.stream(MethodSubmit, args.Text, events, err) + }) case MethodQuestionReplace: args, err := arg[QuestionArgs](call) @@ -2989,28 +3131,36 @@ func (s *server) invoke(call Frame) (out json.RawMessage, err error) { if err != nil { return nil, err } - // A MARKED FOLLOW-UP IS QUEUED WITH ITS MARK OR REFUSED before anything - // is queued; its stream is registered for the take-back below exactly as - // a plain one's is. - var events <-chan session.Event - if args.composed() { - return nil, errors.New("engine: a queued message carries no pictures; send them as a message") - } - door, ok := followUpMarksDoor(agent) - switch { - case args.marked() && !ok: - return nil, errors.New("engine: this session cannot keep a follow-up's description; update the engine before sending it") - case ok: - // A FOLLOW-UP BY THIS WIRE IS THE PERSON'S, marked or not, and the - // agent's mark door is its person door ([session.Agent.FollowUpMessage]): - // plain FollowUp is also an engine door and counts nobody. A creation - // context rides to it too; a door that cannot keep one queues the - // words and the team stays unknown. - events, err = door(args.submission()) - default: - events, err = agent.FollowUp(args.Text) - } - return s.stream(MethodFollowUp, args.Text, events, err) + return s.deliverIdempotent(agent, args.ClientID, func() (json.RawMessage, error) { + // A MARKED FOLLOW-UP IS QUEUED WITH ITS MARK OR REFUSED before anything + // is queued; its stream is registered for the take-back below exactly as + // a plain one's is. + var events <-chan session.Event + if args.composed() { + return nil, errors.New("engine: a queued message carries no pictures; send them as a message") + } + door, ok := followUpMarksDoor(agent) + hasMark := args.marked() + if s.remote != nil && !ok { + withoutID := args + withoutID.ClientID = "" + hasMark = withoutID.marked() + } + switch { + case hasMark && !ok: + return nil, errors.New("engine: this session cannot keep a follow-up's description; update the engine before sending it") + case ok: + // A FOLLOW-UP BY THIS WIRE IS THE PERSON'S, marked or not, and the + // agent's mark door is its person door ([session.Agent.FollowUpMessage]): + // plain FollowUp is also an engine door and counts nobody. A creation + // context rides to it too; a door that cannot keep one queues the + // words and the team stays unknown. + events, err = door(args.submission()) + default: + events, err = agent.FollowUp(args.Text) + } + return s.stream(MethodFollowUp, args.Text, events, err) + }) case MethodUnqueueFollowUp: args, err := arg[UnqueueArgs](call) @@ -3045,28 +3195,36 @@ func (s *server) invoke(call Frame) (out json.RawMessage, err error) { if err != nil { return nil, err } - // A MARKED CORRECTION IS SPLICED WITH ITS MARK OR REFUSED before it - // reaches the turn. - var events <-chan session.Event - if args.composed() { - return nil, errors.New("engine: a correction carries no pictures; send them as a message") - } - door, ok := steerMarksDoor(agent) - switch { - case args.marked() && !ok: - return nil, errors.New("engine: this session cannot keep a correction's description; update the engine before sending it") - case args.marked(): - events, err = door(args.submission()) - case ok: - // A CORRECTION BY THIS WIRE IS THE PERSON'S, marked or not, and the - // agent's mark door is its person door ([session.Agent.SteerMessage]): - // plain Steer is also the engine's and runners' door and counts - // nobody. The words go alone, as they did by Steer. - events, err = door(session.Submission{Text: args.Text}) - default: - events, err = agent.Steer(args.Text) - } - return s.stream(MethodSteer, args.Text, events, err) + return s.deliverIdempotent(agent, args.ClientID, func() (json.RawMessage, error) { + // A MARKED CORRECTION IS SPLICED WITH ITS MARK OR REFUSED before it + // reaches the turn. + var events <-chan session.Event + if args.composed() { + return nil, errors.New("engine: a correction carries no pictures; send them as a message") + } + door, ok := steerMarksDoor(agent) + hasMark := args.marked() + if s.remote != nil && !ok { + withoutID := args + withoutID.ClientID = "" + hasMark = withoutID.marked() + } + switch { + case hasMark && !ok: + return nil, errors.New("engine: this session cannot keep a correction's description; update the engine before sending it") + case args.marked() && ok: + events, err = door(args.submission()) + case ok: + // A CORRECTION BY THIS WIRE IS THE PERSON'S, marked or not, and the + // agent's mark door is its person door ([session.Agent.SteerMessage]): + // plain Steer is also the engine's and runners' door and counts + // nobody. The words go alone, as they did by Steer. + events, err = door(session.Submission{Text: args.Text}) + default: + events, err = agent.Steer(args.Text) + } + return s.stream(MethodSteer, args.Text, events, err) + }) case MethodSubmitImage: args, err := arg[SubmitImageArgs](call) @@ -3370,6 +3528,28 @@ func (s *server) invoke(call Frame) (out json.RawMessage, err error) { if err != nil { return nil, err } + if s.remote != nil { + // A GUEST NEVER TAKES THE PLAIN ROAD. An engine that cannot say whether an + // ask is one only this computer may settle is an engine a guest may not + // answer for, so a missing door refuses rather than falling through to + // [session.Agent.ResolveConsent], which settles whatever it is handed. + door, ok := agent.(interface { + ResolveConsentFrom(uint64, bool, bool) error + }) + if !ok { + return nil, errors.New("engine: this session cannot answer questions from here") + } + if err := door.ResolveConsentFrom(args.ID, args.Allow, true); err != nil { + if errors.Is(err, session.ErrRemoteIrreversible) { + return nil, errors.New(chatlist.LiveNeedsItsOwnOK(HostName())) + } + if errors.Is(err, session.ErrRemoteWidening) { + return nil, errors.New(chatlist.LiveNotAllowedHere(HostName())) + } + return nil, err + } + return nil, nil + } agent.ResolveConsent(args.ID, args.Allow) return nil, nil @@ -3444,6 +3624,13 @@ func (s *server) invoke(call Frame) (out json.RawMessage, err error) { case MethodTranscript: return json.Marshal(agent.Transcript()) + case MethodTranscriptPage: + args, err := arg[TranscriptPageArgs](call) + if err != nil { + return nil, err + } + return json.Marshal(transcriptPage(agent.Transcript(), args)) + case MethodEarlier: return json.Marshal(agent.EarlierHistory()) @@ -3814,6 +4001,136 @@ func arg[T any](call Frame) (T, error) { return value, nil } +// transcriptPage cuts one entry- and byte-bounded window ending at args.Before +// from the full transcript list. It trims from the older end first so a page +// always ends at the requested index and the older entries arrive on the next +// backward call; when a single entry exceeds maxBytes on its own, that entry is +// returned alone with its text shortened and marked rather than dropped. +func transcriptPage(all []session.DisplayEntry, args TranscriptPageArgs) Page { + total := len(all) + before := args.Before + if before <= 0 || before > total { + before = total + } + limit := args.Limit + if limit <= 0 { + limit = defaultTranscriptPageLimit + } else if limit > maxTranscriptPageLimit { + limit = maxTranscriptPageLimit + } + maxBytes := args.MaxBytes + if maxBytes <= 0 || maxBytes > maxTranscriptPageBytes { + maxBytes = maxTranscriptPageBytes + } + if total == 0 || before <= 0 { + return Page{Total: total} + } + + from := max(0, before-limit) + base := before - 1 + used := 0 + for i := before - 1; i >= from; i-- { + raw, err := json.Marshal(all[i]) + if err != nil { + break + } + if i == before-1 { + if len(raw) > maxBytes { + shortened := shortenDisplayEntry(all[i], maxBytes) + return Page{ + Entries: []session.DisplayEntry{shortened}, + Base: i, + Total: total, + More: i > 0, + } + } + used = len(raw) + base = i + continue + } + if used+1+len(raw) > maxBytes { + break + } + used += 1 + len(raw) + base = i + } + + entries := make([]session.DisplayEntry, before-base) + copy(entries, all[base:before]) + return Page{ + Entries: entries, + Base: base, + Total: total, + More: base > 0, + } +} + +// shortenDisplayEntry truncates the largest text field of entry and appends +// transcriptShortenedMarker so a single oversized entry still crosses within +// maxBytes without mutating the caller's transcript slice. +func shortenDisplayEntry(entry session.DisplayEntry, maxBytes int) session.DisplayEntry { + field := &entry.Text + if len(entry.Output) > len(*field) { + field = &entry.Output + } + if len(entry.Args) > len(*field) { + field = &entry.Args + } + if len(entry.Hint) > len(*field) { + field = &entry.Hint + } + orig := *field + *field = transcriptShortenedMarker + shell, err := json.Marshal(entry) + if err != nil { + *field = truncateUTF8(orig, max(0, maxBytes-len(transcriptShortenedMarker))) + transcriptShortenedMarker + return entry + } + budget := maxBytes - len(shell) + if budget <= 0 { + return entry + } + prefix := truncateUTF8(orig, budget) + *field = prefix + transcriptShortenedMarker + for len(prefix) > 0 { + raw, err := json.Marshal(entry) + if err != nil || len(raw) <= maxBytes { + break + } + excess := len(raw) - maxBytes + if excess >= len(prefix) { + prefix = "" + } else { + prefix = truncateUTF8(prefix, len(prefix)-excess) + } + *field = prefix + transcriptShortenedMarker + } + return entry +} + +// truncateUTF8 cuts s to at most maxBytes without splitting a multi-byte UTF-8 +// rune at the end, so JSON serialisation never expands a torn rune into a +// replacement escape sequence. +func truncateUTF8(s string, maxBytes int) string { + if maxBytes <= 0 { + return "" + } + if len(s) <= maxBytes { + return s + } + s = s[:maxBytes] + for i := len(s) - 1; i >= 0 && len(s)-i <= utf8.UTFMax; i-- { + if !utf8.RuneStart(s[i]) { + continue + } + if r, width := utf8.DecodeRuneInString(s[i:]); r == utf8.RuneError && width == 1 { + return s[:i] + } + return s + } + return s +} + // stream turns a submitted turn into a stream id. The id is answered // IMMEDIATELY, before a single event, because the surface has to be able to bind // events to the turn that caused them and because a result that waited for the @@ -3936,6 +4253,15 @@ func (s *server) sendLocked(frame Frame) error { } } + if s.remote != nil { + var keep bool + var err error + frame, keep, err = s.capGuestFrame(frame) + if err != nil || !keep { + return err + } + } + if frame.Kind != "welcome" { if err := compressFrame(&frame, s.encoding); err != nil { return err @@ -3949,6 +4275,9 @@ func (s *server) sendLocked(frame Frame) error { if s.dead { return io.ErrClosedPipe } + if s.remote != nil { + return s.writeGuestLocked(line) + } if _, err := s.out.Write(line); err != nil { s.dead = true s.dropClientTools() @@ -3961,6 +4290,139 @@ func (s *server) sendLocked(frame Frame) error { return err } +const ( + guestOversizeResultError = "too large for remote control; use the paged read" + guestOversizeEventText = "an update was too large to show here" +) + +// capGuestFrame enforces DefaultMaxLine on the uncompressed frame a remote +// viewer would decode. Oversized results become a refusal result on the same +// call ID, oversized events become a notice event on the same stream and +// sequence number so replay cursors stay contiguous, and any other frame kind +// is dropped and counted. +func (s *server) capGuestFrame(frame Frame) (Frame, bool, error) { + size, err := plainFrameLineLen(frame) + if err != nil { + return Frame{}, false, err + } + if size <= DefaultMaxLine { + return frame, true, nil + } + switch frame.Kind { + case "result": + return Frame{ + Kind: "result", + ID: frame.ID, + Error: guestOversizeResultError, + }, true, nil + case "event": + notice := WireEvent(session.Event{ + Kind: session.EventNotice, + Text: guestOversizeEventText, + }) + return Frame{ + Kind: "event", + ID: frame.ID, + Seq: frame.Seq, + Payload: mustJSON(notice), + }, true, nil + default: + s.droppedOversize.Add(1) + return Frame{}, false, nil + } +} + +type writeDeadliner interface { + SetWriteDeadline(time.Time) error +} + +// writeGuestLocked writes one frame line to a remote viewer connection under +// GuestWriteDeadline. When the underlying writer supports SetWriteDeadline it +// uses that deadline directly; otherwise a watchdog timer closes the connection +// if the write blocks past the deadline. On an overrun the guest connection is +// marked lagging, leaves the session like a normal hang-up, and is closed so a +// stalled viewer cannot block the holder. +func (s *server) writeGuestLocked(line []byte) error { + deadline := GuestWriteDeadline + if deadliner, ok := s.out.(writeDeadliner); ok && deadline > 0 { + if err := deadliner.SetWriteDeadline(time.Now().Add(deadline)); err != nil { + s.failGuestWrite(err, isWriteTimeout(err)) + return err + } + _, err := s.out.Write(line) + if err == nil { + err = flushFrame(s.out) + } + _ = deadliner.SetWriteDeadline(time.Time{}) + if err != nil { + s.failGuestWrite(err, isWriteTimeout(err)) + return err + } + return nil + } + + var timedOut atomic.Bool + var timer *time.Timer + if deadline > 0 { + timer = time.AfterFunc(deadline, func() { + timedOut.Store(true) + s.closeConn() + }) + } + _, err := s.out.Write(line) + if err == nil { + err = flushFrame(s.out) + } + if timer != nil { + timer.Stop() + } + overran := timedOut.Load() || isWriteTimeout(err) + if overran && err == nil { + err = os.ErrDeadlineExceeded + } + if err != nil { + if overran { + err = os.ErrDeadlineExceeded + } + s.failGuestWrite(err, overran) + return err + } + return nil +} + +func (s *server) failGuestWrite(_ error, overran bool) { + s.dead = true + s.dropClientTools() + if overran { + s.lagging.Store(true) + // THE CONNECTION IS CLOSED AND NOTHING ELSE IS DONE HERE. This runs with the + // write lock held, and leaving the room waits on goroutines that are blocked + // on that same lock, so leaving from here could wait on itself. Closing the + // connection ends the reader, and serve's own exit leaves the room on the + // ordinary hang-up road, once the lock is free. + s.closeConn() + } +} + +func (s *server) closeConn() { + if closer, ok := s.out.(io.Closer); ok { + _ = closer.Close() + } + if s.in != nil && any(s.in) != any(s.out) { + if closer, ok := s.in.(io.Closer); ok { + _ = closer.Close() + } + } +} + +func isWriteTimeout(err error) bool { + if errors.Is(err, os.ErrDeadlineExceeded) { + return true + } + var netErr interface{ Timeout() bool } + return errors.As(err, &netErr) && netErr.Timeout() +} + func (s *server) hungUp() bool { s.write.Lock() defer s.write.Unlock() @@ -4008,3 +4470,99 @@ func (sess *Session) takeCloseNotices() []string { sess.closeNotices = nil return lines } + +// deliverIdempotent ensures a remote viewer's send carrying a non-empty +// ClientID is applied at most once per (Remote.Device, ClientID), answering +// repeats from the per-Session table or the persisted transcript tail without +// delivering a second message to the engine. +func (s *server) deliverIdempotent(agent WrappedAgent, clientID string, deliver func() (json.RawMessage, error)) (json.RawMessage, error) { + if s.remote == nil || clientID == "" || s.session == nil { + return deliver() + } + sess := s.session + key := messageRepeatKey{device: s.remote.Device, clientID: clientID} + for { + sess.repeatMu.Lock() + if sess.repeats == nil { + sess.repeats = map[messageRepeatKey]*messageRepeatEntry{} + } + existing, found := sess.repeats[key] + if found { + sess.repeatMu.Unlock() + <-existing.done + if existing.ok { + return append(json.RawMessage(nil), existing.payload...), nil + } + continue + } + entry := &messageRepeatEntry{done: make(chan struct{})} + sess.repeats[key] = entry + sess.repeatMu.Unlock() + + var ( + out json.RawMessage + err error + ) + if sess.transcriptHasClientID(agent, clientID) { + out, err = json.Marshal(StreamRef{}) + } else { + out, err = deliver() + } + + sess.repeatMu.Lock() + if err != nil { + if sess.repeats[key] == entry { + delete(sess.repeats, key) + } + close(entry.done) + sess.repeatMu.Unlock() + return nil, err + } + entry.payload = append(json.RawMessage(nil), out...) + entry.ok = true + sess.repeatOrder = append(sess.repeatOrder, key) + for len(sess.repeatOrder) > messageRepeatCap { + oldest := sess.repeatOrder[0] + sess.repeatOrder = sess.repeatOrder[1:] + delete(sess.repeats, oldest) + } + if cap(sess.repeatOrder) >= 2*messageRepeatCap { + sess.repeatOrder = append(make([]messageRepeatKey, 0, messageRepeatCap), sess.repeatOrder...) + } + close(entry.done) + sess.repeatMu.Unlock() + return out, nil + } +} + +func (sess *Session) transcriptHasClientID(agent WrappedAgent, clientID string) bool { + if clientID == "" { + return false + } + if agent != nil { + entries := agent.Transcript() + if entriesHaveClientID(entries, clientID) { + return true + } + if len(entries) > 0 { + return false + } + } + if file := sess.File(); file != "" { + return entriesHaveClientID(session.ReadTranscript(file).Entries, clientID) + } + return false +} + +func entriesHaveClientID(entries []session.DisplayEntry, clientID string) bool { + start := 0 + if len(entries) > messageRepeatTailScan { + start = len(entries) - messageRepeatTailScan + } + for i := len(entries) - 1; i >= start; i-- { + if entries[i].Person != nil && entries[i].Person.ClientID == clientID { + return true + } + } + return false +} diff --git a/internal/remote/server_deadline_test.go b/internal/remote/server_deadline_test.go new file mode 100644 index 0000000000..a50996c8a5 --- /dev/null +++ b/internal/remote/server_deadline_test.go @@ -0,0 +1,341 @@ +package remote + +import ( + "bufio" + "encoding/json" + "io" + "net" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/session" +) + +type deadlineCountingConn struct { + net.Conn + deadlines atomic.Int64 +} + +func (c *deadlineCountingConn) SetWriteDeadline(t time.Time) error { + if !t.IsZero() { + c.deadlines.Add(1) + } + return c.Conn.SetWriteDeadline(t) +} + +// TestAFrozenRemoteConnectionNeverStallsTheHostsOwnWindow verifies V17: when a +// session has one local surface and one remote guest whose reader stops reading, +// broadcast turn events still reach the local surface within bounded real time, +// the frozen guest is marked lagging, closed, and removed from the room without +// cancelling the engine or turn, and a local connection takes the unchanged +// no-deadline write path. +func TestAFrozenRemoteConnectionNeverStallsTheHostsOwnWindow(t *testing.T) { + prev := GuestWriteDeadline + GuestWriteDeadline = 50 * time.Millisecond + t.Cleanup(func() { GuestWriteDeadline = prev }) + + agent := &fakeAgent{} + sess := heldSession(agent) + t.Cleanup(func() { _ = agent.Close() }) + + // Attach the host's own local window over a deadline-counting connection so + // the control assertion can verify that local writes arm no write deadline. + localSurfaceRaw, localEngineRaw := net.Pipe() + localEngineConn := &deadlineCountingConn{Conn: localEngineRaw} + localFrames := make(chan Frame, 64) + localServed := make(chan error, 1) + guard.Go("test/local-surface-serve", func() { + err := ServeAttach(localEngineConn, localEngineConn, AttachOptions{ + Open: func(Hello) (*Session, error) { return sess, nil }, + }) + _ = localEngineConn.Close() + localServed <- err + }) + guard.Go("test/local-surface-read", func() { + scan := bufio.NewScanner(localSurfaceRaw) + scan.Buffer(make([]byte, 0, 64*1024), frameCap) + for scan.Scan() { + var frame Frame + if err := json.Unmarshal(scan.Bytes(), &frame); err == nil { + localFrames <- frame + } + } + close(localFrames) + }) + t.Cleanup(func() { + _ = localSurfaceRaw.Close() + select { + case <-localServed: + case <-time.After(time.Second): + } + }) + + writeRawFrame := func(w io.Writer, frame Frame) { + t.Helper() + line, err := json.Marshal(frame) + if err != nil { + t.Fatalf("encode frame: %v", err) + } + if _, err := w.Write(append(line, '\n')); err != nil { + t.Fatalf("write frame: %v", err) + } + } + recvLocal := func(within time.Duration, match func(Frame) bool) Frame { + t.Helper() + timer := time.NewTimer(within) + defer timer.Stop() + for { + select { + case frame, ok := <-localFrames: + if !ok { + t.Fatal("local surface closed unexpectedly") + } + if match(frame) { + return frame + } + case <-timer.C: + t.Fatalf("local surface did not receive matching frame within %v", within) + return Frame{} + } + } + } + + writeRawFrame(localSurfaceRaw, Frame{ + Kind: "hello", + Payload: raw(t, Hello{Version: Version, Surface: "macbook"}), + }) + welcomeLocal := recvLocal(time.Second, func(f Frame) bool { return f.Kind == "welcome" }) + if welcomeLocal.Kind != "welcome" { + t.Fatalf("local welcome = %+v", welcomeLocal) + } + + // Attach a remote guest over a net.Pipe whose reader reads only the welcome + // and initial driver push, then never reads again. + guestSurfaceRaw, guestEngineRaw := net.Pipe() + guestEngineConn := &deadlineCountingConn{Conn: guestEngineRaw} + guestServed := make(chan error, 1) + guard.Go("test/frozen-guest-serve", func() { + err := ServeAttach(guestEngineConn, guestEngineConn, AttachOptions{ + Open: func(Hello) (*Session, error) { return sess, nil }, + }) + _ = guestEngineConn.Close() + guestServed <- err + }) + t.Cleanup(func() { _ = guestSurfaceRaw.Close() }) + + guestHello := Hello{ + Version: Version, + Surface: "phone", + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-frozen", + Label: "phone", + Watch: true, + Drive: false, + Road: "relay", + }, + } + guestFirstReadDone := make(chan Frame, 1) + guard.Go("test/frozen-guest-handshake-read", func() { + buf := make([]byte, 64*1024) + var line []byte + for { + n, err := guestSurfaceRaw.Read(buf) + if n > 0 { + line = append(line, buf[:n]...) + for i, b := range line { + if b == '\n' { + var frame Frame + _ = json.Unmarshal(line[:i], &frame) + guestFirstReadDone <- frame + return + } + } + } + if err != nil { + return + } + } + }) + writeRawFrame(guestSurfaceRaw, Frame{Kind: "hello", Payload: raw(t, guestHello)}) + select { + case frame := <-guestFirstReadDone: + if frame.Kind != "welcome" { + t.Fatalf("guest handshake answered %q: %s", frame.Kind, frame.Error) + } + case <-time.After(time.Second): + t.Fatal("guest did not receive welcome") + } + // Drain the local surface's driver notification from the guest's arrival. + recvLocal(time.Second, func(f Frame) bool { return f.Kind == "driver" }) + + if got := sess.Attached(); got != 2 { + t.Fatalf("attached surfaces before freeze = %d, want 2", got) + } + + // Start a turn on the local window and stream events while nobody reads from + // guestSurfaceRaw. The fan-out must drop the frozen guest within a few + // hundred milliseconds and deliver every event to the local surface. + started := time.Now() + writeRawFrame(localSurfaceRaw, Frame{ + Kind: "call", + ID: 1, + Method: MethodSubmit, + Payload: raw(t, SubmitArgs{Text: "keep streaming"}), + }) + submitResult := recvLocal(500*time.Millisecond, func(f Frame) bool { + return f.Kind == "result" && f.ID == 1 + }) + if submitResult.Error != "" { + t.Fatalf("Submit failed: %s", submitResult.Error) + } + ref := decode[StreamRef](t, submitResult.Payload) + + turnStream := agent.stream(0) + if turnStream == nil { + t.Fatal("Submit opened no turn stream on agent") + } + for _, token := range []string{"alpha", "beta", "gamma"} { + turnStream <- session.Event{Kind: session.EventTextDelta, Text: token} + } + + var received []string + for len(received) < 3 { + evFrame := recvLocal(500*time.Millisecond, func(f Frame) bool { + return f.Kind == "event" && f.ID == ref.Stream + }) + ev := decode[EventWire](t, evFrame.Payload).Unwire() + received = append(received, ev.Text) + } + if elapsed := time.Since(started); elapsed > 600*time.Millisecond { + t.Fatalf("fan-out with frozen guest took %v, want bounded within 600ms", elapsed) + } + if received[0] != "alpha" || received[1] != "beta" || received[2] != "gamma" { + t.Fatalf("local surface received %v, want [alpha beta gamma]", received) + } + + // The frozen guest has been closed and removed from the room. + if got := sess.Attached(); got != 1 { + t.Fatalf("attached surfaces after guest write deadline = %d, want 1 (only local)", got) + } + select { + case <-guestServed: + case <-time.After(500 * time.Millisecond): + t.Fatal("frozen guest server loop did not exit after deadline overrun") + } + var probe [1]byte + if _, err := guestSurfaceRaw.Read(probe[:]); err == nil { + t.Fatal("frozen guest connection remained readable after deadline overrun") + } + + // The engine and turn were not interrupted or closed when the guest left. + if agent.interrupts != 0 { + t.Fatalf("agent interrupts = %d, want 0", agent.interrupts) + } + if agent.closed() != 0 { + t.Fatalf("agent closes = %d, want 0", agent.closed()) + } + turnStream <- session.Event{Kind: session.EventTextDelta, Text: "delta"} + afterDrop := recvLocal(500*time.Millisecond, func(f Frame) bool { + return f.Kind == "event" && f.ID == ref.Stream + }) + if got := decode[EventWire](t, afterDrop.Payload).Unwire().Text; got != "delta" { + t.Fatalf("event after guest drop = %q, want delta", got) + } + agent.finish(turnStream) + recvLocal(500*time.Millisecond, func(f Frame) bool { + return f.Kind == "closed" && f.ID == ref.Stream + }) + + // Control: the remote guest armed write deadlines on its connection, whereas + // the local surface never armed a write deadline on any frame. + if got := guestEngineConn.deadlines.Load(); got == 0 { + t.Fatal("remote guest connection never armed SetWriteDeadline") + } + if got := localEngineConn.deadlines.Load(); got != 0 { + t.Fatalf("local surface connection armed SetWriteDeadline %d times, want 0", got) + } + + // Also verify the watchdog timer fallback for a guest writer that does not + // implement SetWriteDeadline (an io.Pipe pair whose reader stops reading). + pipeInR, pipeInW := io.Pipe() + pipeOutR, pipeOutW := io.Pipe() + pipeGuestServed := make(chan error, 1) + guard.Go("test/frozen-pipe-guest-serve", func() { + err := ServeAttach(pipeInR, pipeOutW, AttachOptions{ + Open: func(Hello) (*Session, error) { return sess, nil }, + }) + _ = pipeOutW.Close() + pipeGuestServed <- err + }) + t.Cleanup(func() { + _ = pipeInW.Close() + _ = pipeOutR.Close() + }) + pipeWelcomeCh := make(chan Frame, 1) + guard.Go("test/frozen-pipe-guest-welcome", func() { + buf := make([]byte, 64*1024) + var line []byte + for { + n, err := pipeOutR.Read(buf) + if n > 0 { + line = append(line, buf[:n]...) + for i, b := range line { + if b == '\n' { + var frame Frame + _ = json.Unmarshal(line[:i], &frame) + pipeWelcomeCh <- frame + return + } + } + } + if err != nil { + return + } + } + }) + writeRawFrame(pipeInW, Frame{Kind: "hello", Payload: raw(t, guestHello)}) + select { + case frame := <-pipeWelcomeCh: + if frame.Kind != "welcome" { + t.Fatalf("pipe guest handshake answered %q: %s", frame.Kind, frame.Error) + } + case <-time.After(time.Second): + t.Fatal("pipe guest did not receive welcome") + } + recvLocal(time.Second, func(f Frame) bool { return f.Kind == "driver" }) + if got := sess.Attached(); got != 2 { + t.Fatalf("attached surfaces with pipe guest = %d, want 2", got) + } + + writeRawFrame(localSurfaceRaw, Frame{ + Kind: "call", + ID: 2, + Method: MethodSubmit, + Payload: raw(t, SubmitArgs{Text: "stream with pipe guest frozen"}), + }) + submitResult2 := recvLocal(500*time.Millisecond, func(f Frame) bool { + return f.Kind == "result" && f.ID == 2 + }) + ref2 := decode[StreamRef](t, submitResult2.Payload) + turnStream2 := agent.stream(0) + turnStream2 <- session.Event{Kind: session.EventTextDelta, Text: "watchdog-ok"} + evFrame2 := recvLocal(500*time.Millisecond, func(f Frame) bool { + return f.Kind == "event" && f.ID == ref2.Stream + }) + if got := decode[EventWire](t, evFrame2.Payload).Unwire().Text; got != "watchdog-ok" { + t.Fatalf("local event with frozen pipe guest = %q, want watchdog-ok", got) + } + agent.finish(turnStream2) + if got := sess.Attached(); got != 1 { + t.Fatalf("attached surfaces after pipe guest watchdog = %d, want 1", got) + } + select { + case <-pipeGuestServed: + case <-time.After(500 * time.Millisecond): + t.Fatal("frozen pipe guest server loop did not exit after watchdog deadline") + } +} diff --git a/internal/remote/transcriptpage_test.go b/internal/remote/transcriptpage_test.go new file mode 100644 index 0000000000..d155be2932 --- /dev/null +++ b/internal/remote/transcriptpage_test.go @@ -0,0 +1,371 @@ +package remote + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/session" +) + +// dialClientOnSession connects a live Client to sess with the given Hello so +// tests can exercise the real wire framing and client decoder end to end. +func dialClientOnSession(t *testing.T, sess *Session, hello Hello) *Client { + t.Helper() + surface, engineConn := Pipe() + guard.Go("test/transcript-page-server", func() { + _ = ServeAttach(engineConn, engineConn, AttachOptions{ + Open: func(Hello) (*Session, error) { return sess, nil }, + }) + _ = engineConn.Close() + }) + client, err := Dial(surface, "devbox", hello) + if err != nil { + t.Fatalf("Dial: %v", err) + } + t.Cleanup(func() { _ = client.Close() }) + return client +} + +// TestATranscriptPageReturnsOlderEntriesFromAnIndexInPages verifies V4: a +// 250-entry transcript serves the 40-entry tail on Before<=0, walks backward +// in 40-entry pages by absolute index until More is false so the union equals +// the whole-transcript read, caps oversized limits at 200, and serves the +// remaining prefix when Before is smaller than Limit. +func TestATranscriptPageReturnsOlderEntriesFromAnIndexInPages(t *testing.T) { + const total = 250 + entries := make([]session.DisplayEntry, total) + for i := range entries { + role := "user" + if i%2 == 1 { + role = "assistant" + } + entries[i] = session.DisplayEntry{ + Role: role, + Text: fmt.Sprintf("entry-%03d", i), + } + } + + fake := &fakeAgent{transcript: entries} + sess := heldSession(fake) + t.Cleanup(func() { _ = fake.Close() }) + + client := dialClientOnSession(t, sess, Hello{Surface: "macbook"}) + agent := client.Agent() + ctx := context.Background() + + // Tail call with Before: 0 and Limit: 0 uses the 40-entry default from the end. + tail, err := agent.TranscriptPage(ctx, 0, 0) + if err != nil { + t.Fatalf("tail TranscriptPage: %v", err) + } + if tail.Base != 210 || tail.Total != 250 || !tail.More || len(tail.Entries) != 40 { + t.Fatalf("tail page = {Base:%d Total:%d More:%v len:%d}, want {Base:210 Total:250 More:true len:40}", + tail.Base, tail.Total, tail.More, len(tail.Entries)) + } + for i, got := range tail.Entries { + if want := entries[210+i]; got.Role != want.Role || got.Text != want.Text { + t.Fatalf("tail.Entries[%d] = %+v, want %+v", i, got, want) + } + } + + // Next older page from Before: 210 with Limit: 40 returns entries 170..209. + prev, err := agent.TranscriptPage(ctx, 210, 40) + if err != nil { + t.Fatalf("TranscriptPage(210, 40): %v", err) + } + if prev.Base != 170 || prev.Total != 250 || !prev.More || len(prev.Entries) != 40 { + t.Fatalf("page(210, 40) = {Base:%d Total:%d More:%v len:%d}, want {Base:170 Total:250 More:true len:40}", + prev.Base, prev.Total, prev.More, len(prev.Entries)) + } + for i, got := range prev.Entries { + if want := entries[170+i]; got.Role != want.Role || got.Text != want.Text { + t.Fatalf("prev.Entries[%d] = %+v, want %+v", i, got, want) + } + } + + // Walking back from the tail until More is false visits every entry once in order + // and matches the whole-transcript read. + var collected []session.DisplayEntry + before := 0 + for steps := 0; ; steps++ { + if steps > 20 { + t.Fatal("paging backward did not terminate") + } + page, err := agent.TranscriptPage(ctx, before, 40) + if err != nil { + t.Fatalf("walk step %d (before=%d): %v", steps, before, err) + } + collected = append(append([]session.DisplayEntry(nil), page.Entries...), collected...) + if !page.More { + if page.Base != 0 { + t.Fatalf("final page has More=false but Base=%d", page.Base) + } + break + } + if page.Base <= 0 || (before > 0 && page.Base >= before) { + t.Fatalf("page Base=%d did not move backward from before=%d", page.Base, before) + } + before = page.Base + } + whole := agent.Transcript() + if len(collected) != len(whole) { + t.Fatalf("collected %d entries across pages, whole transcript has %d", len(collected), len(whole)) + } + for i := range whole { + if collected[i].Role != whole[i].Role || collected[i].Text != whole[i].Text { + t.Fatalf("entry %d mismatch: paged=%+v whole=%+v", i, collected[i], whole[i]) + } + } + + // Limit: 1000 is capped at 200. + capped, err := agent.TranscriptPage(ctx, 250, 1000) + if err != nil { + t.Fatalf("TranscriptPage(250, 1000): %v", err) + } + if len(capped.Entries) != 200 || capped.Base != 50 || capped.Total != 250 || !capped.More { + t.Fatalf("capped page = {Base:%d Total:%d More:%v len:%d}, want {Base:50 Total:250 More:true len:200}", + capped.Base, capped.Total, capped.More, len(capped.Entries)) + } + + // Before > Total is also treated as the tail. + overBefore, err := agent.TranscriptPage(ctx, 999, 40) + if err != nil { + t.Fatalf("TranscriptPage(999, 40): %v", err) + } + if overBefore.Base != 210 || len(overBefore.Entries) != 40 || !overBefore.More { + t.Fatalf("page(999, 40) = {Base:%d More:%v len:%d}, want tail {Base:210 More:true len:40}", + overBefore.Base, overBefore.More, len(overBefore.Entries)) + } + + // Before: 5, Limit: 40 returns entries 0..4 with Base: 0 and More: false. + head, err := agent.TranscriptPage(ctx, 5, 40) + if err != nil { + t.Fatalf("TranscriptPage(5, 40): %v", err) + } + if head.Base != 0 || head.Total != 250 || head.More || len(head.Entries) != 5 { + t.Fatalf("head page = {Base:%d Total:%d More:%v len:%d}, want {Base:0 Total:250 More:false len:5}", + head.Base, head.Total, head.More, len(head.Entries)) + } + for i, got := range head.Entries { + if want := entries[i]; got.Role != want.Role || got.Text != want.Text { + t.Fatalf("head.Entries[%d] = %+v, want %+v", i, got, want) + } + } +} + +// TestATranscriptPageNeverExceedsItsByteBound verifies V4: a page of 10 KiB +// entries is cut from the newest end to fit the 192 KiB default ceiling while +// subsequent calls deliver the older entries, and a single 1 MiB entry comes +// back truncated with the remote-control marker within the byte ceiling. +func TestATranscriptPageNeverExceedsItsByteBound(t *testing.T) { + ctx := context.Background() + + t.Run("100 entries of 10 KiB each arrive in byte-bounded pages from the newest end", func(t *testing.T) { + const count = 100 + const entryTextBytes = 10 << 10 + entries := make([]session.DisplayEntry, count) + for i := range entries { + prefix := fmt.Sprintf("entry-%03d:", i) + entries[i] = session.DisplayEntry{ + Role: "assistant", + Text: prefix + strings.Repeat("x", entryTextBytes-len(prefix)), + } + } + + fake := &fakeAgent{transcript: entries} + sess := heldSession(fake) + t.Cleanup(func() { _ = fake.Close() }) + + client := dialClientOnSession(t, sess, Hello{ + Surface: "tablet", + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-tablet", + Label: "tablet", + Watch: true, + Road: "relay", + }, + }) + agent := client.Agent() + + first, err := agent.TranscriptPage(ctx, 0, count) + if err != nil { + t.Fatalf("first TranscriptPage: %v", err) + } + if len(first.Entries) >= count || len(first.Entries) < 15 || len(first.Entries) > 20 { + t.Fatalf("first page returned %d entries, want about 19 (fewer than %d)", len(first.Entries), count) + } + if first.Base != count-len(first.Entries) || first.Total != count || !first.More { + t.Fatalf("first page = {Base:%d Total:%d More:%v}, want {Base:%d Total:%d More:true}", + first.Base, first.Total, first.More, count-len(first.Entries), count) + } + rawFirst, err := json.Marshal(first) + if err != nil { + t.Fatal(err) + } + if len(rawFirst) > maxTranscriptPageBytes+256 { + t.Fatalf("first page marshaled to %d bytes, exceeding 192 KiB ceiling", len(rawFirst)) + } + + // Walk the remaining older pages and confirm all 100 entries arrive in order. + collected := append([]session.DisplayEntry(nil), first.Entries...) + before := first.Base + for steps := 0; before > 0; steps++ { + if steps > 20 { + t.Fatal("byte-bounded paging did not terminate") + } + page, err := agent.TranscriptPage(ctx, before, count) + if err != nil { + t.Fatalf("TranscriptPage(before=%d): %v", before, err) + } + rawPage, err := json.Marshal(page) + if err != nil { + t.Fatal(err) + } + if len(rawPage) > maxTranscriptPageBytes+256 { + t.Fatalf("page(before=%d) marshaled to %d bytes, exceeding 192 KiB ceiling", before, len(rawPage)) + } + if page.Base+len(page.Entries) != before { + t.Fatalf("page Base=%d + len=%d != before=%d", page.Base, len(page.Entries), before) + } + collected = append(append([]session.DisplayEntry(nil), page.Entries...), collected...) + before = page.Base + if !page.More && before != 0 { + t.Fatalf("page reported More=false at Base=%d", before) + } + } + if len(collected) != count { + t.Fatalf("collected %d entries across byte-bounded pages, want %d", len(collected), count) + } + for i := range entries { + if collected[i].Text != entries[i].Text { + t.Fatalf("entry %d text mismatch after byte-bounded walk", i) + } + } + }) + + t.Run("one entry of 1 MiB comes back truncated with the marker within 192 KiB", func(t *testing.T) { + const oneMiB = 1 << 20 + originalText := strings.Repeat("m", oneMiB) + fake := &fakeAgent{ + transcript: []session.DisplayEntry{ + {Role: "assistant", Text: originalText}, + }, + } + sess := heldSession(fake) + t.Cleanup(func() { _ = fake.Close() }) + + client := dialClientOnSession(t, sess, Hello{ + Surface: "phone", + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-phone", + Label: "phone", + Watch: true, + Road: "relay", + }, + }) + + page, err := client.Agent().TranscriptPage(ctx, 0, 40) + if err != nil { + t.Fatalf("TranscriptPage on 1 MiB entry: %v", err) + } + if len(page.Entries) != 1 || page.Base != 0 || page.Total != 1 || page.More { + t.Fatalf("page = {Base:%d Total:%d More:%v len:%d}, want single entry at Base 0", + page.Base, page.Total, page.More, len(page.Entries)) + } + gotText := page.Entries[0].Text + if !strings.HasSuffix(gotText, transcriptShortenedMarker) { + t.Fatalf("truncated text does not end with %q", transcriptShortenedMarker) + } + rawPage, err := json.Marshal(page) + if err != nil { + t.Fatal(err) + } + const smallAllowance = 256 + if len(rawPage) > maxTranscriptPageBytes+smallAllowance { + t.Fatalf("marshaled page length = %d, want <= %d", len(rawPage), maxTranscriptPageBytes+smallAllowance) + } + // The read must not have mutated the underlying transcript entry on the host. + if gotOrig := fake.Transcript()[0].Text; len(gotOrig) != oneMiB { + t.Fatalf("host transcript entry length mutated to %d, want %d", len(gotOrig), oneMiB) + } + }) +} + +// TestATranscriptPageIsOpenToAGuestWhileWholeTranscriptIsRefused verifies V4: +// a remote guest connection can read the transcript through Transcript.Page +// while its whole-transcript MethodTranscript call is refused with the guest +// refusal sentence, and a local surface's whole-transcript read is unchanged. +func TestATranscriptPageIsOpenToAGuestWhileWholeTranscriptIsRefused(t *testing.T) { + entries := []session.DisplayEntry{ + {Role: "user", Text: "first question"}, + {Role: "assistant", Text: "first answer"}, + } + fake := &fakeAgent{transcript: entries} + sess := heldSession(fake) + t.Cleanup(func() { _ = fake.Close() }) + + guest := dialSession(t, sess) + welcome := guest.hello(Hello{ + Version: Version, + Surface: "guest-laptop", + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-guest", + Label: "guest-laptop", + Watch: true, + Drive: true, + Road: "relay", + }, + }) + if welcome.Kind != "welcome" { + t.Fatalf("guest handshake answered %q: %s", welcome.Kind, welcome.Error) + } + + pageFrame := guest.ok(1, MethodTranscriptPage, TranscriptPageArgs{Before: 0, Limit: 40}) + page := decode[Page](t, pageFrame.Payload) + if len(page.Entries) != 2 || page.Base != 0 || page.Total != 2 || page.More { + t.Fatalf("guest Transcript.Page = %+v", page) + } + + wholeFrame := guest.call(2, MethodTranscript, nil) + wantRefusal := chatlist.LiveNotAllowedHere(HostName()) + if wholeFrame.Error != wantRefusal { + t.Fatalf("guest MethodTranscript error = %q, want %q", wholeFrame.Error, wantRefusal) + } + + local := dialSession(t, sess) + if frame := local.hello(Hello{Version: Version, Surface: "macbook"}); frame.Kind != "welcome" { + t.Fatalf("local handshake answered %q: %s", frame.Kind, frame.Error) + } + localWhole := decode[[]session.DisplayEntry](t, local.ok(1, MethodTranscript, nil).Payload) + if len(localWhole) != 2 || localWhole[0].Text != "first question" || localWhole[1].Text != "first answer" { + t.Fatalf("local MethodTranscript = %+v, want %+v", localWhole, entries) + } +} + +// TestATranscriptPageAgainstAnOldHostReturnsNoSuchMethod verifies V4: calling +// TranscriptPage against an older engine that answers "no such method" returns +// that error unchanged so the caller can fall back. +func TestATranscriptPageAgainstAnOldHostReturnsNoSuchMethod(t *testing.T) { + client, eng := newEngine(t) + wantErr := fmt.Sprintf("engine: no such method %q", MethodTranscriptPage) + eng.fails[MethodTranscriptPage] = wantErr + + _, err := client.Agent().TranscriptPage(context.Background(), 0, 40) + if err == nil { + t.Fatal("TranscriptPage against old host succeeded, want error") + } + if err.Error() != wantErr { + t.Fatalf("TranscriptPage error = %q, want %q", err.Error(), wantErr) + } +} diff --git a/internal/remote/wire.go b/internal/remote/wire.go index 8e19995f9a..0d82ad583d 100644 --- a/internal/remote/wire.go +++ b/internal/remote/wire.go @@ -398,6 +398,17 @@ import ( // Like the other welcome capabilities, absence preserves the existing wire. const Version = 22 +// DefaultMaxLine is the largest serialised frame line, after decompression, that +// a remote viewer connection may send or accept. Keeping every line within a +// fixed ceiling prevents a single oversized tool output or update from pinning a +// guest link or exhausting viewer memory. +const DefaultMaxLine = 256 << 10 + +// GuestWriteDeadline is the longest a remote viewer connection may take to +// accept one outbound frame before the holder drops it as lagging. It is a +// variable so tests can exercise a stalled viewer without waiting two seconds. +var GuestWriteDeadline = 2 * time.Second + // AND THE NEWS FRAMES RIDE THAT SAME NUMBER, for the reason the places methods // rode version 5's: neither half can be surprised by them. "phase" and "lane" // are pushes the surface never asks for, and a version-13 surface that does not @@ -419,7 +430,7 @@ const Version = 22 // Frame is one line on the wire, either direction. type Frame struct { // Kind says what this frame is: "hello", "welcome", "call", "result", - // "event", "closed", "facts", "task", "design", "question", "phase", "lane", + // "event", "gap", "closed", "facts", "task", "design", "question", "phase", "lane", // "turn", "driver", "moved", "fatal", "sideAskDelta", "clientToolCall", // "clientToolEnded". The two client-tool kinds answer nothing. // @@ -614,18 +625,19 @@ const ( // project it was in. `/autonomy` printed that sentence on a machine with the // rules sitting in `.codeaf/autonomy.json`, and the settings rows that read // the same door drew nothing at all. - MethodAutonomy = "Autonomy" // nothing → map[AskKind]Policy - MethodHarness = "ResolveHarness" // HarnessArgs → nothing - MethodConnect = "ResolveConnect" // ConnectArgs → nothing - MethodConnectKey = "ResolveConnectKey" // ConnectArgs → nothing - MethodNoteConnected = "NoteConnected" // ConnectedArgs → nothing - MethodTitle = "Title" // nothing → string - MethodUsage = "Usage" // nothing → session.Usage - MethodContextTokens = "ContextTokens" // nothing → int - MethodTranscript = "Transcript" // nothing → []session.DisplayEntry - MethodEarlier = "EarlierHistory" // nothing → session.EarlierHistory - MethodRewindPoints = "RewindPoints" // nothing → []session.RewindPoint - MethodRewindAt = "RewindAt" // int → []session.DisplayEntry + MethodAutonomy = "Autonomy" // nothing → map[AskKind]Policy + MethodHarness = "ResolveHarness" // HarnessArgs → nothing + MethodConnect = "ResolveConnect" // ConnectArgs → nothing + MethodConnectKey = "ResolveConnectKey" // ConnectArgs → nothing + MethodNoteConnected = "NoteConnected" // ConnectedArgs → nothing + MethodTitle = "Title" // nothing → string + MethodUsage = "Usage" // nothing → session.Usage + MethodContextTokens = "ContextTokens" // nothing → int + MethodTranscript = "Transcript" // nothing → []session.DisplayEntry + MethodTranscriptPage = "Transcript.Page" // TranscriptPageArgs → Page + MethodEarlier = "EarlierHistory" // nothing → session.EarlierHistory + MethodRewindPoints = "RewindPoints" // nothing → []session.RewindPoint + MethodRewindAt = "RewindAt" // int → []session.DisplayEntry // MethodPlanSpend CARRIES THE RUN'S SPEND-BY-SEAT ACROSS THE WIRE, and it // is the spend page's other reading beside the machine's own ledger above. // A conversation that seeded a plan writes its workers' calls into the plan @@ -1106,6 +1118,21 @@ type Hello struct { // retired while the window is open (cmd/codeaf's chatv3_beside.go). A // headless `--once` is a script and not a window, and says nothing. Window bool `json:"window,omitempty"` + + // Remote carries the peer identity and permissions stamped by the door that + // accepted the connection, never trusted from a surface directly. + Remote *RemoteViewer `json:"remote,omitempty"` +} + +// RemoteViewer describes a paired remote computer viewing or driving a chat held +// on this host. It is stamped by the door that carried the connection and is +// never trusted from a surface. +type RemoteViewer struct { + Device string `json:"device,omitempty"` + Label string `json:"label,omitempty"` + Watch bool `json:"watch,omitempty"` + Drive bool `json:"drive,omitempty"` + Road string `json:"road,omitempty"` } // StreamCursor is one "I have seen this stream through here". @@ -1114,6 +1141,16 @@ type StreamCursor struct { Seq uint64 `json:"seq"` } +// Gap reports that a running stream's replay ring evicted events older than +// First before a surface resuming from Have reattached. It rides a "gap" frame +// ahead of the retained events so a surface that knows the kind can re-read the +// transcript tail while an older reader ignores the unknown frame kind. +type Gap struct { + Stream uint64 `json:"stream"` + Have uint64 `json:"have"` + First uint64 `json:"first"` +} + // Welcome is the server's answer ("welcome"): the facts a surface needs before // its first frame, which are the same facts newApp reads off a local agent. type Welcome struct { @@ -1308,6 +1345,22 @@ type Welcome struct { // asking twice, which is the degradation that costs a keystroke rather than // the one that corrects a worker twice. SteerRepeat bool `json:"steerRepeat,omitempty"` + + // MessageRepeat says this holder RECOGNISES A REMOTE SEND IT HAS ALREADY + // TAKEN: a Submit, FollowUp or Steer arriving again under the same + // `(Remote.Device, SubmitArgs.ClientID)` answers the original [StreamRef] + // (or an empty [StreamRef] after a holder restart when the id is already in + // the persisted transcript tail) and delivers nothing to the engine. + // + // IT IS CARRIED FOR [Welcome.SteerRepeat]'S REASON: a roaming client holding + // an unanswered send after a dropped link must know, before it resends on + // the new pipe, whether repeating the call could deliver the person's words + // twice. + // + // ABSENCE IS false AND false IS THE SAFE READING: an older holder ignores + // the identity for deduplication, so the client fails the in-flight send + // rather than asking a second time. + MessageRepeat bool `json:"messageRepeat,omitempty"` // QueuedMarks says this engine keeps a Submit's queued mark // ([SubmitArgs.Queued]) on the message's line. ABSENCE IS AN ENGINE THAT // WOULD DROP IT: the surface then sends the words without the mark and @@ -1547,6 +1600,10 @@ type Welcome struct { // then says it has no machine to set up rather than showing a plan nobody // can act on. Setup bool `json:"setup,omitempty"` + + // Remote echoes the peer identity and permissions stamped on Hello.Remote by + // the door that carried this connection. Absent on local connections. + Remote *RemoteViewer `json:"remote,omitempty"` } // SkillShelfArgs asks for one reading of the conversation's skill shelf, on @@ -1645,7 +1702,10 @@ type SubmitArgs struct { Annotation *session.Annotation `json:"annotation,omitempty"` Queued bool `json:"queued,omitempty"` // ClientID is the door's opaque name for the message - // ([session.Submission.ClientID]); correlation only, never idempotency. + // ([session.Submission.ClientID]). On a remote viewer connection + // ([Hello.Remote]) the holder deduplicates sends by `(Remote.Device, + // ClientID)` so a resent message after a dropped link is never applied + // twice. ClientID string `json:"clientId,omitempty"` // From names who sent the message on the person's behalf // ([session.Submission.From]). @@ -2273,3 +2333,37 @@ type PlanRunSummaryResult struct { Summary session.RunPlanSummary `json:"summary"` OK bool `json:"ok"` } + +// TranscriptPageArgs asks for one bounded page of the conversation's transcript +// ending before the absolute entry index Before (zero for the tail). +type TranscriptPageArgs struct { + Before int `json:"before,omitempty"` + Limit int `json:"limit,omitempty"` + MaxBytes int `json:"maxBytes,omitempty"` +} + +// Page is one slice of the transcript returned by [MethodTranscriptPage], with +// the absolute index of its first entry, the transcript's total entry count, +// and whether older entries remain before Base. +type Page struct { + Entries []session.DisplayEntry `json:"entries,omitempty"` + Base int `json:"base,omitempty"` + Total int `json:"total,omitempty"` + More bool `json:"more,omitempty"` +} + +const ( + // defaultTranscriptPageLimit is the entry count [MethodTranscriptPage] serves + // when the caller leaves [TranscriptPageArgs.Limit] unset, matching the two + // screens of scrollback the surface draws per helping. + defaultTranscriptPageLimit = 40 + // maxTranscriptPageLimit caps the number of entries a single transcript page + // may return so one read never materialises an unbounded batch over a live link. + maxTranscriptPageLimit = 200 + // maxTranscriptPageBytes caps the byte weight of a single transcript page so + // its result frame stays comfortably below [DefaultMaxLine]. + maxTranscriptPageBytes = 192 << 10 + // transcriptShortenedMarker is appended to the text of a single transcript + // entry that had to be shortened to fit [maxTranscriptPageBytes]. + transcriptShortenedMarker = " … [shortened for remote control]" +) diff --git a/internal/remote/wire_cap_test.go b/internal/remote/wire_cap_test.go new file mode 100644 index 0000000000..7a7738a7e2 --- /dev/null +++ b/internal/remote/wire_cap_test.go @@ -0,0 +1,359 @@ +package remote + +import ( + "bufio" + "encoding/json" + "net" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/session" +) + +// TestAnOutboundLineOverTheCapIsRefusedAndTheReaderIsBounded verifies V18: +// (a) a result frame of DefaultMaxLine+1 bytes to a remote guest arrives as the +// error result with the same call ID while one of exactly DefaultMaxLine bytes +// arrives intact; (b) an oversized event arrives at a remote guest as a notice +// event carrying the same stream ID and sequence number, the next event's +// sequence number is contiguous, and a local surface receives the original +// oversized event; (c) a Client built with MaxLine fails on a line longer than +// the cap with the "too large to read" error while working for lines at the +// cap, and a Client built without MaxLine reads a 1 MiB line as before. +func TestAnOutboundLineOverTheCapIsRefusedAndTheReaderIsBounded(t *testing.T) { + t.Run("outbound result cap at DefaultMaxLine and DefaultMaxLine+1", func(t *testing.T) { + agent := &fakeAgent{} + sess := heldSession(agent) + t.Cleanup(func() { _ = agent.Close() }) + + guest := dialSession(t, sess) + welcome := guest.hello(Hello{ + Version: Version, + Surface: "laptop", + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-guest", + Label: "laptop", + Watch: true, + Drive: true, + Road: "relay", + }, + }) + if welcome.Kind != "welcome" { + t.Fatalf("guest handshake answered %q: %s", welcome.Kind, welcome.Error) + } + + // Compute the exact title length that produces a serialised result frame + // of DefaultMaxLine bytes for call ID 1. + baseAtCap, err := plainFrameLineLen(Frame{Kind: "result", ID: 1, Payload: raw(t, "")}) + if err != nil { + t.Fatal(err) + } + exactTitle := strings.Repeat("a", DefaultMaxLine-baseAtCap) + agent.SetModel(exactTitle) + atCap := guest.call(1, MethodModel, nil) + if atCap.Error != "" { + t.Fatalf("result frame at exact DefaultMaxLine (%d bytes) was refused: %s", DefaultMaxLine, atCap.Error) + } + if got := decode[string](t, atCap.Payload); got != exactTitle { + t.Fatalf("result at cap payload length = %d, want %d", len(got), len(exactTitle)) + } + + // Now make a result frame of DefaultMaxLine+1 bytes for call ID 2. + baseOverCap, err := plainFrameLineLen(Frame{Kind: "result", ID: 2, Payload: raw(t, "")}) + if err != nil { + t.Fatal(err) + } + overTitle := strings.Repeat("b", DefaultMaxLine+1-baseOverCap) + agent.SetModel(overTitle) + overCap := guest.call(2, MethodModel, nil) + const wantErr = "too large for remote control; use the paged read" + if overCap.ID != 2 || overCap.Error != wantErr { + t.Fatalf("oversized result (DefaultMaxLine+1) = {ID:%d Error:%q}, want {ID:2 Error:%q}", overCap.ID, overCap.Error, wantErr) + } + if len(overCap.Payload) != 0 { + t.Fatalf("oversized result still carried payload of %d bytes", len(overCap.Payload)) + } + + // Verify the same cap holds when gzip encoding is negotiated so a highly + // compressible payload whose inflated line is DefaultMaxLine+1 bytes is + // still refused while DefaultMaxLine bytes after inflate arrives intact. + agent.SetModel("") + gzipGuest := dialSession(t, sess) + gzipWelcome := gzipGuest.hello(Hello{ + Version: Version, + Surface: "gzip-laptop", + Session: sess.engine.SessionFile, + Join: true, + Encodings: []string{frameEncodingGzip}, + Remote: &RemoteViewer{ + Device: "dev-gzip", + Label: "gzip-laptop", + Watch: true, + Drive: true, + Road: "relay", + }, + }) + if gzipWelcome.Kind != "welcome" { + t.Fatalf("gzip guest handshake: %s", gzipWelcome.Error) + } + agent.SetModel(exactTitle) + gzipAtCap := gzipGuest.call(1, MethodModel, nil) + if gzipAtCap.Error != "" { + t.Fatalf("gzip guest result at DefaultMaxLine refused: %s", gzipAtCap.Error) + } + if err := expandFrame(&gzipAtCap); err != nil { + t.Fatal(err) + } + if got := decode[string](t, gzipAtCap.Payload); got != exactTitle { + t.Fatalf("gzip guest result at cap len = %d, want %d", len(got), len(exactTitle)) + } + agent.SetModel(overTitle) + gzipOverCap := gzipGuest.call(2, MethodModel, nil) + if gzipOverCap.ID != 2 || gzipOverCap.Error != wantErr { + t.Fatalf("gzip guest oversized result = {ID:%d Error:%q}, want {ID:2 Error:%q}", gzipOverCap.ID, gzipOverCap.Error, wantErr) + } + + // Any other oversized frame kind is dropped and counted without tearing + // the connection. + var sink strings.Builder + srv := &server{ + out: &sink, + remote: &RemoteViewer{Device: "dev-count", Label: "guest", Watch: true}, + } + if err := srv.send(Frame{Kind: "facts", Payload: raw(t, strings.Repeat("f", DefaultMaxLine))}); err != nil { + t.Fatalf("dropping oversized non-result non-event frame returned error: %v", err) + } + if got := srv.droppedOversize.Load(); got != 1 { + t.Fatalf("droppedOversize = %d, want 1", got) + } + if sink.Len() != 0 { + t.Fatalf("dropped oversized frame wrote %d bytes", sink.Len()) + } + }) + + t.Run("oversized event becomes notice with same stream and seq for guest while local gets original", func(t *testing.T) { + agent := &fakeAgent{} + sess := heldSession(agent) + t.Cleanup(func() { _ = agent.Close() }) + + local := dialSession(t, sess) + if frame := local.hello(Hello{Version: Version, Surface: "macbook"}); frame.Kind != "welcome" { + t.Fatalf("local handshake: %s", frame.Error) + } + + guest := dialSession(t, sess) + if frame := guest.hello(Hello{ + Version: Version, + Surface: "tablet", + Session: sess.engine.SessionFile, + Join: true, + Remote: &RemoteViewer{ + Device: "dev-tablet", + Label: "tablet", + Watch: true, + Drive: false, + Road: "relay", + }, + }); frame.Kind != "welcome" { + t.Fatalf("guest handshake: %s", frame.Error) + } + + ref := decode[StreamRef](t, local.ok(1, MethodSubmit, SubmitArgs{Text: "produce large output"}).Payload) + stream := agent.stream(0) + if stream == nil { + t.Fatal("Submit opened no stream") + } + + hugeText := strings.Repeat("x", DefaultMaxLine) + stream <- session.Event{Kind: session.EventTextDelta, Text: "first"} + stream <- session.Event{Kind: session.EventTextDelta, Text: hugeText} + stream <- session.Event{Kind: session.EventTextDelta, Text: "third"} + agent.finish(stream) + + // Guest sees seq 1 ("first"), seq 2 (notice replacement on the same + // stream and seq), and seq 3 ("third", contiguous). + guestEv1 := guest.await(func(f Frame) bool { return f.Kind == "event" && f.ID == ref.Stream && f.Seq == 1 }) + if got := decode[EventWire](t, guestEv1.Payload).Unwire(); got.Kind != session.EventTextDelta || got.Text != "first" { + t.Fatalf("guest seq 1 = %+v", got) + } + guestEv2 := guest.await(func(f Frame) bool { return f.Kind == "event" && f.ID == ref.Stream && f.Seq == 2 }) + gotNotice := decode[EventWire](t, guestEv2.Payload).Unwire() + if gotNotice.Kind != session.EventNotice || gotNotice.Text != "an update was too large to show here" { + t.Fatalf("guest seq 2 = {Kind:%v Text:%q}, want notice %q", gotNotice.Kind, gotNotice.Text, "an update was too large to show here") + } + guestEv3 := guest.await(func(f Frame) bool { return f.Kind == "event" && f.ID == ref.Stream && f.Seq == 3 }) + if got := decode[EventWire](t, guestEv3.Payload).Unwire(); got.Kind != session.EventTextDelta || got.Text != "third" { + t.Fatalf("guest seq 3 = %+v", got) + } + + // Local surface sees the original huge event untouched at seq 2. + localEv1 := local.await(func(f Frame) bool { return f.Kind == "event" && f.ID == ref.Stream && f.Seq == 1 }) + if got := decode[EventWire](t, localEv1.Payload).Unwire(); got.Text != "first" { + t.Fatalf("local seq 1 = %+v", got) + } + localEv2 := local.await(func(f Frame) bool { return f.Kind == "event" && f.ID == ref.Stream && f.Seq == 2 }) + if got := decode[EventWire](t, localEv2.Payload).Unwire(); got.Kind != session.EventTextDelta || got.Text != hugeText { + t.Fatalf("local seq 2 kind=%v len=%d, want textDelta len=%d", got.Kind, len(got.Text), len(hugeText)) + } + localEv3 := local.await(func(f Frame) bool { return f.Kind == "event" && f.ID == ref.Stream && f.Seq == 3 }) + if got := decode[EventWire](t, localEv3.Payload).Unwire(); got.Text != "third" { + t.Fatalf("local seq 3 = %+v", got) + } + }) + + t.Run("bounded client reader enforces MaxLine while default reader accepts 1 MiB", func(t *testing.T) { + runScriptedHost := func(t *testing.T, replySizes []int) net.Conn { + t.Helper() + ours, theirs := net.Pipe() + t.Cleanup(func() { + _ = ours.Close() + _ = theirs.Close() + }) + guard.Go("test/scripted-maxline-host", func() { + scan := bufio.NewScanner(theirs) + scan.Buffer(make([]byte, 0, 64*1024), frameCap) + callIndex := 0 + for scan.Scan() { + var frame Frame + if err := json.Unmarshal(scan.Bytes(), &frame); err != nil { + return + } + switch frame.Kind { + case "hello": + welcome := Welcome{ + Version: Version, + Workspace: "/srv/app", + SessionFile: "/srv/j.jsonl", + Model: "a/b", + } + line, _ := json.Marshal(Frame{Kind: "welcome", Payload: mustClientJSON(welcome)}) + _, _ = theirs.Write(append(line, '\n')) + case "call": + target := 64 + if callIndex < len(replySizes) { + target = replySizes[callIndex] + } + callIndex++ + base, _ := plainFrameLineLen(Frame{ + Kind: "result", + ID: frame.ID, + Payload: mustClientJSON([]session.DisplayEntry{{Role: "assistant", Text: ""}}), + }) + textLen := target - base + if textLen < 0 { + textLen = 0 + } + entries := []session.DisplayEntry{{Role: "assistant", Text: strings.Repeat("z", textLen)}} + reply := Frame{Kind: "result", ID: frame.ID, Payload: mustClientJSON(entries)} + line, _ := json.Marshal(reply) + _, _ = theirs.Write(append(line, '\n')) + } + } + }) + return ours + } + + // 1. Bounded client with DefaultMaxLine works at exact DefaultMaxLine + // and on a follow-up call, then fails on DefaultMaxLine+1 with the + // "too large to read" error. + boundedConn := runScriptedHost(t, []int{DefaultMaxLine, 128, DefaultMaxLine + 1}) + boundedClient, err := Dial(boundedConn, "devbox", Hello{Workspace: "app"}, WithMaxLine(DefaultMaxLine)) + if err != nil { + t.Fatalf("Dial bounded client: %v", err) + } + t.Cleanup(func() { _ = boundedClient.Close() }) + + // First call: line of exactly DefaultMaxLine bytes succeeds. + var entriesAtCap []session.DisplayEntry + rawAtCap, err := boundedClient.call(nil, MethodTranscript, nil) + if err != nil { + t.Fatalf("bounded client at exact DefaultMaxLine failed: %v", err) + } + if err := json.Unmarshal(rawAtCap, &entriesAtCap); err != nil || len(entriesAtCap) != 1 { + t.Fatalf("unmarshal entries at cap: %v", err) + } + // Second call: client keeps working after a line at the cap. + if _, err := boundedClient.call(nil, MethodTranscript, nil); err != nil { + t.Fatalf("bounded client subsequent call after cap line failed: %v", err) + } + // Third call: line of DefaultMaxLine+1 bytes ends the connection with + // the "too large to read" error. + _, err = boundedClient.call(nil, MethodTranscript, nil) + if err == nil { + t.Fatal("bounded client accepted a line of DefaultMaxLine+1 bytes") + } + if !strings.Contains(err.Error(), "too large to read") { + t.Fatalf("bounded client error = %q, want text containing 'too large to read'", err.Error()) + } + if clientErr := boundedClient.Err(); clientErr == nil || !strings.Contains(clientErr.Error(), "too large to read") { + t.Fatalf("boundedClient.Err() = %v, want 'too large to read'", clientErr) + } + + // 2. Unbounded client (no MaxLine) reads a 1 MiB line as before. + const oneMiB = 1 << 20 + unboundedConn := runScriptedHost(t, []int{oneMiB}) + unboundedClient, err := Dial(unboundedConn, "devbox", Hello{Workspace: "app"}) + if err != nil { + t.Fatalf("Dial unbounded client: %v", err) + } + t.Cleanup(func() { _ = unboundedClient.Close() }) + + rawOneMiB, err := unboundedClient.call(nil, MethodTranscript, nil) + if err != nil { + t.Fatalf("unbounded client failed on 1 MiB line: %v", err) + } + var entriesOneMiB []session.DisplayEntry + if err := json.Unmarshal(rawOneMiB, &entriesOneMiB); err != nil || len(entriesOneMiB) != 1 { + t.Fatalf("unbounded client 1 MiB decode: %v", err) + } + if gotFrameLen, _ := plainFrameLineLen(Frame{Kind: "result", ID: 1, Payload: rawOneMiB}); gotFrameLen != oneMiB { + t.Fatalf("unbounded client decoded frame of %d bytes, want %d", gotFrameLen, oneMiB) + } + + // 3. A compressed frame whose wire line is tiny but inflates past MaxLine + // is also rejected by a bounded client with the "too large to read" error. + gzipOurs, gzipTheirs := net.Pipe() + t.Cleanup(func() { + _ = gzipOurs.Close() + _ = gzipTheirs.Close() + }) + guard.Go("test/scripted-gzip-bomb-host", func() { + scan := bufio.NewScanner(gzipTheirs) + scan.Buffer(make([]byte, 0, 64*1024), frameCap) + for scan.Scan() { + var frame Frame + if err := json.Unmarshal(scan.Bytes(), &frame); err != nil { + return + } + switch frame.Kind { + case "hello": + welcome := Welcome{ + Version: Version, + Encoding: frameEncodingGzip, + Workspace: "/srv/app", + SessionFile: "/srv/j.jsonl", + Model: "a/b", + } + line, _ := json.Marshal(Frame{Kind: "welcome", Payload: mustClientJSON(welcome)}) + _, _ = gzipTheirs.Write(append(line, '\n')) + case "call": + entries := []session.DisplayEntry{{Role: "assistant", Text: strings.Repeat("g", DefaultMaxLine+64)}} + reply := Frame{Kind: "result", ID: frame.ID, Payload: mustClientJSON(entries)} + _ = compressFrame(&reply, frameEncodingGzip) + line, _ := json.Marshal(reply) + _, _ = gzipTheirs.Write(append(line, '\n')) + } + } + }) + gzipBounded, err := Dial(gzipOurs, "devbox", Hello{Workspace: "app"}, WithMaxLine(DefaultMaxLine)) + if err != nil { + t.Fatalf("Dial gzip bounded client: %v", err) + } + t.Cleanup(func() { _ = gzipBounded.Close() }) + if _, err := gzipBounded.call(nil, MethodTranscript, nil); err == nil || !strings.Contains(err.Error(), "too large to read") { + t.Fatalf("gzip bounded client on inflated oversized frame = %v, want 'too large to read'", err) + } + }) +} diff --git a/internal/rotate/steps.go b/internal/rotate/steps.go index ab9159f94d..e9e1c344fb 100644 --- a/internal/rotate/steps.go +++ b/internal/rotate/steps.go @@ -118,7 +118,7 @@ func (r *run) seal(ctx context.Context) error { if err := r.registerDevice(ctx); err != nil { return err } - r.say("sync storage is off; chats stay on your computers") + r.say("relay storage is off; chats stay on your computers") return r.advance(Sealed) } if err := r.registerDevice(ctx); err != nil { diff --git a/internal/session/answers.go b/internal/session/answers.go index 2eb81acb6a..c7067559f0 100644 --- a/internal/session/answers.go +++ b/internal/session/answers.go @@ -645,6 +645,11 @@ type Answer struct { // asked reads that nothing was decided ([consentDismissed]) rather than that // the person said no, and no decision is recorded, because none was. Dismissed bool `json:"dismissed,omitempty"` + // Remote is set only by the door that carried the answer from another + // computer (internal/remote stamps it, overwriting whatever the surface + // sent), never trusted; it is why this answer may not settle a question + // only the host may settle. + Remote bool `json:"remote,omitempty"` } // Keys is what was picked, however the answer spelled it: [Answer.Picked] where @@ -731,6 +736,9 @@ func deliverAnswer(sessionDir string, answer Answer) error { if dir == "" { return errNoSessionFolder } + // The doorstep file on disk never persists the transient wire stamp from + // another computer. + answer.Remote = false line, err := json.Marshal(answer) if err != nil { return err diff --git a/internal/session/consent.go b/internal/session/consent.go index 94665d92f8..fbb8addd35 100644 --- a/internal/session/consent.go +++ b/internal/session/consent.go @@ -112,6 +112,20 @@ func (a *Agent) ResolveConsent(id uint64, allow bool) { a.ResolveConsentRemember(id, allow, ConsentOnce) } +// ResolveConsentFrom answers one EventConsentRequest and refuses an answer from +// another computer when the banked question was graded irreversible by the +// approval floor. A local caller takes the same path as [Agent.ResolveConsent]; +// a permitted remote caller delivers for this call alone. +func (a *Agent) ResolveConsentFrom(id uint64, allow bool, remote bool) error { + if remote { + if q, said := a.questionSaid(QuestionConsent, strconv.FormatUint(id, 10)); said && q.Stakes == StakesIrreversible { + return ErrRemoteIrreversible + } + } + a.ResolveConsent(id, allow) + return nil +} + // ResolveConsentRemember answers one request and says how long the answer // lasts. An unknown scope is read as ConsentOnce: the narrow reading is the // safe one, and a typo must not silently widen an approval. diff --git a/internal/session/question.go b/internal/session/question.go index fd6e34223d..0357355044 100644 --- a/internal/session/question.go +++ b/internal/session/question.go @@ -2014,6 +2014,12 @@ func (a *Agent) ResolveQuestion(answer Answer) error { if strings.TrimSpace(answer.Key) == "" { answer.Key = answer.FirstKey() } + if err := a.refuseRemoteAnswer(answer); err != nil { + return err + } + // Clear the transport stamp once the remote gate has passed so no + // persisted record or rendered message carries wire metadata. + answer.Remote = false // A REVISION IS THE OTHER THING AN ANSWER CAN BE, and it takes its own road // for one reason: every lane below is a resolver handing an answer to // somebody WAITING for it, and a question that has been settled has nobody diff --git a/internal/session/question_remote.go b/internal/session/question_remote.go new file mode 100644 index 0000000000..127fbd03e2 --- /dev/null +++ b/internal/session/question_remote.go @@ -0,0 +1,84 @@ +package session + +import ( + "errors" + "strings" +) + +// The two fallback sentences returned when an answer from another computer +// tries to settle an irreversible question or remember a wider permission. The +// remote server replaces both with host-named sentences from internal/chatlist +// before sending the refusal over the wire. +var ( + // ErrRemoteIrreversible refuses an answer from another computer when the + // question has irreversible stakes. + ErrRemoteIrreversible = errors.New("that one has to be answered on the computer the chat is running on") + // ErrRemoteWidening refuses a permission answer from another computer when + // its scope reaches beyond a single call. + ErrRemoteWidening = errors.New("that kind of answer has to be given on the computer the chat is running on") +) + +// refuseRemoteAnswer checks whether an answer that arrived from another +// computer is allowed to proceed. It peeks the open-question book with +// [Agent.questionSaid] instead of claiming the entry so a refused answer never +// takes the question off the book, requires no put-back, and leaves no instant +// in which another window could see the question vanish. +func (a *Agent) refuseRemoteAnswer(answer Answer) error { + if !answer.Remote { + return nil + } + if answer.Revises && a.remoteRevisionIsIrreversible(answer) { + return ErrRemoteIrreversible + } + // When nothing is banked (said == false), stakes are unknown: QuestionConsent, + // QuestionAsk, QuestionTask, QuestionAutomation, and QuestionConnect fall + // through to not-irreversible only because an unbanked answer reaches a + // resolver that drops a late id anyway. + if q, said := a.questionSaid(answer.Kind, answerToken(answer)); said && q.Stakes == StakesIrreversible { + return ErrRemoteIrreversible + } + if answer.Kind == QuestionConsent { + if action, ok := AnswerFromKey(QuestionConsent, answer.FirstKey()); ok { + if ConsentScopeOf(action, answer) != ConsentOnce { + return ErrRemoteWidening + } + } + if strings.TrimSpace(answer.Comments[AnswerBanked]) != "" { + return ErrRemoteWidening + } + } + return nil +} + +// remoteRevisionIsIrreversible reports whether a revision from another computer +// targets a settled decision whose stakes were irreversible. +func (a *Agent) remoteRevisionIsIrreversible(answer Answer) bool { + if answer.Kind == QuestionAsk { + a.mu.Lock() + open, settled := a.asked.settledLocked(answer.ID) + var stakes Stakes + if settled { + stakes = open.q.Stakes + } + a.mu.Unlock() + if settled && stakes == StakesIrreversible { + return true + } + } + records := a.Decisions() + for at := len(records) - 1; at >= 0; at-- { + record := records[at] + if record.Kind != answer.Kind { + continue + } + if answer.Ref != "" { + if record.Ref != answer.Ref { + continue + } + } else if record.ID != answer.ID { + continue + } + return !record.Reversible() + } + return false +} diff --git a/internal/session/question_remote_test.go b/internal/session/question_remote_test.go new file mode 100644 index 0000000000..0109a14157 --- /dev/null +++ b/internal/session/question_remote_test.go @@ -0,0 +1,515 @@ +package session + +import ( + "context" + "encoding/json" + "errors" + "os" + "strconv" + "strings" + "testing" + "time" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/approval" + "github.com/Agent-Field/codeaf/internal/guard" +) + +// parkConsentQuestion banks one permission question through the approval gate +// and returns the request event, the channel receiving the gate's verdict, and +// the question watcher stream after the raise event has arrived. +func parkConsentQuestion(t *testing.T, agent *Agent, call ai.ToolCall, rule string) (Event, chan consentAnswer, <-chan Event) { + t.Helper() + hub := newEventHub() + events := hub.subscribe() + asks, stopAsking := agent.WatchQuestions() + t.Cleanup(stopAsking) + + answers := make(chan consentAnswer, 1) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + guard.Go("test/parkConsentQuestion", func() { + answer, err := agent.askAnswer(ctx, hub, call, approval.Decision{ + Action: approval.ActionPrompt, + Rule: rule, + }) + if err == nil { + answers <- answer + } + }) + + request := <-events + if request.Kind != EventConsentRequest { + t.Fatalf("the gate emitted %v before EventConsentRequest", request.Kind) + } + waitForAsk(t, asks, EventQuestion) + return request, answers, asks +} + +// assertNoQuestionAnswered verifies that no EventQuestionAnswered has been +// emitted on the question stream while an answer was refused. +func assertNoQuestionAnswered(t *testing.T, asks <-chan Event) { + t.Helper() + for { + select { + case ev := <-asks: + if ev.Kind == EventQuestionAnswered { + t.Fatalf("a refused answer still emitted EventQuestionAnswered: %+v", ev) + } + default: + return + } + } +} + +// TestARemoteDriverCannotAnswerAnIrreversibleAskRememberAPermissionOrRaiseThePosture +// verifies V26 in the session engine: an answer stamped from another computer +// cannot settle an irreversible permission question, cannot widen a permission +// beyond a single call, and remains subject to the same gate when routed +// through the older consent door or a side discussion, while the host window +// can settle the waiting question afterwards. +func TestARemoteDriverCannotAnswerAnIrreversibleAskRememberAPermissionOrRaiseThePosture(t *testing.T) { + t.Run("irreversible ask is refused to a remote viewer and stays open for the host window", func(t *testing.T) { + agent, _ := questionSession(t, "remote-irrev-host", nil) + call := ai.ToolCall{ + ID: "c-irrev", + Function: ai.ToolCallFunction{Name: "bash", Arguments: `{"command":"rm -rf /tmp/victim"}`}, + } + request, answers, asks := parkConsentQuestion(t, agent, call, "critical command pattern \"rm -rf /*\"") + + open := agent.OpenQuestions() + if len(open) != 1 || open[0].Stakes != StakesIrreversible { + t.Fatalf("expected one open irreversible question, got %+v", open) + } + + // Remote allow, remote deny, and remote dismiss are all refused on an + // irreversible question. + for _, attempt := range []Answer{ + {Remote: true, Kind: QuestionConsent, ID: request.ID, Key: "1"}, + {Remote: true, Kind: QuestionConsent, ID: request.ID, Key: "3"}, + {Remote: true, Kind: QuestionConsent, ID: request.ID, Key: "3", Dismissed: true}, + } { + err := agent.ResolveQuestion(attempt) + if !errors.Is(err, ErrRemoteIrreversible) { + t.Fatalf("ResolveQuestion(%+v) = %v, want ErrRemoteIrreversible", attempt, err) + } + select { + case got := <-answers: + t.Fatalf("refused remote answer %+v released the parked call with %+v", attempt, got) + default: + } + if records := agent.Decisions(); len(records) != 0 { + t.Fatalf("refused remote answer recorded a decision: %+v", records) + } + assertNoQuestionAnswered(t, asks) + if open := agent.OpenQuestions(); len(open) != 1 || open[0].ID != request.ID { + t.Fatalf("refused remote answer took the question off OpenQuestions: %+v", open) + } + } + + // The host's own window (Remote: false) can answer the same question afterwards. + if err := agent.ResolveQuestion(Answer{Remote: false, Kind: QuestionConsent, ID: request.ID, Key: "1"}); err != nil { + t.Fatalf("local ResolveQuestion failed after remote refusals: %v", err) + } + select { + case got := <-answers: + if !got.allow || got.scope != ConsentOnce { + t.Fatalf("local allow delivered %+v, want allow=true scope=once", got) + } + case <-time.After(2 * time.Second): + t.Fatal("the parked call did not proceed after the host window answered") + } + waitForAsk(t, asks, EventQuestionAnswered) + if records := agent.Decisions(); len(records) != 1 { + t.Fatalf("expected 1 recorded decision after host allow, got %+v", records) + } + if open := agent.OpenQuestions(); len(open) != 0 { + t.Fatalf("expected question to close after host allow, got %+v", open) + } + + // A remote viewer also cannot revise a settled irreversible decision. + revErr := agent.ResolveQuestion(Answer{ + Remote: true, + Kind: QuestionConsent, + ID: request.ID, + Key: "3", + Revises: true, + }) + if !errors.Is(revErr, ErrRemoteIrreversible) { + t.Fatalf("remote revision of irreversible decision returned %v, want ErrRemoteIrreversible", revErr) + } + }) + + t.Run("remembering a permission or banking a rule is refused to a remote viewer while once allow and deny deliver", func(t *testing.T) { + agent, _ := questionSession(t, "remote-remember-costly", func(cfg *Config) { + cfg.ApprovalPolicy = promptAll() + }) + costlyCall := ai.ToolCall{ + ID: "c-costly-1", + Function: ai.ToolCallFunction{Name: "write", Arguments: `{"path":"notes.txt","content":"first"}`}, + } + request, answers, asks := parkConsentQuestion(t, agent, costlyCall, "write requires approval") + + if open := agent.OpenQuestions(); len(open) != 1 || open[0].Stakes != StakesCostly { + t.Fatalf("expected one costly question, got %+v", open) + } + + // Key "2" (always / ConsentToolSession) is refused as widening. + err := agent.ResolveQuestion(Answer{Remote: true, Kind: QuestionConsent, ID: request.ID, Key: "2"}) + if !errors.Is(err, ErrRemoteWidening) { + t.Fatalf("remote always returned %v, want ErrRemoteWidening", err) + } + select { + case got := <-answers: + t.Fatalf("refused remote always delivered %+v", got) + default: + } + if _, known := agent.rememberedConsent("write"); known { + t.Fatal("refused remote always recorded a session memo for write") + } + if records := agent.Decisions(); len(records) != 0 { + t.Fatalf("refused remote always recorded a decision: %+v", records) + } + assertNoQuestionAnswered(t, asks) + + // A rule-banking answer (Comments[AnswerBanked] set with key "2") is also + // refused as widening. + bankedErr := agent.ResolveQuestion(Answer{ + Remote: true, + Kind: QuestionConsent, + ID: request.ID, + Key: "2", + Comments: map[string]string{AnswerBanked: "write notes.txt"}, + }) + if !errors.Is(bankedErr, ErrRemoteWidening) { + t.Fatalf("remote banked-rule answer returned %v, want ErrRemoteWidening", bankedErr) + } + select { + case got := <-answers: + t.Fatalf("refused remote banked-rule answer delivered %+v", got) + default: + } + if _, known := agent.rememberedConsent("write"); known { + t.Fatal("refused remote banked-rule answer recorded a session memo") + } + assertNoQuestionAnswered(t, asks) + + // Key "1" (once) from a remote viewer IS delivered and recorded, without + // leaving a session memo behind. + if err := agent.ResolveQuestion(Answer{Remote: true, Kind: QuestionConsent, ID: request.ID, Key: "1"}); err != nil { + t.Fatalf("remote allow-once returned %v", err) + } + select { + case got := <-answers: + if !got.allow || got.scope != ConsentOnce { + t.Fatalf("remote allow-once delivered %+v, want allow=true scope=once", got) + } + case <-time.After(2 * time.Second): + t.Fatal("remote allow-once never reached the waiting call") + } + waitForAsk(t, asks, EventQuestionAnswered) + if records := agent.Decisions(); len(records) != 1 || records[0].Words() != "allow once" { + t.Fatalf("remote allow-once left decisions %+v, want one allow-once record", records) + } + if _, known := agent.rememberedConsent("write"); known { + t.Fatal("remote allow-once recorded a standing session memo") + } + + // Because no session memo was recorded, the next identical call still + // prompts rather than passing silently through approve(). + hub := newEventHub() + events := hub.subscribe() + secondDone := make(chan bool, 1) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + guard.Go("test/secondCostlyCall", func() { + _, allowed := agent.approve(ctx, hub, costlyCall) + secondDone <- allowed + }) + var secondReq Event + select { + case ev := <-events: + if ev.Kind != EventConsentRequest { + t.Fatalf("second identical call emitted %v, want EventConsentRequest", ev.Kind) + } + secondReq = ev + case allowed := <-secondDone: + t.Fatalf("second identical call did not ask again (allowed=%v)", allowed) + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for the second identical call to ask") + } + + // Key "3" (deny) from a remote viewer on a costly question IS delivered. + if err := agent.ResolveQuestion(Answer{Remote: true, Kind: QuestionConsent, ID: secondReq.ID, Key: "3"}); err != nil { + t.Fatalf("remote deny on costly ask returned %v", err) + } + select { + case allowed := <-secondDone: + if allowed { + t.Fatal("remote deny allowed the second call") + } + case <-time.After(2 * time.Second): + t.Fatal("remote deny never released the second call") + } + }) + + t.Run("the older consent door refuses irreversible asks to a remote viewer and delivers once on costly asks", func(t *testing.T) { + agent, _ := questionSession(t, "remote-older-door", nil) + irrevCall := ai.ToolCall{ + ID: "c-irrev-old", + Function: ai.ToolCallFunction{Name: "bash", Arguments: `{"command":"rm -rf /tmp/victim"}`}, + } + irrevReq, irrevAnswers, _ := parkConsentQuestion(t, agent, irrevCall, "critical command pattern \"rm -rf /*\"") + + if err := agent.ResolveConsentFrom(irrevReq.ID, true, true); !errors.Is(err, ErrRemoteIrreversible) { + t.Fatalf("ResolveConsentFrom(irrev, true, remote=true) = %v, want ErrRemoteIrreversible", err) + } + if err := agent.ResolveConsentFrom(irrevReq.ID, false, true); !errors.Is(err, ErrRemoteIrreversible) { + t.Fatalf("ResolveConsentFrom(irrev, false, remote=true) = %v, want ErrRemoteIrreversible", err) + } + select { + case got := <-irrevAnswers: + t.Fatalf("refused ResolveConsentFrom delivered %+v", got) + default: + } + + // Costly ask via ResolveConsentFrom(..., remote=true) delivers once. + costlyCall := ai.ToolCall{ + ID: "c-costly-old", + Function: ai.ToolCallFunction{Name: "write", Arguments: `{"path":"a.txt","content":"b"}`}, + } + costlyReq, costlyAnswers, _ := parkConsentQuestion(t, agent, costlyCall, "write asks") + if err := agent.ResolveConsentFrom(costlyReq.ID, true, true); err != nil { + t.Fatalf("ResolveConsentFrom(costly, true, remote=true) = %v", err) + } + select { + case got := <-costlyAnswers: + if !got.allow || got.scope != ConsentOnce { + t.Fatalf("ResolveConsentFrom on costly ask delivered %+v, want allow=true scope=once", got) + } + case <-time.After(2 * time.Second): + t.Fatal("ResolveConsentFrom on costly ask did not deliver") + } + + // Local ResolveConsentFrom(..., remote=false) on the irreversible ask delivers. + if err := agent.ResolveConsentFrom(irrevReq.ID, true, false); err != nil { + t.Fatalf("ResolveConsentFrom(irrev, true, remote=false) = %v", err) + } + select { + case got := <-irrevAnswers: + if !got.allow || got.scope != ConsentOnce { + t.Fatalf("local ResolveConsentFrom on irreversible ask delivered %+v", got) + } + case <-time.After(2 * time.Second): + t.Fatal("local ResolveConsentFrom on irreversible ask did not deliver") + } + }) + + t.Run("a remote clarification on an irreversible ask and a remote answer to a reversible ask proceed", func(t *testing.T) { + agent, _ := newTestAgent(t, &scriptedCompleter{steps: []step{ + func(context.Context, []ai.Message) (*ai.Response, error) { + return textResponse("That command overwrites the remote branch history."), nil + }, + }}, func(c *Config) { + c.AskConsent = true + c.Interactive = true + c.ApprovalPolicy = promptAll() + }) + watch, stop := agent.WatchQuestions() + t.Cleanup(stop) + + irrevCall := ai.ToolCall{ + ID: "c-clarify-irrev", + Function: ai.ToolCallFunction{Name: "bash", Arguments: `{"command":"rm -rf /tmp/victim"}`}, + } + irrevReq, irrevAnswers, _ := parkConsentQuestion(t, agent, irrevCall, "critical command pattern \"rm -rf /*\"") + + // A Clarify answer only asks for words and resolves nothing, so a remote + // viewer is not refused even when the underlying question is irreversible. + err := agent.ResolveQuestion(Answer{ + Remote: true, + Kind: QuestionConsent, + ID: irrevReq.ID, + Clarify: true, + AskedBack: []Exchange{{Asked: "why does this need force push?"}}, + }) + if err != nil { + t.Fatalf("remote Clarify on irreversible ask was refused: %v", err) + } + discussionWait(t, watch, func(e Event) bool { + return e.Discussion != nil && e.Discussion.Event != nil && e.Discussion.Event.Kind == EventTurnDone + }) + // The irreversible ask itself is still waiting and can be settled locally. + select { + case got := <-irrevAnswers: + t.Fatalf("clarification settled the irreversible ask: %+v", got) + default: + } + if err := agent.ResolveQuestion(Answer{Remote: false, Kind: QuestionConsent, ID: irrevReq.ID, Key: "3"}); err != nil { + t.Fatalf("local deny after clarification failed: %v", err) + } + <-irrevAnswers + + // A remote answer to a reversible model ask question is delivered normally. + askAgent := askTestAgent(t, true) + if _, _, err := askAgent.executeAsk(context.Background(), json.RawMessage(askNotWaiting)); err != nil { + t.Fatalf("executeAsk: %v", err) + } + q := waitForOneQuestion(t, askAgent) + if err := askAgent.ResolveQuestion(Answer{Remote: true, Kind: QuestionAsk, ID: q.ID, Key: "2"}); err != nil { + t.Fatalf("remote answer to reversible ask question failed: %v", err) + } + if notes := askDelivered(askAgent); len(notes) != 1 || !strings.Contains(notes[0], `"key":"2"`) { + t.Fatalf("reversible ask answer was not delivered: %v", notes) + } + }) + + t.Run("a side discussion preserves the remote flag and refuses an irreversible child ask", func(t *testing.T) { + parent, _ := questionSession(t, "remote-discuss-parent", nil) + child, _ := questionSession(t, "remote-discuss-child", nil) + done := make(chan struct{}) + close(done) + parent.mu.Lock() + parent.discussions = map[string]*questionDiscussion{ + "clarify-1": {child: child, cancel: func() {}, done: done, depth: 1}, + } + parent.mu.Unlock() + + irrevCall := ai.ToolCall{ + ID: "c-child-irrev", + Function: ai.ToolCallFunction{Name: "bash", Arguments: `{"command":"rm -rf /tmp/victim"}`}, + } + childReq, childAnswers, _ := parkConsentQuestion(t, child, irrevCall, "critical command pattern \"rm -rf /*\"") + nestedRef := "clarify-1/" + strconv.FormatUint(childReq.ID, 10) + + // Calling discussionAnswer directly returns the Answer value with Remote unchanged. + gotChild, forwarded, ok := parent.discussionAnswer(Answer{ + Remote: true, + Kind: QuestionConsent, + Ref: nestedRef, + Key: "1", + }) + if !ok || gotChild != child || !forwarded.Remote || forwarded.ID != childReq.ID { + t.Fatalf("discussionAnswer lost Remote or target: ok=%v child=%v forwarded=%+v", ok, gotChild == child, forwarded) + } + + // And routing the remote answer through parent.ResolveQuestion refuses the + // child's irreversible ask with ErrRemoteIrreversible. + err := parent.ResolveQuestion(Answer{ + Remote: true, + Kind: QuestionConsent, + Ref: nestedRef, + Key: "1", + }) + if !errors.Is(err, ErrRemoteIrreversible) { + t.Fatalf("parent.ResolveQuestion for remote child irreversible ask = %v, want ErrRemoteIrreversible", err) + } + select { + case got := <-childAnswers: + t.Fatalf("refused child irreversible ask still delivered %+v", got) + default: + } + + // Local answer through the parent discussion door settles the child question. + if err := parent.ResolveQuestion(Answer{ + Remote: false, + Kind: QuestionConsent, + Ref: nestedRef, + Key: "1", + }); err != nil { + t.Fatalf("local parent.ResolveQuestion for child ask failed: %v", err) + } + select { + case got := <-childAnswers: + if !got.allow { + t.Fatalf("local child answer delivered %+v", got) + } + case <-time.After(2 * time.Second): + t.Fatal("local child answer never reached the child wait") + } + }) +} + +// TestAnAnswerCarriesNoRemoteBytesIntoWhatIsKept verifies V26: a remote +// once-allow on a costly permission leaves a decision record on disk and in +// memory, and an answers-file line on disk, with no "remote" key in the +// marshalled bytes. +func TestAnAnswerCarriesNoRemoteBytesIntoWhatIsKept(t *testing.T) { + agent, dir := questionSession(t, "remote-no-persisted-bytes", nil) + costlyCall := ai.ToolCall{ + ID: "c-costly-kept", + Function: ai.ToolCallFunction{Name: "write", Arguments: `{"path":"kept.txt","content":"ok"}`}, + } + request, answers, _ := parkConsentQuestion(t, agent, costlyCall, "write asks") + + if err := agent.ResolveQuestion(Answer{ + Remote: true, + Kind: QuestionConsent, + ID: request.ID, + Key: "1", + }); err != nil { + t.Fatalf("remote once-allow failed: %v", err) + } + <-answers + + records := agent.Decisions() + if len(records) != 1 { + t.Fatalf("expected 1 decision record, got %d", len(records)) + } + recordBytes, err := json.Marshal(records[0]) + if err != nil { + t.Fatalf("marshal decision record: %v", err) + } + if strings.Contains(string(recordBytes), `"remote"`) { + t.Fatalf("marshalled DecisionRecord contains remote key: %s", recordBytes) + } + diskDecisions, err := os.ReadFile(DecisionsPath(dir)) + if err != nil { + t.Fatalf("read decisions file: %v", err) + } + if strings.Contains(string(diskDecisions), `"remote"`) { + t.Fatalf("decisions.jsonl contains remote key: %s", diskDecisions) + } + + if err := WriteAnswer(dir, QuestionConsent, request.ID, "1"); err != nil { + t.Fatalf("WriteAnswer: %v", err) + } + if err := deliverAnswer(dir, Answer{ + At: time.Date(2026, 9, 9, 10, 0, 0, 0, time.UTC), + Kind: QuestionConsent, + ID: request.ID, + Key: "1", + Remote: true, + }); err != nil { + t.Fatalf("deliverAnswer: %v", err) + } + diskAnswers, err := os.ReadFile(AnswersPath(dir)) + if err != nil { + t.Fatalf("read answers file: %v", err) + } + if strings.Contains(string(diskAnswers), `"remote"`) { + t.Fatalf("answers.jsonl contains remote key: %s", diskAnswers) + } +} + +// TestAnAnswerWithoutTheRemoteFlagMarshalsAsItAlwaysDid verifies V26: an Answer +// with Remote false marshals to the exact JSON bytes written from the field +// list, with no "remote" key present. +func TestAnAnswerWithoutTheRemoteFlagMarshalsAsItAlwaysDid(t *testing.T) { + answer := Answer{ + At: time.Date(2026, 9, 9, 10, 0, 0, 0, time.UTC), + Kind: QuestionConsent, + ID: 7, + Key: "1", + From: "home", + } + raw, err := json.Marshal(answer) + if err != nil { + t.Fatalf("marshal Answer: %v", err) + } + const want = `{"at":"2026-09-09T10:00:00Z","kind":"consent","id":7,"key":"1","from":"home"}` + if string(raw) != want { + t.Fatalf("json.Marshal(Answer) =\n got: %s\nwant: %s", raw, want) + } +} diff --git a/internal/session/submission.go b/internal/session/submission.go index c096c56a1b..98e60e9253 100644 --- a/internal/session/submission.go +++ b/internal/session/submission.go @@ -80,10 +80,13 @@ type Submission struct { // entry ([PersonMark.ClientID]), so a door can recognise its message after // the process that sent it is gone. // - // IT IS CORRELATION, NEVER IDEMPOTENCY. The session does not look it up, - // refuse a repeat of it or skip a send because of it; two messages with one - // ClientID are two messages. Empty is "the door named none", and the model - // is sent nothing of it. + // IT IS CORRELATION HERE; THE REMOTE DOOR MAKES IT IDEMPOTENCY. The session + // itself does not look it up, refuse a repeat of it or skip a send because + // of it; two messages handed to this package with one ClientID are two + // messages. The remote door (internal/remote) does look it up for + // connections stamped with Hello.Remote, answering a repeat with the + // original stream rather than delivering the message a second time. Empty + // is "the door named none", and the model is sent nothing of it. ClientID string // From names who sent the message on the person's behalf, such as "afi", // at most [MaxMessageFromBytes] bytes of one line. It is kept on the diff --git a/internal/session/tools_settings.go b/internal/session/tools_settings.go index 36067d474c..8dd2f1d6ab 100644 --- a/internal/session/tools_settings.go +++ b/internal/session/tools_settings.go @@ -353,7 +353,7 @@ func settingListing(registry *config.Settings, search string) string { return fmt.Sprintf("No setting mentions %q. Call %s with no arguments to see every row.", search, settingsToolName) } var out strings.Builder - for _, category := range []string{"General", "Models", "Memory", "Tasks", "AI teams", "Permissions", "Spending", "Connections", "Privacy"} { + for _, category := range []string{"General", "Models", "Memory", "Tasks", "AI teams", "Permissions", "Spending", "Connections", "Devices", "Privacy"} { if len(groups[category]) == 0 { continue } diff --git a/internal/session/tools_settings_test.go b/internal/session/tools_settings_test.go index fff6c8e8d4..c6c3561ac5 100644 --- a/internal/session/tools_settings_test.go +++ b/internal/session/tools_settings_test.go @@ -118,7 +118,7 @@ func TestSettingsListsEveryRowByItsRegistryKey(t *testing.T) { t.Errorf("the listing does not carry the row %s", row.Key) } } - for _, category := range []string{"General", "Models", "Memory", "Tasks", "AI teams", "Permissions", "Spending", "Connections", "Privacy"} { + for _, category := range []string{"General", "Models", "Memory", "Tasks", "AI teams", "Permissions", "Spending", "Connections", "Devices", "Privacy"} { if !strings.Contains(text, category) { t.Errorf("the listing does not name the %q group", category) } diff --git a/internal/session/workspace_gate_test.go b/internal/session/workspace_gate_test.go index e0244fa2b5..78fecea966 100644 --- a/internal/session/workspace_gate_test.go +++ b/internal/session/workspace_gate_test.go @@ -331,7 +331,7 @@ func TestC3WorkspaceToolNeverRunsAfterTheOwnerOfAFailedArrivalDied(t *testing.T) t.Fatalf("tool executed %d times on a partial workspace tree after its fetch failed and its owner left; want 0", executedOnPartialTree.Load()) } combined := toolErrText + "\n" + finalText - for _, want := range []string{"workspace files could not arrive", "sync could not be reached", "continue the chat here again"} { + for _, want := range []string{"workspace files could not arrive", "sync could not be reached", "move the chat here again"} { if !strings.Contains(combined, want) { t.Fatalf("expected %q in what the person is told, got:\n%s", want, combined) } diff --git a/internal/syncsetup/arrival_abandoned_test.go b/internal/syncsetup/arrival_abandoned_test.go index fda6e574e3..ae475ae53b 100644 --- a/internal/syncsetup/arrival_abandoned_test.go +++ b/internal/syncsetup/arrival_abandoned_test.go @@ -62,8 +62,8 @@ func TestW10bTakingAChatAgainRestartsTheFilesOfAnAbandonedArrival(t *testing.T) // Until the restart, a seal refuses, with what to do. _, sealErr := h.engB.Seal(t.Context(), bCell, cellstore.TurnInfo{}) - if !errors.Is(sealErr, cell.ErrWorkspaceArrivalAbandoned) || !strings.Contains(sealErr.Error(), "sync could not be reached") || !strings.Contains(sealErr.Error(), "continue the chat here again") { - t.Fatalf("a seal of the partial tree = %v; want a refusal carrying the reason and saying to continue the chat here again", sealErr) + if !errors.Is(sealErr, cell.ErrWorkspaceArrivalAbandoned) || !strings.Contains(sealErr.Error(), "sync could not be reached") || !strings.Contains(sealErr.Error(), "move the chat here again") { + t.Fatalf("a seal of the partial tree = %v; want a refusal carrying the reason and saying to move the chat here again", sealErr) } // Opening the chat again is the restart. diff --git a/internal/syncsetup/cluster.go b/internal/syncsetup/cluster.go index be92cc8ec9..a846f36882 100644 --- a/internal/syncsetup/cluster.go +++ b/internal/syncsetup/cluster.go @@ -208,7 +208,7 @@ func (s *Sync) ClusterNames(ctx context.Context, status clusterctl.Status) map[u key := directory.MetadataKey(s.Identity.CellKey()) for _, member := range status.Members { if member.Anchor { - names[member.Node] = "the sync service" + names[member.Node] = "the relay" continue } if err != nil { diff --git a/internal/syncsetup/devices.go b/internal/syncsetup/devices.go index 28cc99a534..c81e4b4ba9 100644 --- a/internal/syncsetup/devices.go +++ b/internal/syncsetup/devices.go @@ -217,6 +217,7 @@ func (d *deviceDirectory) List(ctx context.Context) (directory.Listing, error) { s.Devices, s.Version, s.Complete = devices, max(s.Version, l.Version), true }) rememberOthers(d.home, d.binding, l.Devices) + snapshotLegacyOnce(d.home, d.binding, l.Devices) } return l, err } @@ -425,6 +426,9 @@ func (s *deviceStream) Next(ctx context.Context) (dirwatch.Frame, error) { } } }) + if err == nil && f.Event != nil && f.Event.T == dirwatch.EventRevoked && f.Event.Device != "" { + notifyRevoked(s.dir.home, f.Event.Device) + } return f, err } diff --git a/internal/syncsetup/direct_road_test.go b/internal/syncsetup/direct_road_test.go new file mode 100644 index 0000000000..96ff793419 --- /dev/null +++ b/internal/syncsetup/direct_road_test.go @@ -0,0 +1,383 @@ +package syncsetup + +import ( + "context" + "errors" + "io" + "net" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/filesdoor" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/remote" +) + +// fakeDirectRoadHost stands in for the pion implementation: it records what the +// sync package asked of it and lets a test open a stream into the door without +// any network, which is the one thing the sync package decides. +type fakeDirectRoadHost struct { + stun []string + + mu sync.Mutex + ctx context.Context + accept func(ctx context.Context, stream io.ReadWriteCloser) + closed chan struct{} + closeOne sync.Once +} + +func (h *fakeDirectRoadHost) Offered(context.Context, livedoor.Peer, []byte, livedoor.Signaller) livedoor.DirectSession { + return nil +} + +func (h *fakeDirectRoadHost) SetAcceptor(ctx context.Context, accept func(ctx context.Context, stream io.ReadWriteCloser)) { + h.mu.Lock() + h.ctx, h.accept = ctx, accept + h.mu.Unlock() +} + +func (h *fakeDirectRoadHost) Close() { h.closeOne.Do(func() { close(h.closed) }) } + +func (h *fakeDirectRoadHost) acceptor() (context.Context, func(context.Context, io.ReadWriteCloser)) { + h.mu.Lock() + defer h.mu.Unlock() + return h.ctx, h.accept +} + +// connect hands the door the far end of a fresh pipe, the way the road hands it +// the stream of an opened data channel, and returns the viewer's end. +func (h *fakeDirectRoadHost) connect(t *testing.T) io.ReadWriteCloser { + t.Helper() + ctx, accept := h.acceptor() + if accept == nil { + t.Fatal("the door never installed an acceptor on the direct road's host") + } + viewer, host := net.Pipe() + guard.Go("syncsetup.test.direct.accept", func() { accept(ctx, host) }) + t.Cleanup(func() { _ = viewer.Close() }) + return viewer +} + +// fakeDirectRoad installs a counting stand-in for the direct road and restores +// whatever the program had installed when the test ends. +type fakeDirectRoad struct { + mu sync.Mutex + hosts []*fakeDirectRoadHost +} + +func installFakeDirectRoad(t *testing.T) *fakeDirectRoad { + t.Helper() + previous, _ := InstalledDirectRoad() + t.Cleanup(func() { SetDirectRoad(previous) }) + f := &fakeDirectRoad{} + SetDirectRoad(DirectRoad{ + NewHost: func(stun []string) DirectRoadHost { + h := &fakeDirectRoadHost{stun: slices.Clone(stun), closed: make(chan struct{})} + f.mu.Lock() + f.hosts = append(f.hosts, h) + f.mu.Unlock() + return h + }, + Offer: func(context.Context, []string, livedoor.Signaller, <-chan []byte) (io.ReadWriteCloser, error) { + return nil, errors.New("the test's direct road makes no offers") + }, + }) + return f +} + +func (f *fakeDirectRoad) built() []*fakeDirectRoadHost { + f.mu.Lock() + defer f.mu.Unlock() + return slices.Clone(f.hosts) +} + +// V36 / V38: a computer builds no direct road, and so can make no STUN request, +// unless remote control is on, the road is not pinned to the relay, and the +// program installed one; when it does, the door takes its host half and serves +// every live tunnel through the road-aware handler. +func TestDirectIsAbsentWhenRemoteControlIsOffOrTheRoadIsRelay(t *testing.T) { + cases := []struct { + name string + env map[string]string + install bool + want bool + }{ + {"remote control off", map[string]string{"CODEAF_REMOTE_CONTROL": "off"}, true, false}, + {"road pinned to the relay", map[string]string{"CODEAF_REMOTE_CONTROL": "on", "CODEAF_REMOTE_ROAD": "relay"}, true, false}, + {"nothing installed", map[string]string{"CODEAF_REMOTE_CONTROL": "on"}, false, false}, + {"on, default road", map[string]string{"CODEAF_REMOTE_CONTROL": "on"}, true, true}, + {"on, road auto", map[string]string{"CODEAF_REMOTE_CONTROL": "on", "CODEAF_REMOTE_ROAD": "auto"}, true, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + for k, v := range tc.env { + t.Setenv(k, v) + } + r := newLiveRig(t) + road := installFakeDirectRoad(t) + if !tc.install { + SetDirectRoad(DirectRoad{}) + } + cfg, err := r.a.filesDoorConfig() + if err != nil { + t.Fatal(err) + } + hosts := road.built() + if !tc.want { + if len(hosts) != 0 || cfg.Direct != nil || cfg.LiveRoad != nil { + t.Fatalf("a direct road was built (%d hosts, Direct set=%v, LiveRoad set=%v)", len(hosts), cfg.Direct != nil, cfg.LiveRoad != nil) + } + if config.RemoteControlOn() != (cfg.Live != nil) { + t.Fatalf("Live set=%v with remote control %v: the relay road must be unchanged", cfg.Live != nil, config.RemoteControlOn()) + } + return + } + if len(hosts) != 1 || cfg.Direct == nil || cfg.LiveRoad == nil || cfg.Live != nil { + t.Fatalf("hosts=%d Direct=%v LiveRoad=%v Live=%v; want one host and the road-aware handler only", len(hosts), cfg.Direct != nil, cfg.LiveRoad != nil, cfg.Live != nil) + } + if want := config.RemoteSTUN(); !slices.Equal(hosts[0].stun, want) || len(want) != 2 { + t.Fatalf("the host was given STUN %v, want the configured default %v", hosts[0].stun, want) + } + }) + } + + t.Run("STUN off reaches the host as an empty list", func(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + t.Setenv("CODEAF_REMOTE_STUN", "off") + r := newLiveRig(t) + road := installFakeDirectRoad(t) + if _, err := r.a.filesDoorConfig(); err != nil { + t.Fatal(err) + } + hosts := road.built() + if len(hosts) != 1 || hosts[0].stun == nil || len(hosts[0].stun) != 0 { + t.Fatalf("with STUN off the host was given %#v, want an empty non-nil list", hosts) + } + }) +} + +// V35: the door counts direct streams (filesdoor) and the router counts direct +// tunnels (livedoor); they are one limit written twice, so they must agree. +func TestDirectCapIsTheSameNumberOnBothSidesOfTheDoor(t *testing.T) { + if filesdoor.MaxDirect != livedoor.MaxDirect { + t.Fatalf("filesdoor admits %d direct streams and livedoor serves %d direct tunnels; the two caps are one number", filesdoor.MaxDirect, livedoor.MaxDirect) + } +} + +// V34: a device removed through the real directory path loses its direct view +// with the word `removed`, the view said it was on the direct road, and the +// same device is refused a new direct stream afterwards. +func TestRemovingADeviceClosesItsDirectViewThroughTheRealDirectoryPath(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + r := newLiveRig(t) + liveDoorRosterFor = 20 * time.Millisecond + road := installFakeDirectRoad(t) + + stub := &stubLiveAgent{title: "Direct Revoke Chat"} + hostHeldChat(t, r, r.cell.ID, stub) + r.a.ensureFilesDoor() + waitFor(t, "the door to take its direct host half", func() bool { + hosts := road.built() + if len(hosts) == 0 { + return false + } + _, accept := hosts[0].acceptor() + return accept != nil + }) + host := road.built()[0] + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + tun, err := filesdoor.DialDirect(ctx, host.connect(t), r.b.Identity, r.b.Device, r.a.Device.ID()) + if err != nil { + t.Fatalf("DialDirect: %v", err) + } + mux := livedoor.NewMux(tun, livedoor.Viewer, livedoor.MuxConfig{}) + t.Cleanup(func() { _ = mux.Close() }) + ack, err := mux.WaitHelloAck(ctx) + if err != nil { + t.Fatalf("WaitHelloAck: %v", err) + } + if ack.Road != livedoor.RoadDirect || ack.Direct { + t.Fatalf("the host's ack on a direct stream = %+v, want road %q and no further offer", ack, livedoor.RoadDirect) + } + + opened := make(chan *livedoor.Channel, 4) + viewer, err := remote.Roam(nameA, remote.Hello{Surface: nameB, Join: true}, remote.Roaming{ + Dial: func() (io.ReadWriteCloser, error) { + ch, openErr := mux.Open(ctx, r.cell.ID) + if openErr != nil { + return nil, openErr + } + opened <- ch + return ch, nil + }, + }) + if err != nil { + t.Fatalf("a direct view did not open: %v", err) + } + t.Cleanup(func() { _ = viewer.Close() }) + ch := <-opened + + mustNil(t, r.a.Dir.Revoke(context.Background(), r.b.Device.ID())) + select { + case <-ch.Done(): + case <-time.After(5 * time.Second): + t.Fatal("a removed device's direct view stayed open") + } + if got := ch.Reason(); got != livedoor.ReasonRemoved { + t.Fatalf("the direct view ended with %q, want %q", got, livedoor.ReasonRemoved) + } + + _, err = filesdoor.DialDirect(ctx, host.connect(t), r.b.Identity, r.b.Device, r.a.Device.ID()) + var refused *filesdoor.RefusedError + if !errors.As(err, &refused) || strings.TrimSpace(refused.Reason) != filesdoor.RemovedLine { + t.Fatalf("a removed device's new direct stream gave %v, want a refusal that says %q", err, filesdoor.RemovedLine) + } +} + +// V37 (lifetime): the host half is closed when the door's context ends, so a +// door that stops takes every pending attempt with it. +func TestDirectHostEndsWithTheDoor(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + r := newLiveRig(t) + road := installFakeDirectRoad(t) + r.a.ensureFilesDoor() + waitFor(t, "the door to take its direct host half", func() bool { + hosts := road.built() + if len(hosts) == 0 { + return false + } + _, accept := hosts[0].acceptor() + return accept != nil + }) + host := road.built()[0] + stopFilesDoor(r.a.Home) + select { + case <-host.closed: + case <-time.After(5 * time.Second): + t.Fatal("the direct host half outlived the files door that owned it") + } +} + +// V36 (the viewer's half): a viewer link has a direct half, and so can make a +// STUN request, under exactly the conditions the door answers one: remote +// control on, the road not pinned to the relay, and a road installed. Anywhere +// else the link is the relay link it was before this phase, with nothing to +// signal and nothing to offer. +func TestAViewerLinkOffersTheDirectRoadOnlyWhereTheDoorWouldAnswerIt(t *testing.T) { + cases := []struct { + name string + env map[string]string + install bool + want bool + }{ + {"remote control off", map[string]string{"CODEAF_REMOTE_CONTROL": "off"}, true, false}, + {"road pinned to the relay", map[string]string{"CODEAF_REMOTE_CONTROL": "on", "CODEAF_REMOTE_ROAD": "relay"}, true, false}, + {"nothing installed", map[string]string{"CODEAF_REMOTE_CONTROL": "on"}, false, false}, + {"on, default road", map[string]string{"CODEAF_REMOTE_CONTROL": "on"}, true, true}, + {"on, road auto", map[string]string{"CODEAF_REMOTE_CONTROL": "on", "CODEAF_REMOTE_ROAD": "auto"}, true, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + for k, v := range tc.env { + t.Setenv(k, v) + } + r := newLiveRig(t) + installFakeDirectRoad(t) + if !tc.install { + SetDirectRoad(DirectRoad{}) + } + cfg := r.b.liveLinkConfig(r.a.Device.ID(), nameA, nil, nil) + if (cfg.Direct != nil) != tc.want || (cfg.OnSignal != nil) != tc.want { + t.Fatalf("Direct set=%v and OnSignal set=%v, want both %v", cfg.Direct != nil, cfg.OnSignal != nil, tc.want) + } + }) + } +} + +// V30 and V36 (the viewer's half): an attempt hands the road the STUN list the +// person configured (an empty one when they said off), gives it every signal the +// host sends after the attempt began and none from before it, and never blocks +// the relay's read loop however many arrive with nobody reading them. +func TestAViewerLinksDirectAttemptReadsTheHostsSignalsAndNeverBlocksTheRelay(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + t.Setenv("CODEAF_REMOTE_STUN", "off") + r := newLiveRig(t) + + type asked struct { + stun []string + deliver <-chan []byte + } + started := make(chan asked, 1) + previous, _ := InstalledDirectRoad() + t.Cleanup(func() { SetDirectRoad(previous) }) + SetDirectRoad(DirectRoad{ + NewHost: func([]string) DirectRoadHost { return &fakeDirectRoadHost{closed: make(chan struct{})} }, + Offer: func(ctx context.Context, stun []string, _ livedoor.Signaller, deliver <-chan []byte) (io.ReadWriteCloser, error) { + started <- asked{stun: slices.Clone(stun), deliver: deliver} + select { + case payload := <-deliver: + return nil, errors.New("the road read " + string(payload)) + case <-ctx.Done(): + return nil, ctx.Err() + } + }, + }) + cfg := r.b.liveLinkConfig(r.a.Device.ID(), nameA, nil, nil) + if cfg.Direct == nil || cfg.OnSignal == nil { + t.Fatal("the viewer link has no direct half with remote control on and a road installed") + } + + // A flood nobody is reading must return at once: OnSignal runs on the relay's + // read loop, and a view whose loop is blocked is a view that has stopped. + flooded := make(chan struct{}) + guard.Go("syncsetup.test.direct.flood", func() { + for range 4 * directSignalBuffer { + cfg.OnSignal([]byte("stale")) + } + close(flooded) + }) + select { + case <-flooded: + case <-time.After(5 * time.Second): + t.Fatal("OnSignal blocked with nobody reading the host's signals") + } + + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + result := make(chan error, 1) + guard.Go("syncsetup.test.direct.dial", func() { + _, err := cfg.Direct.Dial(ctx, nopSignaller{}) + result <- err + }) + var got asked + select { + case got = <-started: + case <-time.After(5 * time.Second): + t.Fatal("the attempt never reached the road") + } + if got.stun == nil || len(got.stun) != 0 { + t.Fatalf("the road was given STUN %#v with CODEAF_REMOTE_STUN=off, want an empty list", got.stun) + } + cfg.OnSignal([]byte("answer")) + select { + case err := <-result: + if err == nil || err.Error() != "the road read answer" { + t.Fatalf("the attempt ended with %v, want it to have read the one signal that came after it began (not the %d stale ones)", err, 4*directSignalBuffer) + } + case <-time.After(10 * time.Second): + t.Fatal("the attempt never read the host's signal") + } +} + +// nopSignaller is a Signaller whose frames go nowhere, for a road that is not +// the thing under test. +type nopSignaller struct{} + +func (nopSignaller) Send([]byte) error { return nil } diff --git a/internal/syncsetup/directroad.go b/internal/syncsetup/directroad.go new file mode 100644 index 0000000000..cc96407b9b --- /dev/null +++ b/internal/syncsetup/directroad.go @@ -0,0 +1,70 @@ +package syncsetup + +import ( + "context" + "io" + "sync" + + "github.com/Agent-Field/codeaf/internal/livedoor" +) + +// THE DIRECT ROAD REACHES THIS PACKAGE THROUGH ONE SEAM, AND THE PROGRAM FILLS IT. +// The road is a WebRTC data channel, and its implementation pulls a peer-to-peer +// library into whatever imports it. Every package that links syncsetup would pay +// for that, tests and the small binaries included, so this package states what it +// needs from the road and the program's entry point installs the real one, the +// same way the live door is handed its engine host. A build or a test that never +// installs it has no direct road: the door advertises none and takes no offer. + +// DirectRoadHost is the host half of the direct road for one files door: it +// answers offers (livedoor.DirectHost), is told where an opened stream goes, and +// ends every attempt and stream it holds when the door's context ends. +type DirectRoadHost interface { + livedoor.DirectHost + // SetAcceptor installs where an opened stream goes. ctx is the lifetime of + // the files door's Serve call. + SetAcceptor(ctx context.Context, accept func(ctx context.Context, stream io.ReadWriteCloser)) + // Close releases everything the host holds. It is safe to call twice. + Close() +} + +// DirectRoad is what the program installs: the host half and the viewer half, +// each given the STUN servers the person's configuration names (an empty list is +// "no STUN request, ever"). +type DirectRoad struct { + // NewHost builds one host half. It must not touch the network. + NewHost func(stun []string) DirectRoadHost + // Offer is the viewer half: it signals through s, reads the host's replies + // from deliver, and returns the opened byte stream or an error. + Offer func(ctx context.Context, stun []string, s livedoor.Signaller, deliver <-chan []byte) (io.ReadWriteCloser, error) +} + +var ( + directRoadMu sync.RWMutex + directRoad DirectRoad +) + +// SetDirectRoad installs the direct road. It is meant to be called once, from +// the program's entry point, before any door starts. +func SetDirectRoad(d DirectRoad) { + directRoadMu.Lock() + directRoad = d + directRoadMu.Unlock() +} + +// InstalledDirectRoad returns the direct road the program installed and whether +// both halves are in place. +func InstalledDirectRoad() (DirectRoad, bool) { + directRoadMu.RLock() + d := directRoad + directRoadMu.RUnlock() + return d, d.NewHost != nil && d.Offer != nil +} + +// DirectRoadInstalled says whether the program installed the direct road, so a +// test of the program's entry point can pin that it did: without it no computer +// ever offers or answers a direct connection, and nothing else would say so. +func DirectRoadInstalled() bool { + _, ok := InstalledDirectRoad() + return ok +} diff --git a/internal/syncsetup/drive.go b/internal/syncsetup/drive.go index 55159796e5..16765d1dbf 100644 --- a/internal/syncsetup/drive.go +++ b/internal/syncsetup/drive.go @@ -47,6 +47,12 @@ type DriveOptions struct { OnRenewalChange func() // Sleep replaces real time between background attempts; tests inject a fake. Sleep func(ctx context.Context, d time.Duration) error + // EarlyRecord says whether the START of a chat's first spoken turn may + // create its directory record, instead of waiting for the first sealed turn. + // It is read at the moment the turn starts, and nil means no. It exists for + // remote control: another computer can only open a chat it can list, and a + // chat whose first turn is long was on no other computer's list for all of it. + EarlyRecord func() bool } // Drive is the drive side of one chat: it publishes each sealed turn, holds @@ -59,6 +65,14 @@ type Drive struct { idleRequested atomic.Bool idlePrepared atomic.Bool working atomic.Bool + // earlyNoted is set once the startup head has been handed to the batcher + // for an early record, so the turns after the first do not read the journal + // again to decide the same thing. + earlyNoted atomic.Bool + // earlyAsked is set the one time the drive has said the first spoken turn + // began on a chat with no sealed head ([Drive.EarlyHeadOwed]), so a failed + // save is not asked for again at every later turn. + earlyAsked atomic.Bool workMu sync.Mutex // Admission and voluntary release cannot cross each other. activity atomic.Uint64 released atomic.Bool @@ -887,8 +901,83 @@ func (d *Drive) Gate() error { func (d *Drive) Working(on bool) { d.working.Store(on) if d.batcher != nil { + // The flag is stored first so the publish that creates an early record is + // told the chat is working, and the row is never born idle. d.batcher.Working(on) + if on { + d.recordEarly() + } + } +} + +// recordEarly creates the directory record of a chat at the START of its first +// spoken turn, behind [DriveOptions.EarlyRecord]. The record has always come +// from the first SEALED turn, and the person's first message is journaled +// before any turn seals, so a chat whose first turn runs for minutes was on no +// other computer's list while it ran. The head handed over is the one this +// window sealed at startup: a record needs some head to stand on, and that is +// the least a head can be. Nothing about the turn travels, the title and folder +// are whatever a publish sends today under the same storage rules, and when +// the turn seals the head moves on exactly as it does for every chat. +// +// IT IS A NO-OP unless every one of these holds: the option is on now, the +// chat has no record yet, and the journal holds a spoken message, which is the +// same test [Drive.note] makes against a sealed head and what keeps a chat +// nobody spoke in off every other computer. A chat that already has a record +// needs nothing, because it is already listed and its working flag rides the +// beat. +func (d *Drive) recordEarly() { + if d.opt.EarlyRecord == nil || d.earlyNoted.Load() || d.batcher.Fence() != 0 || d.sync.isRemoved() { + return + } + if !d.opt.EarlyRecord() { + return + } + if spoken, _ := session.ConversationIn(session.Place{Dir: d.cell.Root}.Transcript(), -1); !spoken { + return + } + head, err := cellstore.Head(d.cell) + if err != nil || head == nil { + return + } + d.earlyNoted.Store(true) + d.batcher.Note(head.Turn) +} + +// EarlyHeadOwed says the first spoken turn has begun on a chat that has never +// been sealed, so [Drive.recordEarly] had no head to stand on and the record +// would wait for the turn to end. It answers true at most once per drive, and +// only when every one of these holds: the option is on now, a turn is running, +// the chat has no record yet, no head exists, and the journal holds a spoken +// message. The caller then has the chat sealed through its own recorder, the +// road every other seal takes, and that seal reaches [Drive.note] and makes +// the record exactly as a sealed turn does. +// +// A CHAT OPENED WITH /new HAS NO HEAD WHEN ITS FIRST TURN STARTS. The warm +// capture opens the folder without sealing an empty turn, and the trailing seal +// treats a journal that holds only its header as not grown. So the head the +// early record was written to stand on is there only when something else had +// sealed the chat, and for a new chat that waited for the first message the +// record appeared when the turn ended, as it did before the option existed. +// +// The head this asks for is the chat as it stands when the turn starts, which +// holds the person's first message. Nothing about that travels in the record, +// and the frames behind it go where every sealed turn's frames go: nowhere +// while blind pass-through is the road, the relay's store otherwise. +func (d *Drive) EarlyHeadOwed() bool { + if d.batcher == nil || !d.working.Load() || d.opt.EarlyRecord == nil || d.earlyNoted.Load() || d.earlyAsked.Load() || d.batcher.Fence() != 0 || d.sync.isRemoved() { + return false + } + if !d.opt.EarlyRecord() { + return false + } + if head, err := cellstore.Head(d.cell); err != nil || head != nil { + return false + } + if spoken, _ := session.ConversationIn(session.Place{Dir: d.cell.Root}.Transcript(), -1); !spoken { + return false } + return d.earlyAsked.CompareAndSwap(false, true) } func (d *Drive) Idle() { diff --git a/internal/syncsetup/drive_early_head_test.go b/internal/syncsetup/drive_early_head_test.go new file mode 100644 index 0000000000..31014536e7 --- /dev/null +++ b/internal/syncsetup/drive_early_head_test.go @@ -0,0 +1,159 @@ +package syncsetup + +import ( + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/cellstore" +) + +// These tests are the other half of the early directory record (see +// drive_early_record_test.go). That file proves the record is made from a head +// the window sealed at startup. A chat opened with /new has no such head: the +// warm capture seals no empty turn and a journal that holds only its header is +// not grown. So the first spoken turn of a new chat started with NO head, the +// early record had nothing to stand on, and the row appeared when the turn +// ended. The drive now says, once, that a head is owed; the window then seals +// the chat through its own recorder and that seal makes the record. + +// freshChat is a drive on a chat that has only been opened: nothing sealed, +// nobody spoken, the state /new leaves. +func freshChat(t *testing.T, r *twoHomes, early func() bool) *Drive { + t.Helper() + d, err := r.a.Drive(t.Context(), r.engine, r.cell, DriveOptions{EarlyRecord: early}) + mustNil(t, err) + t.Cleanup(func() { _ = d.Close(t.Context()) }) + if head, err := cellstore.Head(r.cell); err != nil || head != nil { + t.Fatalf("the fixture's new chat already has a head (%v, %v)", head, err) + } + return d +} + +// sealsAsTheWindowDoes is what the window's recorder does when asked to seal a +// chat now: a seal through the drive's own store. +func (r *twoHomes) sealsAsTheWindowDoes(t *testing.T, d *Drive) { + t.Helper() + _, err := d.Store(r.engine).Seal(t.Context(), r.cell, cellstore.TurnInfo{}) + mustNil(t, err) +} + +// C1: remote control on, a new chat whose first turn runs. The drive says a +// head is owed, once; the seal that follows puts the chat on the other +// computer's list as working while the turn is still running. +func TestTheFirstTurnOfANewChatAsksForAHeadAndThenHasItsRecord(t *testing.T) { + r := newTwoHomes(t) + d := freshChat(t, r, func() bool { return true }) + appendTo(t, transcriptOf(r.cell), `{"type":"message","role":"user","content":"hello"}`+"\n") + d.Working(true) + if _, found := r.recordOn(t, r.cell.ID); found { + t.Fatal("a record exists before any head was sealed") + } + if !d.EarlyHeadOwed() { + t.Fatal("the first spoken turn of a chat with no head did not ask for one") + } + if d.EarlyHeadOwed() { + t.Fatal("the drive asked for the head twice") + } + r.sealsAsTheWindowDoes(t, d) + waitFor(t, "the working chat's record on the other computer", func() bool { + view, found := r.recordOn(t, r.cell.ID) + return found && view.Cell.Lease.Working + }) + rows, err := r.b.Rows(t.Context()) + mustNil(t, err) + if len(rows) != 1 || rows[0].Cell != r.cell.ID || !rows[0].Working { + t.Fatalf("the other computer lists %+v, want the one working chat", rows) + } +} + +// C2: a chat nobody typed in asks for nothing and appears nowhere. +func TestAChatNobodyTypedInNeverAsksForAHead(t *testing.T) { + r := newTwoHomes(t) + d := freshChat(t, r, func() bool { return true }) + d.Working(true) + if d.EarlyHeadOwed() { + t.Fatal("a chat nobody has spoken in asked for a head") + } + r.sealsAsTheWindowDoes(t, d) + d.Working(false) + mustNil(t, d.Close(t.Context())) + if _, found := r.recordOn(t, r.cell.ID); found { + t.Fatal("a chat nobody has spoken in appeared on the other computer") + } + rows, err := r.b.Rows(t.Context()) + mustNil(t, err) + if len(rows) != 0 { + t.Fatalf("the other computer lists an unused chat: %+v", rows) + } +} + +// C3: with the option off, or never given, or off by the time the turn starts, +// nothing is asked for and the record comes when the turn is sealed, as before. +func TestWithTheOptionOffTheFirstTurnAsksForNoHead(t *testing.T) { + on := true + for name, early := range map[string]func() bool{ + "not given": nil, + "off": func() bool { return false }, + "turned off after the drive started": func() bool { return on }, + } { + t.Run(name, func(t *testing.T) { + r := newTwoHomes(t) + d := freshChat(t, r, early) + on = false + appendTo(t, transcriptOf(r.cell), `{"type":"message","role":"user","content":"hello"}`+"\n") + d.Working(true) + if d.EarlyHeadOwed() { + t.Fatal("a head was asked for with the option off") + } + time.Sleep(200 * time.Millisecond) + if _, found := r.recordOn(t, r.cell.ID); found { + t.Fatal("a record appeared before the turn was sealed with the option off") + } + r.sealsAsTheWindowDoes(t, d) + r.durable(r.cell.ID, r.cell) + if _, found := r.recordOn(t, r.cell.ID); !found { + t.Fatal("the sealed turn did not make the record") + } + }) + } +} + +// A chat that already has a head is served by the record made from that head +// (drive_early_record_test.go) and asks for nothing. +func TestAChatWithAHeadAlreadyAsksForNoOther(t *testing.T) { + r := newTwoHomes(t) + d := startupChat(t, r, func() bool { return true }) + appendTo(t, transcriptOf(r.cell), `{"type":"message","role":"user","content":"hello"}`+"\n") + d.Working(true) + if d.EarlyHeadOwed() { + t.Fatal("a chat with a head asked for another") + } +} + +// C1 and C4 with relay storage off and blind pass-through the road, which is +// the hosted default: the record appears while the turn runs, carries no title +// or folder, and the relay is sent no object. +func TestTheEarlyRecordOfANewChatSendsNothingButTheRecordWhilePassThroughIsTheRoad(t *testing.T) { + r := newLiveRig(t) + d := freshChat(t, r.twoHomes, func() bool { return true }) + appendTo(t, transcriptOf(r.cell), `{"type":"message","role":"user","content":"the first words"}`+"\n") + d.Working(true) + if !d.EarlyHeadOwed() { + t.Fatal("the first spoken turn of a chat with no head did not ask for one") + } + r.sealsAsTheWindowDoes(t, d) + waitFor(t, "the working chat's record on the other computer", func() bool { + view, found := r.recordOn(t, r.cell.ID) + return found && view.Cell.Lease.Working + }) + view, _ := r.recordOn(t, r.cell.ID) + if view.Cell.Title != "" || view.Cell.Folder != "" { + t.Fatalf("the early record carries a title %q or folder %q", view.Cell.Title, view.Cell.Folder) + } + if named := r.wire.recordsWithNames(); len(named) != 0 { + t.Fatalf("a record carried a name: %v", named) + } + if n := r.wire.storeWrites(); n != 0 { + t.Fatalf("the relay was sent %d objects while pass-through was the road", n) + } +} diff --git a/internal/syncsetup/drive_early_record_test.go b/internal/syncsetup/drive_early_record_test.go new file mode 100644 index 0000000000..9e19dfa9a3 --- /dev/null +++ b/internal/syncsetup/drive_early_record_test.go @@ -0,0 +1,202 @@ +package syncsetup + +import ( + "bytes" + "errors" + "os" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/cellstore" + "github.com/Agent-Field/codeaf/internal/directory" +) + +// These tests are the early directory record of remote control (contract E1 to +// E6 in NOTES-POLISH). A chat appears on the other computers' Home only once its +// directory record exists, and the record has always been created by the first +// SEALED turn, so a chat whose first turn was still running appeared nowhere. With +// the option on, the turn's START creates the record from the head the window +// already sealed at startup; with it off, nothing here changes by a byte. + +// startupChat is a window that has just opened a chat: the startup head is +// sealed (bookkeeping only, nobody has spoken yet) and the drive is up. +func startupChat(t *testing.T, r *twoHomes, early func() bool) *Drive { + t.Helper() + ctx := t.Context() + d, err := r.a.Drive(ctx, r.engine, r.cell, DriveOptions{EarlyRecord: early}) + mustNil(t, err) + t.Cleanup(func() { _ = d.Close(ctx) }) + appendTo(t, transcriptOf(r.cell), `{"type":"session","version":1,"id":"early"}`+"\n") + _, err = d.Store(r.engine).Seal(ctx, r.cell, cellstore.TurnInfo{}) + mustNil(t, err) + d.CatchUp() + return d +} + +func (r *twoHomes) recordOn(t *testing.T, id string) (directory.CellView, bool) { + t.Helper() + view, err := r.b.Dir.Cell(t.Context(), id) + if errors.Is(err, directory.ErrNotFound) { + return view, false + } + mustNil(t, err) + return view, true +} + +// E1, E2, E4: with the option on, the first turn's START puts the chat on the +// other computer's list as working, from the head the window sealed at startup +// and carrying no words of the turn; when the turn ends the row moves on as it +// always did, head first and the working flag clearing after. +func TestTheFirstTurnStartingCreatesTheDirectoryRecordWhenTheOptionIsOn(t *testing.T) { + r := newTwoHomes(t) + ctx := t.Context() + d := startupChat(t, r, func() bool { return true }) + startup := r.head() + if _, found := r.recordOn(t, r.cell.ID); found { + t.Fatal("a chat nobody has spoken in has a record before its turn started") + } + + // The person's message is journaled before the turn goroutine starts, and the + // turn tells the drive it is working. Nothing has been sealed since startup. + appendTo(t, transcriptOf(r.cell), `{"type":"message","role":"user","content":"hello"}`+"\n") + d.Working(true) + + waitFor(t, "the working chat's record on the other computer", func() bool { + view, found := r.recordOn(t, r.cell.ID) + return found && view.Cell.Lease.Working + }) + view, _ := r.recordOn(t, r.cell.ID) + if view.Cell.Head != startup { + t.Fatalf("the early record carries head %s, want the startup head %s", view.Cell.Head, startup) + } + if view.Cell.Lease.Device != r.a.Device.ID() { + t.Fatalf("the early record is held by %q, want this computer", view.Cell.Lease.Device) + } + if view.Cell.Title != "" { + t.Fatalf("the early record carries the title %q before anything was named", view.Cell.Title) + } + rows, err := r.b.Rows(ctx) + mustNil(t, err) + if len(rows) != 1 || rows[0].Cell != r.cell.ID { + t.Fatalf("the other computer lists %+v, want the one working chat", rows) + } + + // The turn ends: the head advances to the sealed turn and working clears. + appendTo(t, transcriptOf(r.cell), `{"type":"message","role":"assistant","content":"hi"}`+"\n") + _, err = d.Store(r.engine).Seal(ctx, r.cell, cellstore.TurnInfo{}) + mustNil(t, err) + d.Working(false) + r.durable(r.cell.ID, r.cell) + waitFor(t, "the working flag to clear", func() bool { + view, found := r.recordOn(t, r.cell.ID) + return found && !view.Cell.Lease.Working + }) + if view, _ := r.recordOn(t, r.cell.ID); view.Cell.Head == startup { + t.Fatal("the head did not move on when the first turn ended") + } +} + +// E3: a turn that started with nothing the person said (a bookkeeping +// start) appears nowhere, option on or not. No untitled chats. +func TestAChatNobodyHasSpokenInHasNoEarlyRecord(t *testing.T) { + r := newTwoHomes(t) + d := startupChat(t, r, func() bool { return true }) + d.Working(true) + if n := d.batcher.Pending(); n != 0 { + t.Fatalf("a chat nobody spoke in has %d turns waiting to be published", n) + } + d.Working(false) + mustNil(t, d.Close(t.Context())) + if _, found := r.recordOn(t, r.cell.ID); found { + t.Fatal("a chat nobody has spoken in appeared on the other computer") + } + rows, err := r.b.Rows(t.Context()) + mustNil(t, err) + if len(rows) != 0 { + t.Fatalf("the other computer lists an unused chat: %+v", rows) + } +} + +// E6: with the option off, or never given, the first turn starting publishes +// nothing: the record still appears only when the first turn is sealed, as it +// does today, and the startup head is not published from an unsealed message. +func TestWithTheOptionOffTheFirstTurnStartingPublishesNothing(t *testing.T) { + for name, early := range map[string]func() bool{ + "not given": nil, + "off": func() bool { return false }, + } { + t.Run(name, func(t *testing.T) { + r := newTwoHomes(t) + d := startupChat(t, r, early) + appendTo(t, transcriptOf(r.cell), `{"type":"message","role":"user","content":"hello"}`+"\n") + d.Working(true) + if n := d.batcher.Pending(); n != 0 { + t.Fatalf("the first turn starting queued %d turns with the option off", n) + } + d.Working(false) + mustNil(t, d.Close(t.Context())) + if view, found := r.recordOn(t, r.cell.ID); found { + t.Fatalf("a record appeared before any turn was sealed: head=%s", view.Cell.Head) + } + }) + } +} + +// E6, read the other way: the option is read when the turn starts, not once +// at startup, so turning remote control off between chats stops the early +// record on the very next turn. +func TestTheEarlyRecordFollowsTheOptionAtTheMomentTheTurnStarts(t *testing.T) { + r := newTwoHomes(t) + on := true + d := startupChat(t, r, func() bool { return on }) + on = false + appendTo(t, transcriptOf(r.cell), `{"type":"message","role":"user","content":"hello"}`+"\n") + d.Working(true) + if n := d.batcher.Pending(); n != 0 { + t.Fatalf("a turn that started after the option went off queued %d turns", n) + } +} + +// The advisor's check, and the one risk the early record adds (NOTES-POLISH, +// G3): the row exists while only the startup head is behind it, so another +// computer could land on it. A chat held by a computer that is alive and working +// is never taken silently, and once that computer has died and its lease has +// lapsed the open is still refused until the person confirms the card, as for +// every lapsed chat. In neither case does anything touch the words the first +// turn journaled on the computer that spoke them. +func TestAnEarlyRecordIsNotTakenSilentlyAndTheWordsStayWhereTheyWereSpoken(t *testing.T) { + r := newTwoHomes(t) + ctx := t.Context() + d := startupChat(t, r, func() bool { return true }) + appendTo(t, transcriptOf(r.cell), `{"type":"message","role":"user","content":"the only copy of these words"}`+"\n") + d.Working(true) + waitFor(t, "the working chat's record", func() bool { + view, found := r.recordOn(t, r.cell.ID) + return found && view.Cell.Lease.Working + }) + words, err := os.ReadFile(transcriptOf(r.cell)) + mustNil(t, err) + seen, _ := r.recordOn(t, r.cell.ID) + expect := &directory.LeaseExpectation{Device: seen.Cell.Lease.Device, Fence: seen.Cell.Lease.Fence} + continuer := r.continuerB() + + // A is alive and working: the free-chat open is refused as held. + if _, err := continuer.OpenAvailable(ctx, r.cell.ID, expect); !errors.Is(err, directory.ErrLeaseHeld) { + t.Fatalf("the other computer opened a chat that is working here: %v", err) + } + + // A dies in the middle of the first turn and its lease lapses. The row is + // still not opened without the card. + d.cancel() + <-d.done + r.clock.advance(directory.LeaseTTL + time.Second) + if _, err := continuer.OpenAvailable(ctx, r.cell.ID, expect); !errors.Is(err, directory.ErrLeaseHeld) { + t.Fatalf("the other computer opened the lapsed early record without the card: %v", err) + } + + after, err := os.ReadFile(transcriptOf(r.cell)) + mustNil(t, err) + if !bytes.Equal(words, after) || !bytes.Contains(after, []byte("the only copy of these words")) { + t.Fatal("the words the first turn journaled were changed") + } +} diff --git a/internal/syncsetup/firstrun.go b/internal/syncsetup/firstrun.go index e3c7daca8c..7386212821 100644 --- a/internal/syncsetup/firstrun.go +++ b/internal/syncsetup/firstrun.go @@ -19,7 +19,7 @@ func FirstRunLineFor(relayURL string) string { if u, err := url.Parse(shown); err == nil && u.Host != "" { shown = u.Host + strings.TrimRight(u.Path, "/") } - return "Your chats sync end-to-end encrypted through codeaf's fabric (" + shown + "), a sync service that only ever sees ciphertext; turn that off with CODEAF_SYNC_URL=off, or use your own with CODEAF_SYNC_URL=." + return "Your chats sync end-to-end encrypted through codeaf's fabric (" + shown + "), a relay that only ever sees ciphertext; turn that off with CODEAF_SYNC_URL=off, or use your own with CODEAF_SYNC_URL=." } // FirstRunLine is the first-run sentence for this binary's hosted sync service. diff --git a/internal/syncsetup/live_control_test.go b/internal/syncsetup/live_control_test.go new file mode 100644 index 0000000000..5afce76da8 --- /dev/null +++ b/internal/syncsetup/live_control_test.go @@ -0,0 +1,744 @@ +package syncsetup + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net/http" + "os" + "path/filepath" + "reflect" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/filelock" + "github.com/Agent-Field/codeaf/internal/filesdoor" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/home" + "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/pair" + relaypkg "github.com/Agent-Field/codeaf/internal/relay" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" +) + +// stubLiveAgent embeds remote.WrappedAgent so only the methods exercised by a +// live viewer turn are implemented and any unexpected call panics into the +// server's recovery. +type stubLiveAgent struct { + remote.WrappedAgent + title string + replyTexts []string + + mu sync.Mutex + submitted []string +} + +func (a *stubLiveAgent) Submit(_ context.Context, text string) (<-chan session.Event, error) { + a.mu.Lock() + a.submitted = append(a.submitted, text) + replies := slices.Clone(a.replyTexts) + a.mu.Unlock() + + ch := make(chan session.Event, len(replies)) + for _, part := range replies { + ch <- session.Event{Kind: session.EventTextDelta, Text: part} + } + close(ch) + return ch, nil +} + +func (a *stubLiveAgent) Interrupt() {} +func (a *stubLiveAgent) InterruptFor(session.StopDoor) {} +func (a *stubLiveAgent) Close() error { return nil } +func (a *stubLiveAgent) Model() string { return "stub-live-model" } +func (a *stubLiveAgent) Title() string { return a.title } +func (a *stubLiveAgent) Usage() session.Usage { return session.Usage{} } +func (a *stubLiveAgent) ContextTokens() int { return 0 } +func (a *stubLiveAgent) ReasoningLevels() map[string]string { return nil } +func (a *stubLiveAgent) Transcript() []session.DisplayEntry { return nil } +func (a *stubLiveAgent) EarlierHistory() session.EarlierHistory { return session.EarlierHistory{} } +func (a *stubLiveAgent) RewindPoints() []session.RewindPoint { return nil } +func (a *stubLiveAgent) RewindAt(int) ([]session.DisplayEntry, error) { return nil, nil } + +func (a *stubLiveAgent) submissions() []string { + a.mu.Lock() + defer a.mu.Unlock() + return slices.Clone(a.submitted) +} + +// shortHostHome symlinks r.homeA into a short /tmp/ld-* path so Unix domain +// sockets created under /v3/live/.sock stay well below the 103-byte +// sun_path limit regardless of the test function name length. +func shortHostHome(t *testing.T, r *liveRig) string { + t.Helper() + shortDir, err := os.MkdirTemp("/tmp", "ld-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(shortDir) }) + shortHome := filepath.Join(shortDir, "a") + if err := os.Symlink(r.homeA, shortHome); err != nil { + t.Fatal(err) + } + r.homeA = shortHome + r.a.Home = shortHome + return shortHome +} + +// hostHeldChat sets up a running chat on r.a backed by livedoor.Listen and a +// locked transcript plus presence file so livedoor.NewResolver routes live +// channels to it without starting a daemon. +func hostHeldChat(t *testing.T, r *liveRig, chatID string, agent *stubLiveAgent) (*remote.Session, string) { + t.Helper() + shortHostHome(t, r) + chatDir := filepath.Join(r.a.Home, "v3", "projects", "bucket", chatID) + if err := os.MkdirAll(chatDir, 0o700); err != nil { + t.Fatal(err) + } + transcript := (session.Place{Dir: chatDir}).Transcript() + lockFile, err := os.OpenFile(transcript, os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + t.Fatal(err) + } + if err := filelock.Lock(lockFile, true, true); err != nil { + _ = lockFile.Close() + t.Fatalf("locking transcript %q: %v", transcript, err) + } + t.Cleanup(func() { + _ = filelock.Unlock(lockFile) + _ = lockFile.Close() + }) + + presenceRaw, err := json.Marshal(session.SessionPresence{ + Schema: 1, + SessionID: chatID, + Workspace: r.work, + PID: os.Getpid(), + UpdatedAt: time.Now(), + State: session.PresenceIdle, + }) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(chatDir, "presence.json"), presenceRaw, 0o600); err != nil { + t.Fatal(err) + } + + sess := remote.NewSession(&remote.Engine{ + Agent: agent, + Workspace: r.work, + SessionFile: transcript, + }, true) + t.Cleanup(func() { _ = sess.Close() }) + + ln, err := livedoor.Listen(r.a.Home, func(target string) (*remote.Session, bool) { + if filepath.Clean(target) == filepath.Clean(transcript) { + return sess, true + } + return nil, false + }, nil) + if err != nil { + t.Fatalf("livedoor.Listen: %v", err) + } + t.Cleanup(func() { _ = ln.Close() }) + + return sess, transcript +} + +func allowViewerDrive(t *testing.T, r *liveRig) { + t.Helper() + on := true + mustNil(t, pair.Permits().Set(r.a.Identity.ID(), r.b.Device.ID(), &on, &on, "person")) +} + +// TestAMessageTypedOnTheViewerReachesTheHostAndTheReplyShowsOnBothWithStorageOff +// verifies contract V3: with storage off on both homes, a viewer connected via +// Sync.LiveLink and remote.Roam submits a message that reaches the host's held +// session stub agent once, the stub's reply events reach both the viewer and +// the host's own attached surface, zero /v1/store/* requests are made, and at +// least one dial carries header Codeaf-Door: live. +func TestAMessageTypedOnTheViewerReachesTheHostAndTheReplyShowsOnBothWithStorageOff(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + r := newLiveRig(t) + allowViewerDrive(t, r) + + stub := &stubLiveAgent{ + title: "Live Hosted Chat", + replyTexts: []string{"reply-part-1", "reply-part-2"}, + } + sess, transcript := hostHeldChat(t, r, r.cell.ID, stub) + + // Attach the host's own local surface to the same persistent session. + hostSurface, err := remote.LoopbackAttach(remote.Hello{ + Workspace: r.work, + Session: transcript, + Surface: nameA, + Join: true, + }, remote.AttachOptions{ + Open: func(remote.Hello) (*remote.Session, error) { + return sess, nil + }, + }) + if err != nil { + t.Fatalf("LoopbackAttach on host: %v", err) + } + t.Cleanup(func() { _ = hostSurface.Close() }) + + r.a.ensureFilesDoor() + + link := r.b.LiveLink(r.a.Device.ID(), nameA, func() bool { return true }, nil) + t.Cleanup(link.Close) + + var viewerClient *remote.Client + waitFor(t, "the viewer to connect to the host's live door", func() bool { + c, dialErr := remote.Roam(nameA, remote.Hello{ + Surface: nameB, + Join: true, + }, remote.Roaming{ + Dial: link.Opener(r.cell.ID), + }) + if dialErr != nil { + return false + } + viewerClient = c + return true + }) + t.Cleanup(func() { _ = viewerClient.Close() }) + + if !viewerClient.Driver().Yours { + if err := viewerClient.Take(); err != nil { + t.Fatalf("viewerClient.Take: %v", err) + } + } + + const prompt = "hello from the viewer with storage off" + viewerEvents, err := viewerClient.Agent().Submit(context.Background(), prompt) + if err != nil { + t.Fatalf("viewer Submit: %v", err) + } + + var viewerGot []string + for ev := range viewerEvents { + if ev.Kind == session.EventTextDelta { + viewerGot = append(viewerGot, ev.Text) + } + } + if !slices.Equal(viewerGot, stub.replyTexts) { + t.Fatalf("viewer received reply deltas %v, want %v", viewerGot, stub.replyTexts) + } + + select { + case hostTurn := <-hostSurface.Client.Follow(): + if hostTurn.Said != prompt { + t.Fatalf("host surface saw prompt %q, want %q", hostTurn.Said, prompt) + } + var hostGot []string + for ev := range hostTurn.Events { + if ev.Kind == session.EventTextDelta { + hostGot = append(hostGot, ev.Text) + } + } + if !slices.Equal(hostGot, stub.replyTexts) { + t.Fatalf("host surface received reply deltas %v, want %v", hostGot, stub.replyTexts) + } + case <-time.After(5 * time.Second): + t.Fatal("host surface did not receive the followed turn from the viewer") + } + + if got := stub.submissions(); !slices.Equal(got, []string{prompt}) { + t.Fatalf("stub agent submissions = %v, want exactly [%q]", got, prompt) + } + + for _, e := range r.wire.snapshot() { + if strings.HasPrefix(e.Path, "/v1/store") { + t.Fatalf("unexpected store request during live session: %s %s", e.Method, e.Path) + } + } + if !bytes.Contains(r.tap.bytes(), []byte("Codeaf-Door: live")) { + t.Fatal("wire tap saw no dial with header Codeaf-Door: live") + } +} + +// TestALiveSessionAddsNoStoredObjectAtTheRelay verifies contract V5: across an +// entire live session, the relay request log contains no /v1/store path and no +// write to any per-chat record route. +func TestALiveSessionAddsNoStoredObjectAtTheRelay(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + r := newLiveRig(t) + allowViewerDrive(t, r) + + stub := &stubLiveAgent{ + title: "Zero Relay Storage Chat", + replyTexts: []string{"delta-one", "delta-two"}, + } + hostHeldChat(t, r, r.cell.ID, stub) + r.a.ensureFilesDoor() + + before := len(r.wire.snapshot()) + + link := r.b.LiveLink(r.a.Device.ID(), nameA, func() bool { return true }, nil) + t.Cleanup(link.Close) + + var viewerClient *remote.Client + waitFor(t, "the viewer to connect to the host's live door", func() bool { + c, err := remote.Roam(nameA, remote.Hello{ + Surface: nameB, + Join: true, + }, remote.Roaming{ + Dial: link.Opener(r.cell.ID), + }) + if err != nil { + return false + } + viewerClient = c + return true + }) + + if !viewerClient.Driver().Yours { + mustNil(t, viewerClient.Take()) + } + events, err := viewerClient.Agent().Submit(context.Background(), "check relay writes") + mustNil(t, err) + for range events { + } + _ = viewerClient.Close() + link.Close() + + for _, e := range r.wire.snapshot()[before:] { + if strings.HasPrefix(e.Path, "/v1/store") { + t.Fatalf("relay saw store request %s %s during live session", e.Method, e.Path) + } + if e.Method != http.MethodGet && strings.HasPrefix(e.Path, "/v1/dir/cells") { + t.Fatalf("relay saw per-chat record write %s %s during live session", e.Method, e.Path) + } + } +} + +// TestAViewerDoesNotChangeTheHostsLeaseTraffic verifies contract V5: the set of +// relay request paths and counts the host makes for lease traffic +// (heartbeat/publish) over a fixed window is identical with and without an +// attached viewer. +func TestAViewerDoesNotChangeTheHostsLeaseTraffic(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + + measureLeaseTraffic := func(t *testing.T, withViewer bool) map[string]int { + t.Helper() + r := newLiveRig(t) + allowViewerDrive(t, r) + stub := &stubLiveAgent{ + title: "Lease Traffic Chat", + replyTexts: []string{"live-reply"}, + } + hostHeldChat(t, r, r.cell.ID, stub) + seedLiveTree(t, r.work) + a := r.openA() + a.mustSay("first host turn") + r.durable(r.cell.ID, r.cell) + r.a.ensureFilesDoor() + + if withViewer { + link := r.b.LiveLink(r.a.Device.ID(), nameA, func() bool { return true }, nil) + t.Cleanup(link.Close) + + var viewerClient *remote.Client + waitFor(t, "the viewer to attach", func() bool { + c, err := remote.Roam(nameA, remote.Hello{ + Surface: nameB, + Join: true, + }, remote.Roaming{ + Dial: link.Opener(r.cell.ID), + }) + if err != nil { + return false + } + viewerClient = c + return true + }) + t.Cleanup(func() { _ = viewerClient.Close() }) + + if !viewerClient.Driver().Yours { + mustNil(t, viewerClient.Take()) + } + evCh, err := viewerClient.Agent().Submit(context.Background(), "viewer turn while host holds lease") + mustNil(t, err) + for range evCh { + } + } + + // Record the host's lease traffic (publish/heartbeat) across a second + // durable turn on the host. + start := len(r.wire.snapshot()) + a.mustSay("second host turn") + r.durable(r.cell.ID, r.cell) + + counts := map[string]int{} + for _, e := range r.wire.snapshot()[start:] { + if strings.HasPrefix(e.Path, "/v1/dir/cells/") { + parts := strings.Split(strings.TrimPrefix(e.Path, "/v1/dir/cells/"), "/") + route := "/v1/dir/cells/{id}" + if len(parts) > 1 { + route += "/" + parts[len(parts)-1] + } + counts[e.Method+" "+route]++ + } + } + return counts + } + + withoutViewer := measureLeaseTraffic(t, false) + withViewer := measureLeaseTraffic(t, true) + if len(withoutViewer) == 0 { + t.Fatal("host recorded no lease traffic in baseline window") + } + if !reflect.DeepEqual(withoutViewer, withViewer) { + t.Fatalf("host lease traffic changed with an attached viewer:\nwithout viewer: %v\nwith viewer: %v", withoutViewer, withViewer) + } +} + +// TestRemovingADeviceClosesItsLiveViewThroughTheRealDirectoryPath verifies +// contract V10: removing the viewer from the roster through the directory +// client ends the viewer's channel with ReasonRemoved within the roster TTL, +// and livedoor.NotifyRemoved closes an open live view at once. +func TestRemovingADeviceClosesItsLiveViewThroughTheRealDirectoryPath(t *testing.T) { + t.Run("directory revocation closes within roster TTL", func(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + r := newLiveRig(t) + liveDoorRosterFor = 20 * time.Millisecond + + stub := &stubLiveAgent{title: "Revoke Directory Chat"} + hostHeldChat(t, r, r.cell.ID, stub) + r.a.ensureFilesDoor() + + endedCh := make(chan string, 1) + link := r.b.LiveLink(r.a.Device.ID(), nameA, func() bool { return true }, nil) + t.Cleanup(link.Close) + link.OnChannelEnd(func(_, reason string) { + select { + case endedCh <- reason: + default: + } + }) + + var viewerClient *remote.Client + waitFor(t, "the viewer to open the live chat", func() bool { + c, err := remote.Roam(nameA, remote.Hello{ + Surface: nameB, + Join: true, + }, remote.Roaming{ + Dial: link.Opener(r.cell.ID), + }) + if err != nil { + return false + } + viewerClient = c + return true + }) + t.Cleanup(func() { _ = viewerClient.Close() }) + + // Remove the viewer through the real directory client without calling + // NotifyRemoved directly; the pull backstop must close the view with + // ReasonRemoved within the shrunk roster TTL. + mustNil(t, r.a.Dir.Revoke(context.Background(), r.b.Device.ID())) + + select { + case reason := <-endedCh: + if reason != livedoor.ReasonRemoved { + t.Fatalf("viewer channel ended with reason %q, want %q", reason, livedoor.ReasonRemoved) + } + case <-time.After(2 * time.Second): + t.Fatal("viewer channel did not end within the roster TTL after directory revocation") + } + waitFor(t, "the link state to reach Revoked", func() bool { + st := link.State() + return st.Kind == livedoor.Revoked && st.Reason == livedoor.ReasonRemoved + }) + }) + + t.Run("NotifyRemoved closes at once without waiting for the roster TTL", func(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + r := newLiveRig(t) + // Set a long roster TTL so only NotifyRemoved can close the channel now. + liveDoorRosterFor = 10 * time.Second + + stub := &stubLiveAgent{title: "NotifyRemoved Chat"} + hostHeldChat(t, r, r.cell.ID, stub) + r.a.ensureFilesDoor() + + endedCh := make(chan string, 1) + link := r.b.LiveLink(r.a.Device.ID(), nameA, func() bool { return true }, nil) + t.Cleanup(link.Close) + link.OnChannelEnd(func(_, reason string) { + select { + case endedCh <- reason: + default: + } + }) + + var viewerClient *remote.Client + waitFor(t, "the viewer to open the live chat", func() bool { + c, err := remote.Roam(nameA, remote.Hello{ + Surface: nameB, + Join: true, + }, remote.Roaming{ + Dial: link.Opener(r.cell.ID), + }) + if err != nil { + return false + } + viewerClient = c + return true + }) + t.Cleanup(func() { _ = viewerClient.Close() }) + + livedoor.NotifyRemoved(r.a.Home, r.b.Device.ID()) + + select { + case reason := <-endedCh: + if reason != livedoor.ReasonRemoved { + t.Fatalf("viewer channel ended with reason %q, want %q", reason, livedoor.ReasonRemoved) + } + case <-time.After(time.Second): + t.Fatal("livedoor.NotifyRemoved did not close the viewer channel at once") + } + }) +} + +// TestTheDoorStartsForRemoteControlEvenWithStorageOffAndNoPassThrough verifies +// the door start condition: when storage is off and blind pass-through is +// switched off, turning remote control on still starts the door so a paired +// viewer can dial live. +func TestTheDoorStartsForRemoteControlEvenWithStorageOffAndNoPassThrough(t *testing.T) { + r := newLiveRig(t) + t.Setenv(LiveTransferVar, "off") + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + + if r.a.liveCarries() { + t.Fatal("liveCarries() is true with CODEAF_PASSTHROUGH=off") + } + if !r.a.remoteControlWanted() { + t.Fatal("remoteControlWanted() is false with CODEAF_REMOTE_CONTROL=on and another paired device") + } + + r.a.ensureFilesDoor() + + waitFor(t, "the host door to register at the relay for remote control", func() bool { + tun, err := filesdoor.DialLive(context.Background(), r.a.Relay, r.b.Identity, r.b.Device, r.a.Device.ID()) + if err != nil { + return false + } + _ = tun.Close() + return true + }) +} + +// TestTheDoorDoesNotStartWhenRemoteControlIsOffAndPassThroughIsOff verifies the +// door start condition: when both blind pass-through and remote control are +// switched off, ensureFilesDoor starts no door and makes no relay registration. +func TestTheDoorDoesNotStartWhenRemoteControlIsOffAndPassThroughIsOff(t *testing.T) { + r := newLiveRig(t) + t.Setenv(LiveTransferVar, "off") + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + + if r.a.liveCarries() { + t.Fatal("liveCarries() is true with CODEAF_PASSTHROUGH=off") + } + if r.a.remoteControlWanted() { + t.Fatal("remoteControlWanted() is true with CODEAF_REMOTE_CONTROL=off") + } + + beforeReg := r.wire.registrations() + r.a.ensureFilesDoor() + + filesDoors.Lock() + _, running := filesDoors.runs[r.a.Home] + filesDoors.Unlock() + if running { + t.Fatal("ensureFilesDoor started a door run with both pass-through and remote control off") + } + if got := r.wire.registrations(); got != beforeReg { + t.Fatalf("relay registrations = %d, want %d (no registration)", got, beforeReg) + } + if _, err := filesdoor.DialLive(context.Background(), r.a.Relay, r.b.Identity, r.b.Device, r.a.Device.ID()); !errors.Is(err, relaypkg.ErrNoMachine) { + t.Fatalf("DialLive = %v, want relay.ErrNoMachine", err) + } +} + +// TestRemoteControlNeverChangesHowChatsSync verifies that toggling +// CODEAF_REMOTE_CONTROL on and off never alters liveCarries, LiveTransfer, +// ChatStorageOff, or the Scope returned by chatScope. +func TestRemoteControlNeverChangesHowChatsSync(t *testing.T) { + r := newLiveRig(t) + for _, passthrough := range []string{"on", "off"} { + t.Setenv(LiveTransferVar, passthrough) + + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + carriesOff := r.a.liveCarries() + transferOff := r.a.LiveTransfer() + storageOff := r.a.ChatStorageOff() + scopeOff := r.a.chatScope(r.cell.ID) + + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + carriesOn := r.a.liveCarries() + transferOn := r.a.LiveTransfer() + storageOn := r.a.ChatStorageOff() + scopeOn := r.a.chatScope(r.cell.ID) + + if carriesOff != carriesOn || transferOff != transferOn || storageOff != storageOn { + t.Fatalf("passthrough=%s: sync predicates changed with CODEAF_REMOTE_CONTROL: off=(%v,%v,%v) on=(%v,%v,%v)", + passthrough, carriesOff, transferOff, storageOff, carriesOn, transferOn, storageOn) + } + if (scopeOff.live != nil) != (scopeOn.live != nil) || reflect.TypeOf(scopeOff.Store) != reflect.TypeOf(scopeOn.Store) { + t.Fatalf("passthrough=%s: chatScope store changed with CODEAF_REMOTE_CONTROL: off=%T (live=%v) on=%T (live=%v)", + passthrough, scopeOff.Store, scopeOff.live != nil, scopeOn.Store, scopeOn.live != nil) + } + } +} + +// TestTheFirstFullRosterReadSnapshotsTheLegacyDevicesOnce verifies contract +// (legacy snapshot): the first full roster read for a non-solo identity writes +// the two existing devices into the legacy snapshot once, a third device that +// joins later resolves to ClassNew with drive on, and a second process-level +// read does not rewrite the permit book. +func TestTheFirstFullRosterReadSnapshotsTheLegacyDevicesOnce(t *testing.T) { + r := newLiveRig(t) + idID := r.a.Identity.ID() + book := pair.Permits() + + for _, devID := range []string{r.a.Device.ID(), r.b.Device.ID()} { + p, class := book.For(idID, devID) + if !p.Watch || p.Drive || class != pair.ClassLegacy { + t.Fatalf("For(%q) after first roster read = (%+v, %v), want Watch=true Drive=false ClassLegacy", devID, p, class) + } + } + + permitPath := filepath.Join(home.Dir(), "v3", "remote", "permits.json") + beforeBytes, err := os.ReadFile(permitPath) + if err != nil { + t.Fatalf("ReadFile(%q): %v", permitPath, err) + } + + // Add a third device to the directory after the initial snapshot. + homeC := t.TempDir() + if _, err := identity.Adopt(homeC, r.a.Identity, false); err != nil { + t.Fatal(err) + } + syncC := openSync(t, homeC) + ctx := context.Background() + mustNil(t, syncC.putDevice(ctx, "tablet")) + + // A second full roster read in this process must not rewrite permits.json, + // and the new device must be ClassNew (Watch:true, Drive:true). + if _, err := r.a.Dir.List(ctx); err != nil { + t.Fatal(err) + } + afterBytes, err := os.ReadFile(permitPath) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(beforeBytes, afterBytes) { + t.Fatalf("second roster read rewrote permits.json:\nbefore: %s\nafter: %s", beforeBytes, afterBytes) + } + + pNew, classNew := book.For(idID, syncC.Device.ID()) + if !pNew.Watch || !pNew.Drive || classNew != pair.ClassNew { + t.Fatalf("For(later device %q) = (%+v, %v), want Watch=true Drive=true ClassNew", syncC.Device.ID(), pNew, classNew) + } +} + +// TestAPermitEditedByAnotherProcessReachesAnOpenViewWithinTheWatchInterval +// verifies contract V10/V11: when another process turns Drive off in +// permits.json on disk, the door's PermitBook.Watch goroutine notifies the live +// registry within the watch interval and the viewer's open channel ends with +// permit-changed. +func TestAPermitEditedByAnotherProcessReachesAnOpenViewWithinTheWatchInterval(t *testing.T) { + oldInterval := livePermitWatchEvery + livePermitWatchEvery = 15 * time.Millisecond + t.Cleanup(func() { livePermitWatchEvery = oldInterval }) + + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + r := newLiveRig(t) + allowViewerDrive(t, r) + + stub := &stubLiveAgent{title: "Permit Watch Chat"} + hostHeldChat(t, r, r.cell.ID, stub) + r.a.ensureFilesDoor() + + endedCh := make(chan string, 1) + link := r.b.LiveLink(r.a.Device.ID(), nameA, func() bool { return true }, nil) + t.Cleanup(link.Close) + link.OnChannelEnd(func(_, reason string) { + select { + case endedCh <- reason: + default: + } + }) + + openCh := link.Opener(r.cell.ID) + var ch interface { + Read([]byte) (int, error) + Write([]byte) (int, error) + Close() error + } + waitFor(t, "the viewer to open a drive-capable channel", func() bool { + rwc, err := openCh() + if err != nil { + return false + } + ch = rwc + return true + }) + t.Cleanup(func() { _ = ch.Close() }) + + helloPayload, err := json.Marshal(remote.Hello{Version: remote.Version, Join: true}) + mustNil(t, err) + helloFrame, err := json.Marshal(remote.Frame{Kind: "hello", Payload: helloPayload}) + mustNil(t, err) + if _, err := ch.Write(append(helloFrame, '\n')); err != nil { + t.Fatalf("writing viewer hello: %v", err) + } + + readDone := make(chan error, 1) + guard.Go("syncsetup.test.permitWatchRead", func() { + buf := make([]byte, 4096) + // First read consumes the welcome line; subsequent read waits for the + // channel reset when Drive is turned off on disk. + for { + _, rErr := ch.Read(buf) + if rErr != nil { + readDone <- rErr + return + } + } + }) + + // Wait until the link reports Live (Drive:true) before editing permits.json. + waitFor(t, "the link state to report Live with Drive:true", func() bool { + st := link.State() + return st.Kind == livedoor.Live && st.Permit.Drive + }) + + // Another PermitBook instance (simulating the CLI in another process) turns + // Drive off on disk. + driveOff := false + otherProcessBook := pair.Permits() + mustNil(t, otherProcessBook.Set(r.a.Identity.ID(), r.b.Device.ID(), nil, &driveOff, "person")) + + select { + case reason := <-endedCh: + if reason != livedoor.ReasonPermitChanged { + t.Fatalf("channel ended with reason %q, want %q", reason, livedoor.ReasonPermitChanged) + } + case rErr := <-readDone: + if reason, ok := livedoor.ReasonOf(rErr); !ok || reason != livedoor.ReasonPermitChanged { + t.Fatalf("channel read ended with %v (reason=%q), want %q", rErr, reason, livedoor.ReasonPermitChanged) + } + case <-time.After(2 * time.Second): + t.Fatal("open channel was not reset with permit-changed within the watch interval") + } +} diff --git a/internal/syncsetup/livetransfer.go b/internal/syncsetup/livetransfer.go index 96000ea62c..110cb1cacf 100644 --- a/internal/syncsetup/livetransfer.go +++ b/internal/syncsetup/livetransfer.go @@ -35,9 +35,13 @@ import ( "time" "github.com/Agent-Field/codeaf/internal/blobstore" + "github.com/Agent-Field/codeaf/internal/config" "github.com/Agent-Field/codeaf/internal/env" "github.com/Agent-Field/codeaf/internal/filesdoor" + "github.com/Agent-Field/codeaf/internal/guard" "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/pair" "github.com/Agent-Field/codeaf/internal/syncwords" ) @@ -280,36 +284,113 @@ var filesDoors = struct { }{runs: map[string]*doorRun{}} type doorRun struct { - stop context.CancelFunc - done chan struct{} + stop context.CancelFunc + done chan struct{} + remoteControl bool } // ensureFilesDoor starts this home's files door in this process if it is not // running. Which process of the home actually registers is decided by the lock -// inside the door, so every codeaf process may call this. +// inside the door, so every codeaf process may call this. It is also what ends +// the remote-control part of a door: the person turning remote control off is +// seen at the next call, which the watch loop of [StartLiveTransfer] makes at +// least every [liveWatchEvery] in every process that opens chats, with or +// without live transfer. func (s *Sync) ensureFilesDoor() { - if !s.liveCarries() { + wantRC := config.RemoteControlOn() + if !s.liveCarries() && !s.remoteControlWanted() { + // THE DOOR HAS NO REASON TO RUN, and the one case that needs ending is a + // run that is serving remote control the person has just turned off: + // without this, the early return left it up, and every view already open + // on it stayed connected until the process quit. A run that was never + // serving remote control, and a computer that has no other computer yet, + // are left exactly as they were. + if !wantRC { + s.endRemoteControlRun() + } return } filesDoors.Lock() - defer filesDoors.Unlock() - if _, ok := filesDoors.runs[s.Home]; ok { - return + if existing, ok := filesDoors.runs[s.Home]; ok { + if existing.remoteControl == wantRC { + filesDoors.Unlock() + return + } + delete(filesDoors.runs, s.Home) + filesDoors.Unlock() + if existing.remoteControl && !wantRC { + // The door goes on for live transfer, so the views end with a reason + // they can say, and the run restarts below without the live handlers. + s.endRemoteControlViews() + } + existing.stop() + <-existing.done + filesDoors.Lock() + if current, ok := filesDoors.runs[s.Home]; ok && current.remoteControl == wantRC { + filesDoors.Unlock() + return + } } + defer filesDoors.Unlock() cfg, err := s.filesDoorConfig() if err != nil { log.Printf("blind pass-through: opening the live store: %v", err) return } ctx, cancel := context.WithCancel(context.Background()) - run := &doorRun{stop: cancel, done: make(chan struct{})} + // Remote control is carried by whichever of the two live handlers is set: Live + // alone, or LiveRoad when the direct road is on. + servesLive := cfg.Live != nil || cfg.LiveRoad != nil + run := &doorRun{stop: cancel, done: make(chan struct{}), remoteControl: servesLive} filesDoors.runs[s.Home] = run - go func() { - defer close(run.done) + homeDir := s.Home + var watchWG sync.WaitGroup + if servesLive { + watchWG.Add(1) + guard.Go("syncsetup.permitsWatch", func() { + defer watchWG.Done() + pair.Permits().Watch(ctx, livePermitWatchEvery, func() { + livedoor.DefaultRegistry(homeDir).PermitsChanged("") + }) + }) + } + guard.Go("syncsetup.filesdoor", func() { + defer func() { + cancel() + watchWG.Wait() + close(run.done) + }() if err := filesdoor.Serve(ctx, cfg); err != nil && ctx.Err() == nil { log.Printf("blind pass-through: files door: %v", err) } - }() + }) +} + +// endRemoteControlViews closes every live view open on this home's door. It +// leans on the door's own permit read, which answers "no watching" while remote +// control is off, so each open tunnel closes the way it does for a permit that +// took watching away, and the viewer's link then finds a refusal and not a door +// that is merely quiet. It holds no lock of ours. +func (s *Sync) endRemoteControlViews() { + livedoor.DefaultRegistry(s.Home).PermitsChanged("") +} + +// endRemoteControlRun ends this home's door when it is running to serve remote +// control and nothing else needs it any more, and waits for it to let go of its +// lock, which is what a restart onto a door without the live handlers does too. +// A door that never served remote control is left alone. +func (s *Sync) endRemoteControlRun() { + filesDoors.Lock() + run, ok := filesDoors.runs[s.Home] + if !ok || !run.remoteControl { + filesDoors.Unlock() + return + } + delete(filesDoors.runs, s.Home) + filesDoors.Unlock() + s.endRemoteControlViews() + run.stop() + <-run.done } // filesDoorConfig is everything one process needs to serve this home's files @@ -323,7 +404,7 @@ func (s *Sync) filesDoorConfig() (filesdoor.ServeConfig, error) { if liveDoorStore != nil { store = liveDoorStore(s.Home, store) } - return filesdoor.ServeConfig{ + cfg := filesdoor.ServeConfig{ Service: s.Relay, Identity: s.Identity, Device: s.Device, @@ -337,7 +418,9 @@ func (s *Sync) filesDoorConfig() (filesdoor.ServeConfig, error) { // from the live store. Secrets: s.serveSecrets, SecretsPage: liveSecretsPage, - }, nil + } + s.attachRemoteControl(&cfg) + return cfg, nil } // stopFilesDoor ends this process's door for one home and waits for it to let @@ -362,9 +445,17 @@ func (s *Sync) activeDevices(ctx context.Context) (map[string]bool, error) { if err != nil { return nil, err } + s.RememberDevices(l.Devices) active := make(map[string]bool, len(l.Devices)) + var revoked []string for id, d := range l.Devices { active[id] = !d.Revoked + if d.Revoked { + revoked = append(revoked, id) + } + } + if len(revoked) > 0 { + livedoor.DefaultRegistry(s.Home).Revoke(revoked...) } return active, nil } diff --git a/internal/syncsetup/notes.go b/internal/syncsetup/notes.go index 5f719839b7..212b0ace01 100644 --- a/internal/syncsetup/notes.go +++ b/internal/syncsetup/notes.go @@ -31,7 +31,7 @@ import ( var ( // ErrNotesUnsupported is a relay that does not keep a device record's // outbox, so a message could not reach the other computer. - ErrNotesUnsupported = errors.New("this sync service cannot carry a message to another computer yet") + ErrNotesUnsupported = errors.New("this relay cannot carry a message to another computer yet") // ErrOutboxFull is MaxNotes messages already waiting to be taken. The // outbox is this device's, across every chat and computer, not one chat's. ErrOutboxFull = errors.New("too many messages sent from this computer are not delivered yet") @@ -40,7 +40,7 @@ var ( ErrNoteEmpty = errors.New("the message is empty") ErrNoteLong = errors.New("the message is too long to send to another computer") // ErrNoOwnRecord is a device whose own record the relay does not list yet. - ErrNoOwnRecord = errors.New("this computer is not listed by the sync service yet") + ErrNoOwnRecord = errors.New("this computer is not listed by the relay yet") ) // Mail is what one listing says about messages between computers, from this diff --git a/internal/syncsetup/old_service_write_test.go b/internal/syncsetup/old_service_write_test.go index 941db6ceff..71911b47ae 100644 --- a/internal/syncsetup/old_service_write_test.go +++ b/internal/syncsetup/old_service_write_test.go @@ -43,7 +43,7 @@ func TestOldServiceStillLetsTheOnlyComputerWriteItsChat(t *testing.T) { // TestOldServiceLetsLocalTurnsCatchUp pins the lockout's second step: turns // this computer saved while it could not publish, on top of the head the // service has, are this computer's own work. Reopening the chat publishes them -// rather than opening it read-only behind "Continue this chat here?". +// rather than opening it read-only behind "Move this chat here?". func TestOldServiceLetsLocalTurnsCatchUp(t *testing.T) { h := newTwoHomes(t, oldService) ctx := context.Background() diff --git a/internal/syncsetup/pair_merge_test.go b/internal/syncsetup/pair_merge_test.go index 071c591526..898bd3c5e6 100644 --- a/internal/syncsetup/pair_merge_test.go +++ b/internal/syncsetup/pair_merge_test.go @@ -21,7 +21,7 @@ import ( ) // M1–M5 exercise real local history, encrypted export/import, the pairing -// mailbox, directory publication, outage/retry and Continue here both ways. +// mailbox, directory publication, outage/retry and Move here both ways. func TestM1M2M3M4M5PairMergeRealHomes(t *testing.T) { h := newTwoHomes(t) ctx := t.Context() diff --git a/internal/syncsetup/passthrough_names_test.go b/internal/syncsetup/passthrough_names_test.go index 65d13cef20..a808b8604a 100644 --- a/internal/syncsetup/passthrough_names_test.go +++ b/internal/syncsetup/passthrough_names_test.go @@ -337,12 +337,12 @@ func TestPassThroughNoteToAChatElsewhereIsNotLeftOnTheRelayWhileStorageIsOff(t * r := newLiveRig(t) liveChat(t, r) if r.b.Notes() { - t.Fatal("Notes() says messages to another computer are on offer while sync storage is off") + t.Fatal("Notes() says messages to another computer are on offer while relay storage is off") } id, refused := r.b.SendNote(context.Background(), r.cell.ID, "PLAINTEXT-NOTE-MARKER-4c1e hello from B") if !errors.Is(refused, syncwords.ErrNotesWaitForStorage) || id != "" { - t.Fatalf("SendNote = %q, %v; want the sentence that messages wait for sync storage", id, refused) + t.Fatalf("SendNote = %q, %v; want the sentence that messages wait for relay storage", id, refused) } if bad := r.wire.noteWrites(); len(bad) > 0 { t.Fatalf("the relay was sent a message outbox: %v", bad) @@ -352,7 +352,7 @@ func TestPassThroughNoteToAChatElsewhereIsNotLeftOnTheRelayWhileStorageIsOff(t * if n := len(l.Devices[r.b.Device.ID()].Outbox); n != 0 { t.Fatalf("the relay holds %d sealed messages from B", n) } - if !strings.Contains(refused.Error(), "sync storage") { + if !strings.Contains(refused.Error(), "relay storage") { t.Fatalf("the refusal %q does not say what the message is waiting for", refused) } } diff --git a/internal/syncsetup/remote_control_off_test.go b/internal/syncsetup/remote_control_off_test.go new file mode 100644 index 0000000000..a9c77f8fc3 --- /dev/null +++ b/internal/syncsetup/remote_control_off_test.go @@ -0,0 +1,404 @@ +package syncsetup + +import ( + "context" + "encoding/json" + "errors" + "io" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/filesdoor" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/livedoor" + relaypkg "github.com/Agent-Field/codeaf/internal/relay" + "github.com/Agent-Field/codeaf/internal/remote" +) + +// These tests are written from the contract for turning remote control off +// while codeaf keeps running, not from the code that implements it: +// +// C1 With remote control on and a live view open, turning it off refuses any +// NEW live view at once: the next one is refused before any chat byte. +// C2 Within one watch tick after it goes off, every live view already open is +// closed and the door no longer serves remote control. If live transfer +// still needs the files door, the door keeps running for that and only the +// live handlers go away. +// C3 With remote control never turned on, no door is started, stopped or +// restarted that was not before; turning it ON still takes effect at the +// next tick. +// C4 A stopped run has been waited on: its done channel is closed when the +// tick returns, so nothing of it is left running. +// +// A "tick" is one call of ensureFilesDoor, which is all the 30 second watch loop +// of StartLiveTransfer does for the door. + +// rawLiveView is one live channel a viewer opened and said hello on. ended gets +// the error its read finished with, which is how a closed view looks from the +// viewer's side; welcomed is closed once the host's first bytes arrived. +type rawLiveView struct { + rwc io.ReadWriteCloser + welcomed chan struct{} + ended chan error +} + +func openRawLiveView(t *testing.T, link *livedoor.Link, chat string) *rawLiveView { + t.Helper() + open := link.Opener(chat) + var rwc io.ReadWriteCloser + waitFor(t, "the viewer to open a live channel", func() bool { + c, err := open() + if err != nil { + return false + } + rwc = c + return true + }) + t.Cleanup(func() { _ = rwc.Close() }) + + payload, err := json.Marshal(remote.Hello{Version: remote.Version, Join: true}) + mustNil(t, err) + frame, err := json.Marshal(remote.Frame{Kind: "hello", Payload: payload}) + mustNil(t, err) + if _, err := rwc.Write(append(frame, '\n')); err != nil { + t.Fatalf("writing the viewer's hello: %v", err) + } + + view := &rawLiveView{rwc: rwc, welcomed: make(chan struct{}), ended: make(chan error, 1)} + guard.Go("syncsetup.test.rawLiveView", func() { + buf := make([]byte, 4096) + first := true + for { + n, err := rwc.Read(buf) + if n > 0 && first { + first = false + close(view.welcomed) + } + if err != nil { + view.ended <- err + return + } + } + }) + waitFor(t, "the host's first bytes on the live view", func() bool { + select { + case <-view.welcomed: + return true + default: + return false + } + }) + return view +} + +// requireViewEnded fails unless the viewer's read finished, which is the stream +// of an open live view ending. +func requireViewEnded(t *testing.T, view *rawLiveView, what string) { + t.Helper() + select { + case <-view.ended: + case <-time.After(5 * time.Second): + t.Fatalf("%s: the live view's stream did not end", what) + } +} + +// requireDone fails unless the run's done channel is already closed: the tick +// that stopped it waited for it. +func requireDone(t *testing.T, run *doorRun, what string) { + t.Helper() + select { + case <-run.done: + default: + t.Fatalf("%s: the stopped door run was not waited on (its done channel is still open)", what) + } +} + +func doorRunOf(r *liveRig) *doorRun { + filesDoors.Lock() + defer filesDoors.Unlock() + return filesDoors.runs[r.a.Home] +} + +// dialLiveUntil keeps dialing the host's live door until ok accepts what it said. +func dialLiveUntil(t *testing.T, r *liveRig, what string, ok func(error) bool) { + t.Helper() + waitFor(t, what, func() bool { + tun, err := filesdoor.DialLive(context.Background(), r.a.Relay, r.b.Identity, r.b.Device, r.a.Device.ID()) + if err == nil { + _ = tun.Close() + } + return ok(err) + }) +} + +// liveViewOnHost builds the scene the C1 and C2 tests start from: remote control +// on, a chat held on the host, the host's door up, and one viewer with its live +// channel open and welcomed. +func liveViewOnHost(t *testing.T, r *liveRig) (*remote.Session, *livedoor.Link, *rawLiveView) { + t.Helper() + allowViewerDrive(t, r) + sess, _ := hostHeldChat(t, r, r.cell.ID, &stubLiveAgent{title: "Switched Off Chat"}) + r.a.ensureFilesDoor() + link := r.b.LiveLink(r.a.Device.ID(), nameA, func() bool { return true }, nil) + t.Cleanup(link.Close) + view := openRawLiveView(t, link, r.cell.ID) + waitFor(t, "the host to count the viewer's tunnel", func() bool { + return livedoor.DefaultRegistry(r.a.Home).Count(r.b.Device.ID()) == 1 + }) + return sess, link, view +} + +// TestC1TurningRemoteControlOffRefusesANewLiveViewAtOnce is C1: with a live view +// open, remote control goes off and NO tick runs; a second viewer's attempt is +// refused as the host having remote control off, before the host attaches it to +// the chat. +func TestC1TurningRemoteControlOffRefusesANewLiveViewAtOnce(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + r := newLiveRig(t) + sess, _, _ := liveViewOnHost(t, r) + attachedBefore := sess.Attached() + if attachedBefore == 0 { + t.Fatal("the first viewer is not attached to the host's chat, so this test proves nothing") + } + + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + + second := r.b.LiveLink(r.a.Device.ID(), nameA, func() bool { return true }, nil) + t.Cleanup(second.Close) + rwc, err := second.Opener(r.cell.ID)() + if err == nil { + _ = rwc.Close() + t.Fatal("a new live view opened with remote control off") + } + // THE REFUSAL SAYS THE SWITCH IS OFF, not that this computer's permit is empty + // (which would send the person to /devices): the host's answer to the dial + // carries it, and the view that follows once it is back on is not refused. + if reason, ok := livedoor.ReasonOf(err); !ok || reason != livedoor.ReasonRemoteControlOff { + t.Fatalf("the refused viewer read %v (reason %q), want the host's %q", err, reason, livedoor.ReasonRemoteControlOff) + } + if got := sess.Attached(); got != attachedBefore { + t.Fatalf("the host's chat has %d viewers after a refused attempt, want %d: the refused viewer was attached", got, attachedBefore) + } + if st := second.State(); st.Kind != livedoor.Revoked || st.Reason != livedoor.ReasonRemoteControlOff { + t.Fatalf("the refused viewer's link is %v/%q, want revoked/%s", st.Kind, st.Reason, livedoor.ReasonRemoteControlOff) + } +} + +// TestC2TurningRemoteControlOffEndsOpenViewsAndTheDoorAtTheNextTick is C2 for a +// computer where only remote control needs the files door (live transfer off): +// the open view's stream ends, the door run is gone, and it was waited on (C4). +func TestC2TurningRemoteControlOffEndsOpenViewsAndTheDoorAtTheNextTick(t *testing.T) { + r := newLiveRig(t) + t.Setenv(LiveTransferVar, "off") + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + if r.a.liveCarries() { + t.Fatal("live transfer carries chats with CODEAF_PASSTHROUGH=off, so remote control is not the only reason for the door") + } + _, _, view := liveViewOnHost(t, r) + run := doorRunOf(r) + if run == nil || !run.remoteControl { + t.Fatalf("no door run serving remote control to start from: %+v", run) + } + + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + r.a.ensureFilesDoor() + + requireViewEnded(t, view, "remote control off") + if got := livedoor.DefaultRegistry(r.a.Home).Count(r.b.Device.ID()); got != 0 { + t.Fatalf("the host still counts %d open live tunnels after the tick", got) + } + if now := doorRunOf(r); now != nil { + t.Fatalf("the door run is still registered after the tick: %+v", now) + } + requireDone(t, run, "remote control off") + dialLiveUntil(t, r, "the relay to say nobody serves this computer", func(err error) bool { + return errors.Is(err, relaypkg.ErrNoMachine) + }) + + // A second tick has nothing left to do. + r.a.ensureFilesDoor() + if now := doorRunOf(r); now != nil { + t.Fatalf("a later tick started a door with remote control off and no live transfer: %+v", now) + } +} + +// TestC2TurningRemoteControlOffKeepsTheDoorForLiveTransferWithoutLiveHandlers is +// C2 for a computer whose live transfer still needs the files door: the open +// view ends, the door restarts without the live handlers (a live intent is +// answered with a refusal while the door itself is still registered), the old +// run was waited on (C4), and turning it back on is taken at the next tick (C3). +func TestC2TurningRemoteControlOffKeepsTheDoorForLiveTransferWithoutLiveHandlers(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + r := newLiveRig(t) + if !r.a.liveCarries() { + t.Fatal("live transfer is not carrying chats in the rig, so the door has no reason beyond remote control") + } + _, _, view := liveViewOnHost(t, r) + before := doorRunOf(r) + if before == nil || !before.remoteControl { + t.Fatalf("no door run serving remote control to start from: %+v", before) + } + + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + r.a.ensureFilesDoor() + + requireViewEnded(t, view, "remote control off") + if got := livedoor.DefaultRegistry(r.a.Home).Count(r.b.Device.ID()); got != 0 { + t.Fatalf("the host still counts %d open live tunnels after the tick", got) + } + requireDone(t, before, "remote control off") + after := doorRunOf(r) + if after == nil { + t.Fatal("the door was stopped although live transfer still needs it") + } + if after == before || after.remoteControl { + t.Fatalf("the door was not restarted without remote control: same run %v, remoteControl %v", after == before, after.remoteControl) + } + dialLiveUntil(t, r, "the restarted door to refuse a live intent without being absent", func(err error) bool { + return err != nil && !errors.Is(err, relaypkg.ErrNoMachine) + }) + + // Turning it back on is taken at the next tick, as it always was. + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + r.a.ensureFilesDoor() + again := doorRunOf(r) + if again == nil || again == after || !again.remoteControl { + t.Fatalf("turning remote control back on did not restart the door with it: %+v", again) + } + requireDone(t, after, "remote control back on") + dialLiveUntil(t, r, "a live view to open again", func(err error) bool { return err == nil }) +} + +// TestC3ARunThatNeverServedRemoteControlIsNeverTouchedByATick is C3: with remote +// control off the whole time, a tick starts a door only for live transfer, a +// second tick leaves it alone, and when live transfer goes off too the door that +// is already up is left exactly as it was (nothing stopped, nothing restarted). +func TestC3ARunThatNeverServedRemoteControlIsNeverTouchedByATick(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + r := newLiveRig(t) + if !r.a.liveCarries() { + t.Fatal("live transfer is not carrying chats in the rig") + } + + r.a.ensureFilesDoor() + run := doorRunOf(r) + if run == nil || run.remoteControl { + t.Fatalf("a tick with remote control off should start a plain door for live transfer: %+v", run) + } + registrations := r.wire.registrations() + + r.a.ensureFilesDoor() + if now := doorRunOf(r); now != run { + t.Fatalf("a second tick replaced the door run: %+v -> %+v", run, now) + } + + t.Setenv(LiveTransferVar, "off") + if r.a.liveCarries() { + t.Fatal("live transfer still carries chats with CODEAF_PASSTHROUGH=off") + } + r.a.ensureFilesDoor() + if now := doorRunOf(r); now != run { + t.Fatalf("a tick with nothing to do replaced or removed a door that never served remote control: %+v -> %+v", run, now) + } + select { + case <-run.done: + t.Fatal("a tick with nothing to do stopped a door that never served remote control") + default: + } + if got := r.wire.registrations(); got != registrations { + t.Fatalf("relay registrations went from %d to %d with remote control never on", registrations, got) + } +} + +// requireNoSignOfAnOfflineHost fails if, over the next stretch of real time, the +// link says anything that claims the host went away or that it is being +// redialled: the host is up and said no, so neither is true. +func requireNoSignOfAnOfflineHost(t *testing.T, link *livedoor.Link, dials func() int, atRest int, over time.Duration) { + t.Helper() + deadline := time.Now().Add(over) + for time.Now().Before(deadline) { + if st := link.State(); st.Kind == livedoor.WentOffline || st.Kind == livedoor.Reconnecting { + t.Fatalf("the link says %v although the host is up and said no (reason %q)", st.Kind, st.Reason) + } + if got := dials(); got != atRest { + t.Fatalf("the viewer dialled again by itself: %d dials, want %d", got, atRest) + } + time.Sleep(25 * time.Millisecond) + } +} + +// TestC1TheViewEndsWithTheSentenceThatRemoteControlWasTurnedOffAndDoesNotRedial +// is the contract of the two-computer hand test: B has a live view of A's chat, +// the person turns remote control OFF on A, and within one tick B's view ends +// saying exactly that. It never says A went offline, the link never redials, and +// the relay sees no further dial from B. The same holds when A's door goes away +// with the switch and when live transfer keeps it up. +func TestC1TheViewEndsWithTheSentenceThatRemoteControlWasTurnedOffAndDoesNotRedial(t *testing.T) { + for _, tc := range []struct { + name string + liveTransfer string + }{ + {"the door goes with it", "off"}, + {"the door stays up for live transfer", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + r := newLiveRig(t) + t.Setenv(LiveTransferVar, tc.liveTransfer) + _, link, view := liveViewOnHost(t, r) + dialedBefore := r.wire.dials() + + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + r.a.ensureFilesDoor() + + select { + case err := <-view.ended: + if reason, ok := livedoor.ReasonOf(err); !ok || reason != livedoor.ReasonRemoteControlOff { + t.Fatalf("the view ended with %v (reason %q), want %q", err, reason, livedoor.ReasonRemoteControlOff) + } + case <-time.After(5 * time.Second): + t.Fatal("the live view did not end") + } + waitFor(t, "the link to rest with the host's reason", func() bool { + st := link.State() + return st.Kind == livedoor.Revoked && st.Reason == livedoor.ReasonRemoteControlOff + }) + if said := chatlist.LiveSaid(link.State().Reason, nameA); said != nameA+" turned remote control off." { + t.Fatalf("the sentence reads %q", said) + } + requireNoSignOfAnOfflineHost(t, link, r.wire.dials, dialedBefore, 1500*time.Millisecond) + }) + } +} + +// TestC2AHostNobodyServesIsNeverSaidToHaveTurnedRemoteControlOff keeps the +// default: a viewer that dials a computer with nobody serving, and has never +// been told why, still reads it as a computer it cannot reach and keeps trying. +// It is not given the host's switch as a reason it never heard, and its link is +// not left resting. +func TestC2AHostNobodyServesIsNeverSaidToHaveTurnedRemoteControlOff(t *testing.T) { + t.Setenv("CODEAF_REMOTE_CONTROL", "on") + t.Setenv(LiveTransferVar, "off") + r := newLiveRig(t) + _, _, _ = liveViewOnHost(t, r) + t.Setenv("CODEAF_REMOTE_CONTROL", "off") + r.a.ensureFilesDoor() + dialLiveUntil(t, r, "the relay to say nobody serves this computer", func(err error) bool { + return errors.Is(err, relaypkg.ErrNoMachine) + }) + + fresh := r.b.LiveLink(r.a.Device.ID(), nameA, func() bool { return true }, nil) + t.Cleanup(fresh.Close) + rwc, err := fresh.Opener(r.cell.ID)() + if err == nil { + _ = rwc.Close() + t.Fatal("a view opened on a computer nobody serves") + } + if reason, ok := livedoor.ReasonOf(err); ok && reason == livedoor.ReasonRemoteControlOff { + t.Fatalf("a viewer that was never told why was handed the host's switch as the reason: %v", err) + } + if st := fresh.State(); st.Kind != livedoor.WentOffline && st.Kind != livedoor.Reconnecting { + t.Fatalf("a viewer that cannot reach the computer reads %v (reason %q), want it still trying", st.Kind, st.Reason) + } +} diff --git a/internal/syncsetup/remotecontrol.go b/internal/syncsetup/remotecontrol.go new file mode 100644 index 0000000000..2ae37314c0 --- /dev/null +++ b/internal/syncsetup/remotecontrol.go @@ -0,0 +1,336 @@ +package syncsetup + +import ( + "context" + "errors" + "fmt" + "io" + "path/filepath" + "slices" + "strings" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/devname" + "github.com/Agent-Field/codeaf/internal/directory" + "github.com/Agent-Field/codeaf/internal/filesdoor" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/home" + "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/livedoor" + "github.com/Agent-Field/codeaf/internal/pair" + relaypkg "github.com/Agent-Field/codeaf/internal/relay" + "github.com/Agent-Field/codeaf/internal/session" +) + +// livePermitWatchEvery is how often the door's permit watcher stats permits.json +// for edits made by another process; zero uses PermitBook.Watch's one-second +// default and tests shrink it with t.Cleanup. +var livePermitWatchEvery time.Duration + +// legacySnapshots remembers which (home, identity) pairs have already taken +// their one-time legacy permit snapshot in this process so later roster reads +// never touch the permit file again. +var legacySnapshots sync.Map + +// revokedSubscribers holds the per-home callbacks registered by the files door +// so a revocation event arriving on a directory watch stream reaches open live +// views without waiting for the roster cache TTL. +var revokedSubscribers = struct { + sync.Mutex + next int + by map[string]map[int]func([]string) +}{by: map[string]map[int]func([]string){}} + +// remoteControlWanted reports whether this computer should hold its files door +// open for remote control: the person turned remote control on and the cached +// roster shows at least one other non-revoked device on this identity. +func (s *Sync) remoteControlWanted() bool { + return config.RemoteControlOn() && s.hasOtherActiveDevice() +} + +// hasOtherActiveDevice answers from the already-read roster snapshot or the +// persisted others marker whether another non-revoked device belongs to this +// identity, making no relay request on the hot path. +func (s *Sync) hasOtherActiveDevice() bool { + if s == nil { + return false + } + binding := deviceBindingFor(s.Relay, s.Identity, s.Device) + deviceObservers.Lock() + snap, ok := deviceObservers.snapshots[binding] + deviceObservers.Unlock() + if ok && snap.Complete { + for id, dev := range snap.Devices { + if id != s.Device.ID() && !dev.Revoked { + return true + } + } + if len(snap.Devices) > 1 { + return false + } + } + return s.OthersPaired() +} + +// snapshotLegacyOnce records the one-time legacy device list in the permit book +// the first time this process reads a full roster for an identity that is not +// solo. Because the permit book's SnapshotLegacy is idempotent once written and +// legacySnapshots guards the call per process and identity, newly paired +// devices that appear in later reads stay ClassNew. +func snapshotLegacyOnce(homeDir string, b deviceBinding, devices map[string]directory.Device) { + if b.identity == "" || len(devices) < 2 { + return + } + if homeDir != "" && identity.Solo(homeDir) { + return + } + hasOther := false + roster := make([]string, 0, len(devices)) + for id, dev := range devices { + if dev.Revoked { + continue + } + if id != b.self { + hasOther = true + } + roster = append(roster, id) + } + if !hasOther || len(roster) < 2 { + return + } + slices.Sort(roster) + key := filepath.Clean(home.Dir()) + "\x00" + b.identity + if _, loaded := legacySnapshots.LoadOrStore(key, true); loaded { + return + } + _ = pair.Permits().SnapshotLegacy(b.identity, roster) +} + +func (s *Sync) budget() *livedoor.Budget { + s.liveBudgetOnce.Do(func() { + s.liveBudget = livedoor.OpenBudget(s.Home, livedoor.RealClock(), 0) + }) + return s.liveBudget +} + +func (s *Sync) peerLabel(deviceID string) string { + if name, ok := s.cachedDeviceName(deviceID); ok && name != "" { + return name + } + return chatlist.DeviceName(nil, deviceID, nil) +} + +func (s *Sync) hostLabel() string { + if name, ok := s.cachedDeviceName(s.Device.ID()); ok && name != "" { + return name + } + return devname.Name(s.Home) +} + +func (s *Sync) livePresence(exclude string) []session.SessionPresence { + rows := session.ReadAllPresence(filepath.Join(s.Home, "v3", "projects"), time.Now(), exclude) + if len(rows) == 0 && filepath.Clean(s.Home) != filepath.Clean(home.Dir()) { + rows = session.HomePresence(exclude) + } + return rows +} + +func (s *Sync) attachRemoteControl(cfg *filesdoor.ServeConfig) { + if !config.RemoteControlOn() { + return + } + identityID := s.Identity.ID() + resolver := livedoor.NewResolver(s.Home, livedoor.ResolverOptions{ + Presence: s.livePresence, + }) + registry := livedoor.DefaultRegistry(s.Home) + // THE SWITCH IS READ AGAIN FOR EVERY PERMIT, never remembered from when this + // door started. Remote control turned off while codeaf keeps running must + // stop handing chats out at once, as the desktop's door does (its lookup + // asks the setting on every question): a permit with no watch is already + // what the router answers with a refusal before any chat byte, for a new + // tunnel, for a new channel on an open one and for a direct offer. + readPermit := func(device string) pair.Permit { + if !config.RemoteControlOn() { + return pair.Permit{} + } + p, _ := pair.Permits().For(identityID, device) + return p + } + // serve is the one place a live tunnel becomes a livedoor.Serve call, whichever + // road carried it. direct is the host half a RELAY tunnel advertises, and is + // nil for every tunnel that must not offer one. + serve := func(ctx context.Context, tun io.ReadWriteCloser, device, road string, direct livedoor.DirectHost) error { + permit, class := pair.Permits().For(identityID, device) + if !config.RemoteControlOn() { + permit = pair.Permit{} + } + peer := livedoor.Peer{ + Device: device, + Label: s.peerLabel(device), + Permit: permit, + Class: class, + } + return livedoor.Serve(ctx, tun, peer, livedoor.ServeConfig{ + Resolver: resolver, + Registry: registry, + Budget: s.budget(), + Permit: readPermit, + Host: s.hostLabel(), + Road: road, + Direct: direct, + Clock: livedoor.RealClock(), + // A VIEW THAT ENDS BECAUSE THE SWITCH IS OFF SAYS SO. The permit read + // above answers "no watching" for it, and a viewer told that its permit + // changed would read a computer that changed what it allows, not one + // that stopped serving. + Off: func() bool { return !config.RemoteControlOn() }, + }) + } + // THE DIRECT ROAD EXISTS ONLY WHEN ALL THREE HOLD: remote control is on (the + // check above), the person did not pin the road to the relay, and the program + // installed an implementation. Otherwise nothing here constructs a peer + // connection, no STUN request can be made, the door advertises no direct road + // and a direct intent is refused before any Noise work. + if road, ok := InstalledDirectRoad(); ok && !config.RemoteRoadRelayOnly() { + host := road.NewHost(config.RemoteSTUN()) + cfg.Direct = func(ctx context.Context, accept filesdoor.StreamAcceptor) { + host.SetAcceptor(ctx, accept) + guard.Go("syncsetup.directroad.close", func() { + <-ctx.Done() + host.Close() + }) + } + cfg.LiveRoad = func(ctx context.Context, tun io.ReadWriteCloser, device, carried string) error { + if carried == livedoor.RoadDirect { + return serve(ctx, tun, device, livedoor.RoadDirect, nil) + } + return serve(ctx, tun, device, livedoor.RoadRelay, host) + } + } else { + cfg.Live = func(ctx context.Context, tun io.ReadWriteCloser, device string) error { + return serve(ctx, tun, device, livedoor.RoadRelay, nil) + } + } + cfg.Revoked = func(ctx context.Context, gone func(devices []string)) func() { + return subscribeRevoked(s.Home, func(ids []string) { + registry.Revoke(ids...) + if gone != nil { + gone(ids) + } + }) + } +} + +func subscribeRevoked(homeDir string, fn func([]string)) func() { + key := filepath.Clean(homeDir) + revokedSubscribers.Lock() + defer revokedSubscribers.Unlock() + revokedSubscribers.next++ + id := revokedSubscribers.next + if revokedSubscribers.by[key] == nil { + revokedSubscribers.by[key] = map[int]func([]string){} + } + revokedSubscribers.by[key][id] = fn + return func() { + revokedSubscribers.Lock() + defer revokedSubscribers.Unlock() + delete(revokedSubscribers.by[key], id) + } +} + +func notifyRevoked(homeDir string, ids ...string) { + if len(ids) == 0 { + return + } + livedoor.DefaultRegistry(homeDir).Revoke(ids...) + key := filepath.Clean(homeDir) + revokedSubscribers.Lock() + var subs []func([]string) + for _, fn := range revokedSubscribers.by[key] { + subs = append(subs, fn) + } + revokedSubscribers.Unlock() + for _, fn := range subs { + fn(ids) + } +} + +// LiveLink constructs a viewer-side multiplexed live link to hostDeviceID over +// the files-door relay tunnel, mapping an unregistered host to +// livedoor.ErrHostOffline so the surface transitions straight to WentOffline. +func (s *Sync) LiveLink(hostDeviceID, hostName string, active func() bool, onState func(livedoor.State)) *livedoor.Link { + return livedoor.NewLink(s.liveLinkConfig(hostDeviceID, hostName, active, onState)) +} + +// directSignalBuffer is how many host signals a viewer link holds for the +// attempt that is reading them. An attempt exchanges an answer and a handful of +// candidates, so this is generous; a full buffer drops the newest signal rather +// than ever blocking the relay's read loop, which would stall the whole view. +const directSignalBuffer = 64 + +// liveLinkConfig is LiveLink's configuration, apart from the link built from it, +// so a test can read what the link was given. +func (s *Sync) liveLinkConfig(hostDeviceID, hostName string, active func() bool, onState func(livedoor.State)) livedoor.LinkConfig { + cfg := livedoor.LinkConfig{ + Home: s.Home, + Dial: func(ctx context.Context) (io.ReadWriteCloser, error) { + tun, err := filesdoor.DialLive(ctx, s.Relay, s.Identity, s.Device, hostDeviceID) + if err != nil { + if errors.Is(err, relaypkg.ErrNoMachine) { + return nil, fmt.Errorf("%w: %w", livedoor.ErrHostOffline, err) + } + var refused *filesdoor.RefusedError + if errors.As(err, &refused) && strings.TrimSpace(refused.Reason) == filesdoor.RemovedLine { + return nil, &livedoor.ReasonError{Reason: livedoor.ReasonRemoved, Host: hostName, Err: err} + } + return nil, err + } + return tun, nil + }, + Identity: s.Identity.ID(), + Host: hostDeviceID, + HostName: hostName, + Active: active, + OnState: onState, + } + // THE VIEWER OFFERS THE DIRECT ROAD UNDER THE SAME THREE CONDITIONS THE DOOR + // ANSWERS IT: remote control is on, the person did not pin the road to the + // relay, and the program installed an implementation. Otherwise the link has + // no direct half at all, so it builds no peer connection, can make no STUN + // request, and never signals anything. + road, ok := InstalledDirectRoad() + if !ok || !config.RemoteControlOn() || config.RemoteRoadRelayOnly() { + return cfg + } + deliver := make(chan []byte, directSignalBuffer) + cfg.OnSignal = func(payload []byte) { + select { + case deliver <- payload: + default: + } + } + cfg.Direct = &livedoor.DirectConfig{ + Dial: func(ctx context.Context, sig livedoor.Signaller) (io.ReadWriteCloser, error) { + // Whatever the host said to an attempt that has ended is of no use to + // this one (the road also checks each signal's attempt id), and it + // must not sit in the way of the answer. + for drained := false; !drained; { + select { + case <-deliver: + default: + drained = true + } + } + stream, err := road.Offer(ctx, config.RemoteSTUN(), sig, deliver) + if err != nil { + return nil, err + } + return filesdoor.DialDirect(ctx, stream, s.Identity, s.Device, hostDeviceID) + }, + } + return cfg +} diff --git a/internal/syncsetup/storage.go b/internal/syncsetup/storage.go index 96cd6a2ac1..a4ee323cb0 100644 --- a/internal/syncsetup/storage.go +++ b/internal/syncsetup/storage.go @@ -142,7 +142,7 @@ func (s *Sync) StorageAllowed() bool { // StorageRequestLink includes only the public account identifier, never a key. func StorageRequestLink(identity string) string { - query := url.Values{"title": {"sync storage access: " + identity}, "body": {"Please turn on sync storage for my account.\n\nRequest code: " + identity}} + query := url.Values{"title": {"relay storage access: " + identity}, "body": {"Please turn on relay storage for my account.\n\nRequest code: " + identity}} return StorageRequestURL + "?" + query.Encode() } diff --git a/internal/syncsetup/storage_off_continue_test.go b/internal/syncsetup/storage_off_continue_test.go index dcf99fc80f..ea59fdfd4d 100644 --- a/internal/syncsetup/storage_off_continue_test.go +++ b/internal/syncsetup/storage_off_continue_test.go @@ -87,7 +87,7 @@ func TestStorageOffContinuePreservesLocalTurns(t *testing.T) { got, err := cont.Take(t.Context(), at.ID) refused := mode == "diverged" || mode == "head moves at acquire" if refused { - if err == nil || err.Error() != "cannot continue this chat here while sync storage is off because this computer is missing saved turns; your local turns stay here" { + if err == nil || err.Error() != "cannot move this chat here while relay storage is off because this computer is missing saved turns; your local turns stay here" { t.Fatalf("refusal: %v", err) } } else if err != nil { diff --git a/internal/syncsetup/storage_optin_test.go b/internal/syncsetup/storage_optin_test.go index 292cde1b7e..3a72b25de9 100644 --- a/internal/syncsetup/storage_optin_test.go +++ b/internal/syncsetup/storage_optin_test.go @@ -225,7 +225,7 @@ func TestStorageOptInRequestLinkUsesPublicWording(t *testing.T) { t.Fatal(err) } query := link.Query() - if query.Get("title") != "sync storage access: "+id || query.Get("body") != "Please turn on sync storage for my account.\n\nRequest code: "+id { + if query.Get("title") != "relay storage access: "+id || query.Get("body") != "Please turn on relay storage for my account.\n\nRequest code: "+id { t.Fatalf("request wording: %v", query) } } diff --git a/internal/syncsetup/syncsetup.go b/internal/syncsetup/syncsetup.go index 012702ecc5..cdb9d23974 100644 --- a/internal/syncsetup/syncsetup.go +++ b/internal/syncsetup/syncsetup.go @@ -30,6 +30,7 @@ import ( "github.com/Agent-Field/codeaf/internal/dirwatch" "github.com/Agent-Field/codeaf/internal/env" "github.com/Agent-Field/codeaf/internal/identity" + "github.com/Agent-Field/codeaf/internal/livedoor" "github.com/Agent-Field/codeaf/internal/pair" "github.com/Agent-Field/codeaf/internal/reqsign" "github.com/Agent-Field/codeaf/internal/rotate" @@ -111,6 +112,8 @@ type Sync struct { Interval time.Duration // flush interval stateCredentialRefresh uint64 // guarded by stateMu across vault rounds + liveBudgetOnce sync.Once + liveBudget *livedoor.Budget } // Open builds the clients for the relay Resolve names. It answers ok = false diff --git a/internal/syncsetup/take.go b/internal/syncsetup/take.go index 4c4fe98b1b..74e391f4a0 100644 --- a/internal/syncsetup/take.go +++ b/internal/syncsetup/take.go @@ -116,7 +116,7 @@ type Continued struct { KeptBranch func() (string, uint32) `json:"-"` } -// Continuer is the take side of one machine: `continue here`. +// Continuer is the take side of one machine: `move here`. type Continuer struct { sync *Sync eng cellstore.Engine @@ -1166,7 +1166,7 @@ func (c *Continuer) take(ctx context.Context, id string, seen *directory.LeaseEx } if c.sync.teamsSharing() { if err := (teamKeys{c.sync.profile(), c.sync.Home, c.sync.Device.ID(), nil}).rebindChat(id, taken.Cell); err != nil { - c.say(taken.Cell, "This chat continued here, but its teams could not be updated yet: "+err.Error()) + c.say(taken.Cell, "This chat moved here, but its teams could not be updated yet: "+err.Error()) } } recordStep("send_lease", "") @@ -1514,7 +1514,7 @@ func (c *Continuer) take(ctx context.Context, id string, seen *directory.LeaseEx hErr := hook(runCtx, taken.Cell) hookDone() if hErr != nil { - c.say(taken.Cell, "This chat continued here, but part of its state could not be updated yet: "+hErr.Error()) + c.say(taken.Cell, "This chat moved here, but part of its state could not be updated yet: "+hErr.Error()) } } @@ -1535,7 +1535,7 @@ func (c *Continuer) take(ctx context.Context, id string, seen *directory.LeaseEx } if c.sync.teamsSharing() { if tErr := (teamKeys{c.sync.profile(), c.sync.Home, c.sync.Device.ID(), nil}).rebindChat(id, taken.Cell); tErr != nil { - c.say(taken.Cell, "This chat continued here, but its teams could not be updated yet: "+tErr.Error()) + c.say(taken.Cell, "This chat moved here, but its teams could not be updated yet: "+tErr.Error()) } } stashPath := filepath.Join(taken.Cell.Root, "resume.pending") diff --git a/internal/syncsetup/twohomes_test.go b/internal/syncsetup/twohomes_test.go index fbfe766fa1..926a04c039 100644 --- a/internal/syncsetup/twohomes_test.go +++ b/internal/syncsetup/twohomes_test.go @@ -791,7 +791,7 @@ func TestTwoHomesTakeARunningChatAtOnce(t *testing.T) { row, ok := rowOf(t, h.b, h.cell.ID) if !ok || row.Status != chatlist.Running || chatlist.OfferFor(row).Kind != chatlist.ContinueHere { - t.Fatalf("B's row = %+v, %v; want a running chat that offers continue here", row, ok) + t.Fatalf("B's row = %+v, %v; want a running chat that offers move here", row, ok) } if _, err := h.continuerB().Take(ctx, h.cell.ID); err != nil { t.Fatalf("Take of a running chat = %v; want it taken at once", err) @@ -811,8 +811,8 @@ func TestTwoHomesTakeARunningChatAtOnce(t *testing.T) { } } -// TestTakeSideContinueHere is the whole of `continue here` from the home's -// side: A goes quiet, its row on B offers `continue here`, B takes the chat and +// TestTakeSideContinueHere is the whole of `move here` from the home's +// side: A goes quiet, its row on B offers `move here`, B takes the chat and // drives it, and A's row says where the chat is now. func TestTakeSideContinueHere(t *testing.T) { h := newTwoHomes(t) @@ -825,7 +825,7 @@ func TestTakeSideContinueHere(t *testing.T) { row, ok := rowOf(t, h.b, h.cell.ID) if !ok || row.Status != chatlist.Off || chatlist.OfferFor(row).Kind != chatlist.ContinueHere { - t.Fatalf("B's row = %+v, %v; want %s off, offering continue here", row, ok, nameA) + t.Fatalf("B's row = %+v, %v; want %s off, offering move here", row, ok, nameA) } took, err := h.continuerB().Take(ctx, h.cell.ID) if err != nil { diff --git a/internal/syncwords/errors.go b/internal/syncwords/errors.go index fadce957f1..69bc8b67c9 100644 --- a/internal/syncwords/errors.go +++ b/internal/syncwords/errors.go @@ -41,7 +41,7 @@ func Explain(err error, address string) error { } switch { case errors.Is(err, context.DeadlineExceeded), errors.As(err, &network) && network.Timeout(): - return explained{"the sync service at " + address + " did not answer in time — try again", err} + return explained{"the relay at " + address + " did not answer in time — try again", err} case IsStruggling(err): return explained{Struggling(address), err} case network != nil, errors.Is(err, syscall.ECONNREFUSED), errors.Is(err, syscall.ENETUNREACH), errors.Is(err, syscall.EHOSTUNREACH), errors.Is(err, relay.ErrUnreachable): diff --git a/internal/syncwords/l4_test.go b/internal/syncwords/l4_test.go index c3bded679b..23436ddc6f 100644 --- a/internal/syncwords/l4_test.go +++ b/internal/syncwords/l4_test.go @@ -24,7 +24,7 @@ func TestMain(m *testing.M) { // L4-M9a: another release channel's hosted service is hosted too, never "your own", // and an unknown address names nothing. func TestL4EveryChannelsServiceIsHosted(t *testing.T) { - if got := ServiceLine("https://fabric-staging.example.test"); got != "sync service: fabric-staging.example.test (hosted)" { + if got := ServiceLine("https://fabric-staging.example.test"); got != "relay: fabric-staging.example.test (hosted)" { t.Fatal(got) } if Hosted("") || Hosted("http://127.0.0.1:8901") { @@ -38,11 +38,11 @@ func TestL4ServiceFailures(t *testing.T) { cause error address, want string }{ - {&url.Error{Op: "Get", URL: "http://127.0.0.1:8901/private", Err: syscall.ECONNREFUSED}, "http://127.0.0.1:8901", "nothing is answering at http://127.0.0.1:8901 — if that is your own sync service, start it there with codeaf relay"}, + {&url.Error{Op: "Get", URL: "http://127.0.0.1:8901/private", Err: syscall.ECONNREFUSED}, "http://127.0.0.1:8901", "nothing is answering at http://127.0.0.1:8901 — if that is your own relay, start it there with codeaf relay"}, {&net.DNSError{Err: "no such host", Name: "mine"}, HostedURL, "cannot reach codeaf.agentfield.ai — check this computer's internet connection"}, - {context.DeadlineExceeded, "http://127.0.0.1:8901", "the sync service at http://127.0.0.1:8901 did not answer in time — try again"}, - {wireauth.ErrUnavailable, "http://127.0.0.1:8901", "the sync service at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute"}, - {directory.ErrUnreachable, "http://127.0.0.1:8901", "the sync service at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute"}, + {context.DeadlineExceeded, "http://127.0.0.1:8901", "the relay at http://127.0.0.1:8901 did not answer in time — try again"}, + {wireauth.ErrUnavailable, "http://127.0.0.1:8901", "the relay at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute"}, + {directory.ErrUnreachable, "http://127.0.0.1:8901", "the relay at 127.0.0.1:8901 is up but cannot agree on changes right now; it usually recovers within a minute"}, } { got := Explain(tc.cause, tc.address) if got.Error() != tc.want || !errors.Is(got, tc.cause) { @@ -53,10 +53,10 @@ func TestL4ServiceFailures(t *testing.T) { // L4-M9a: terminal and future chat lists use one exported service label. func TestL4ServiceLine(t *testing.T) { - if got := ServiceLine(HostedURL); got != "sync service: codeaf.agentfield.ai (hosted)" { + if got := ServiceLine(HostedURL); got != "relay: codeaf.agentfield.ai (hosted)" { t.Fatal(got) } - if got := ServiceLine("http://127.0.0.1:8901"); got != "sync service: 127.0.0.1:8901 (your own)" { + if got := ServiceLine("http://127.0.0.1:8901"); got != "relay: 127.0.0.1:8901 (your own)" { t.Fatal(got) } } diff --git a/internal/syncwords/words.go b/internal/syncwords/words.go index c12bde49e3..11ae6ecac8 100644 --- a/internal/syncwords/words.go +++ b/internal/syncwords/words.go @@ -57,7 +57,7 @@ func ServiceLine(address string) string { if Hosted(address) { kind = "hosted" } - return fmt.Sprintf("sync service: %s (%s)", Host(address), kind) + return fmt.Sprintf("relay: %s (%s)", Host(address), kind) } // Unreachable distinguishes a personal service from the hosted internet service. @@ -65,12 +65,12 @@ func Unreachable(address string) string { if Hosted(address) { return "cannot reach " + Host(address) + " — check this computer's internet connection" } - return "nothing is answering at " + address + " — if that is your own sync service, start it there with codeaf relay" + return "nothing is answering at " + address + " — if that is your own relay, start it there with codeaf relay" } // Struggling is a service that answered but could not finish a coordinated change. func Struggling(address string) string { - return "the sync service at " + Host(address) + " is up but cannot agree on changes right now; it usually recovers within a minute" + return "the relay at " + Host(address) + " is up but cannot agree on changes right now; it usually recovers within a minute" } // Recovered is emitted only after a successful sync-service call. @@ -80,10 +80,10 @@ const Recovered = "syncing again" // LegacyOutage remains the wire spelling for surfaces that predate this vocabulary. const LegacyOutage = "this chat is not syncing because other machines are unreachable; it keeps working here" -const outagePrefix = "the sync service at " +const outagePrefix = "the relay at " const outageSuffix = " is not answering; this chat keeps working here and catches up when it is back" -const UnknownOutage = "the sync service is not answering; this chat keeps working here and catches up when it is back" +const UnknownOutage = "the relay is not answering; this chat keeps working here and catches up when it is back" // Outage is said once while local work continues through a network outage. func Outage(address string) string { @@ -91,7 +91,7 @@ func Outage(address string) string { } // Asking is the delayed progress sentence for terminal commands. -func Asking(address string) string { return "asking the sync service at " + Host(address) + "…" } +func Asking(address string) string { return "asking the relay at " + Host(address) + "…" } // IsOutage recognizes both generations so mixed builds share one notice ledger. func IsOutage(text string) bool { @@ -99,13 +99,13 @@ func IsOutage(text string) bool { } // SavedHerePending names the same pending upload at app quit and individual close. -const SavedHerePending = "saved here; it reaches your other devices when the sync service at %s answers" +const SavedHerePending = "saved here; it reaches your other devices when the relay at %s answers" // SavedStorageOff is shared by app quit and the close of an individual chat. -const SavedStorageOff = "saved here; sync storage is off for this account, so it stays on this computer" +const SavedStorageOff = "saved here; relay storage is off for this account, so it stays on this computer" // ErrContinueStorageOff preserves local turns when the recorded history is missing here. -var ErrContinueStorageOff = errors.New("cannot continue this chat here while sync storage is off because this computer is missing saved turns; your local turns stay here") +var ErrContinueStorageOff = errors.New("cannot move this chat here while relay storage is off because this computer is missing saved turns; your local turns stay here") // ErrHolderOffline is a take that cannot finish because the computer that has // the chat is not running codeaf, so nothing can send its bytes. The chat is @@ -132,14 +132,14 @@ func HolderOffline(name string) string { if name == "" { name = "another computer" } - return name + " has this chat and is not on right now; open codeaf there, then continue here" + return name + " has this chat and is not on right now; open codeaf there, then move here" } // ErrLiveTransferOff is what continuing a chat says when the chat exists only on // the computer that shared it by blind pass-through and this computer has that // mode switched off: the record is in the list, but the only road to its frames // is shut here. -var ErrLiveTransferOff = errors.New("this chat is only on the computer that shares it, and blind pass-through is switched off here; switch it back on (CODEAF_PASSTHROUGH) or turn on sync storage to continue it here") +var ErrLiveTransferOff = errors.New("this chat is only on the computer that shares it, and blind pass-through is switched off here; switch it back on (CODEAF_PASSTHROUGH) or turn on relay storage to move it here") // SecretFilesLate is said when a chat has moved here but the files kept out of // its saved history (.env and the like) did not come with it, because the @@ -156,4 +156,4 @@ func SecretFilesLate(name string) string { // have to sit on the sync service until that computer took it, and the service // keeps nothing of the kind until storage is approved, so the message is not // sent: the chat has to be brought here to be written to. -var ErrNotesWaitForStorage = errors.New("a message to a chat on another computer waits for sync storage, which is off for this account; continue the chat here to write to it") +var ErrNotesWaitForStorage = errors.New("a message to a chat on another computer waits for relay storage, which is off for this account; move the chat here to write to it") diff --git a/internal/taskdoor/registration.go b/internal/taskdoor/registration.go index 9bafa59483..dc8f9d24b1 100644 --- a/internal/taskdoor/registration.go +++ b/internal/taskdoor/registration.go @@ -34,6 +34,18 @@ func (r *registrationLoop) now() time.Time { } return time.Now() } + +// spread is how long to actually wait at a point in a back-off schedule: the +// first wait after a drop is [relay.FirstRetry] and every later one is the +// schedule's wait scaled by [relay.Jitter], so a relay restart does not bring +// every machine back in the same instant. +func spread(schedule time.Duration, first bool) time.Duration { + if first { + return relay.FirstRetry() + } + return relay.Jitter(schedule) +} + func (r *registrationLoop) wait(ctx context.Context, d time.Duration) error { if r.Wait != nil { return r.Wait(ctx, d) @@ -54,7 +66,10 @@ func (r *registrationLoop) Run(ctx context.Context) error { if r.Key == nil || r.Hold == nil { return errors.New("pair: a registration needs a key and a stream handler") } + // wait is the back-off schedule, doubled after each wait and capped at a + // minute. It is never slept as it stands: see [spread]. wait := time.Second + first := true announced := false // told and throttled are each said once per spell, not once per retry. // told is set when the person has been told sync was lost and not yet @@ -125,13 +140,15 @@ func (r *registrationLoop) Run(ctx context.Context) error { // backing off instead of hammering the relay every second. if r.now().Sub(since) >= time.Minute { wait = time.Second + first = true throttled = false } } - if err := r.wait(ctx, wait); err != nil { + if err := r.wait(ctx, spread(wait, first)); err != nil { return nil } + first = false if wait *= 2; wait > time.Minute { wait = time.Minute } diff --git a/internal/taskdoor/registration_spread_test.go b/internal/taskdoor/registration_spread_test.go new file mode 100644 index 0000000000..bb9cec4693 --- /dev/null +++ b/internal/taskdoor/registration_spread_test.go @@ -0,0 +1,62 @@ +package taskdoor + +import ( + "context" + "crypto/ecdh" + "crypto/rand" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/relay" +) + +// V22 at the task door: a relay that turns this machine's registrations away is +// retried after a spread wait, not after exactly one second, two, four. The +// first wait is one second plus a draw from the next five, and each later one is +// the doubling schedule scaled by 0.75 to 1.25, so a fleet dropped by one relay +// restart does not come back in step. +func TestTheRegistrationLoopSpreadsItsRetries(t *testing.T) { + throttled := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "too many registrations from here — wait a minute", http.StatusTooManyRequests) + })) + t.Cleanup(throttled.Close) + key, err := ecdh.X25519().GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + + ctx, stop := context.WithCancel(context.Background()) + defer stop() + var waits []time.Duration + loop := ®istrationLoop{ + Service: throttled.URL, + Key: key, + Say: func(string) {}, + Hold: func(context.Context, *relay.Registration) {}, + Wait: func(_ context.Context, d time.Duration) error { + waits = append(waits, d) + if len(waits) == 6 { + stop() + return context.Canceled + } + return nil + }, + } + if err := loop.Run(ctx); err != nil { + t.Fatalf("a loop cancelled mid-wait returned %v, want nil", err) + } + if len(waits) != 6 { + t.Fatalf("%d waits, want 6: %v", len(waits), waits) + } + if waits[0] < time.Second || waits[0] >= 6*time.Second { + t.Errorf("the first wait was %v, want it in [1s, 6s)", waits[0]) + } + for i, step := range []time.Duration{0, 2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second, 32 * time.Second}[1:] { + got := waits[i+1] + if got < step*3/4 || got >= step*5/4 { + t.Errorf("wait %d was %v, want it in [%v, %v)", i+2, got, step*3/4, step*5/4) + } + } +} diff --git a/internal/taskdoor/security_test.go b/internal/taskdoor/security_test.go index 040858b2b1..a1d9091767 100644 --- a/internal/taskdoor/security_test.go +++ b/internal/taskdoor/security_test.go @@ -346,7 +346,10 @@ func TestATaskDoorComesBackWithoutRestartingItsAttempt(t *testing.T) { t.Fatal(err) } lost, back := 0, 0 - deadline := time.NewTimer(5 * time.Second) + // The first retry after a drop comes after one second plus up to five more, + // and the retry after a failed one after up to two and a half, so the pair of + // lines can take as long as eight and a half seconds even when nothing is wrong. + deadline := time.NewTimer(15 * time.Second) defer deadline.Stop() for back == 0 { select { diff --git a/internal/teams/relay.go b/internal/teams/relay.go index a65e7641be..f83e147af3 100644 --- a/internal/teams/relay.go +++ b/internal/teams/relay.go @@ -127,5 +127,5 @@ func DeliveryRefusal(member Member, computer string) string { if who == "" { who = "This chat" } - return who + " is on " + computer + "; the message would not reach it, so continue the chat here first." + return who + " is on " + computer + "; the message would not reach it, so move the chat here first." } diff --git a/internal/tui3/app.go b/internal/tui3/app.go index a448986d6b..0f48288cba 100644 --- a/internal/tui3/app.go +++ b/internal/tui3/app.go @@ -319,6 +319,12 @@ type entry struct { // `@deepseek` gone from the model word and `▸ worked 1.6s · ctrl+e` where // the explanation should have been (session's EventRowNews). told bool + // local says this note is a sentence this window wrote about itself through + // [app.note] — a refusal, a failed move, a hand-over — which is in nobody's + // record but this screen. A live view's snapshot refresh ([app.refreshHostedReplay]) + // rebuilds every other entry from the host's transcript and puts these back, + // because a sentence the person has read must not vanish because a road swapped. + local bool // summarized says an [entryCompact] pass replaced some of the conversation // with a summary ([session.Event.Summarized]). Only such a pass stands // outside the turn's fold (workfold.go); a free one folds with the work. @@ -731,6 +737,10 @@ type ( to int earlier bool seam bool + older bool + before int + more bool + err error } // gitMsg is what the workspace's repository answered (see [gitHead]). It is // a message rather than a call because `git status` on a large tree is tens @@ -1066,8 +1076,10 @@ type app struct { // journal only ever grows at its end, so an index taken at open still names // the same block an hour of turns later — where a count back from the end // would have slid forward under every one of them. - replayFrom int - replayFloor int + replayFrom int + replayFloor int + transcriptBase int + olderMore bool // earlier is the conversation a compaction edited away — what // [session.Agent.EarlierHistory] hands over — and earlierFrom is where the // DRAWN conversation starts inside it, exactly as replayFrom names a place in @@ -2163,6 +2175,31 @@ type app struct { // is every local session — no segment, no notice, no waiting room — which is // the same absence the seam above draws when automations are off. link LinkSeam + // liveView is the seam of the conversation in front when it is a live view of a + // chat another of this person's computers runs (live.go). Nil is every other + // conversation, and with it every live-view behaviour is absent. + liveView *LiveSeam + // liveMoveFrom records the file or cell of the live view a Move was started + // from so the progress line, composer bar, and completion handlers know to + // return to or retire that live view. + liveMoveFrom string + // followRetry is the follow of a new holder this window is still trying + // after its first try found no live door open (live.go). Nil when nothing + // is being retried, which is every window that was not just displaced. + followRetry *followRetry + // followSeq numbers the displacements, so a retry timer that outlived its + // displacement finds a newer number and does nothing. + followSeq uint64 + // liveTurnTouchAt is when the live link was last told a person or a turn was + // active, so a streaming turn reports at most once a second. + liveTurnTouchAt time.Time + // armingLive makes [app.watchDriving] wait on the live seam's change channel + // instead of the link's, so the harness classifies both waits as one kind. + armingLive bool + // inRoute and liveTouchedInRoute let one routed message touch the live link + // once however many places on its path report the same action. + inRoute bool + liveTouchedInRoute bool // seal is what the door can tell this surface about the sealing of the // conversation's calls (sealseam.go). Its zero value draws nothing. seal SealSeam @@ -2356,6 +2393,9 @@ type app struct { // (homepanel_machines.go). machines chatlist.Source taker Taker + openLive func(context.Context, chatlist.Row) (Conversation, error) + remoteControl func() bool + permitAsk PermitAsker branches BranchActions machineRead machineReading machinesAsking bool @@ -2363,7 +2403,12 @@ type app struct { // machinesRetaken replaces a listing begun before a completed take, so // its late answer cannot put the previous holder back on screen. machinesRetaken bool - machinePoll machinePoll + // workspaceBeforeLive is this computer's own folder as it stood the moment a + // live view of another computer's chat came to the front, which overwrites + // [app.workspace] with that computer's folder. [app.ownWorkspace] answers it + // for Home while a live view is in front, and nothing else reads it. + workspaceBeforeLive string + machinePoll machinePoll // fleet counts this person's devices and addMachine is the home card that // uses the count (homeband_addmachine.go). fleet Fleet @@ -3122,6 +3167,9 @@ func newApp(ctx context.Context, opts Options) *app { waitForRelease: opts.WaitForRelease, machines: opts.Machines, taker: opts.Takeover, + openLive: opts.OpenLive, + remoteControl: opts.RemoteControl, + permitAsk: opts.PermitAsk, pairing: opts.Pairing, teamsPaired: opts.TeamsPaired, syncService: opts.SyncService, @@ -3662,7 +3710,7 @@ func (a *app) Init() tea.Cmd { // the loop for the reason every other reading on this list is: the walk opens // every project's index, and the paint path may never pay for one. standing := []tea.Cmd{a.takeModelCommands(), a.resumeAtLaunch, a.probeGit(), a.watchTasks(), a.watchWakes(), a.watchDesigns(), a.watchTitles(), - a.watchRuns(), a.watchQuestions(), a.loadTasks(), a.stirLane(), a.askHeld(), a.watchDriving(), a.watchFollowing(), + a.watchRuns(), a.watchQuestions(), a.loadTasks(), a.stirLane(), a.askHeld(), a.watchDriving(), a.watchFollowing(), a.armLive(), a.linkPingTick(), a.prefetchReplayedPictures(), a.countConversations(), tea.RequestBackgroundColor, // AND WHAT AUTOMATIONS HAVE BEEN DOING, read off their store on a beat of // its own (automationwatch.go): this window learns of a run whichever @@ -3870,6 +3918,12 @@ func (a *app) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // switch ever sees them and hands on everything else untouched and in the order // it arrived (coalesce.go). func (a *app) route(msg tea.Msg) (tea.Model, tea.Cmd) { + a.inRoute = true + a.liveTouchedInRoute = false + defer func() { + a.inRoute = false + a.liveTouchedInRoute = false + }() // THE LINK'S ONE-SHOT NEWS IS DRAINED HERE AND NOWHERE ELSE (hostlink.go). // The seam forgets the sentence as it hands it over, so a second caller // would not show it twice — it would swallow it. This is the one place the @@ -4057,6 +4111,7 @@ func (a *app) route(msg tea.Msg) (tea.Model, tea.Cmd) { } } a.sawAPerson() + a.touchLive() a.stirred() // AND THE HAND IS STAMPED HERE, because this is the only line every // keypress passes through, and what the question block needs to know @@ -4108,6 +4163,9 @@ func (a *app) route(msg tea.Msg) (tea.Model, tea.Cmd) { return a, tea.Batch(flushed, cmd) } } + if cmd, took := a.liveMoveKeyPress(msg); took { + return a, tea.Batch(flushed, cmd) + } // THE TRAFFIC'S KEYS READ NEXT (teamrailpointer.go): esc while its card // is over the body, and the two chords that show it and go to the // manager, which carry no text and take nothing from the box. @@ -4470,6 +4528,7 @@ func (a *app) route(msg tea.Msg) (tea.Model, tea.Cmd) { return a, nil } a.clearPlaceRowHover() + a.touchLive() a.stirred() a.placePointer.suspended = true // THE CONTEXT CHOOSER OWNS THE WHEEL WHILE IT IS UP, and it owns it over @@ -6080,6 +6139,14 @@ func (a *app) route(msg tea.Msg) (tea.Model, tea.Cmd) { // wait re-arms itself. return a, a.drivingMoved(msg) + case liveChangedMsg: + return a, a.liveMoved(msg) + + case followRetryMsg: + // One more try at following the computer that took this window's chat + // (live.go's followHolderLive). + return a, a.followRetried(msg) + case heldMsg: // The far machine's waiting room, answered. Each question is redrawn // through the door its live twin comes through, and a kind this build @@ -6184,6 +6251,7 @@ func (a *app) route(msg tea.Msg) (tea.Model, tea.Cmd) { // the next tick is scheduled. It is the ONLY place a streamed delta becomes // visible, which is what caps the repaint rate. func (a *app) paint() tea.Cmd { + a.touchLiveTurn() // ONE FRAME IS A WHOLE STRIDE OF THE ANIMATION, which is the whole of what a // slower link costs the picture: three slots pass in one frame over a // connection, so the spinner arrives where it would have been anyway and it @@ -6529,6 +6597,7 @@ func (a *app) takeStream(ch <-chan session.Event) tea.Cmd { // The turn is open and the first request is out with nothing back from it. a.awaited = time.Now() a.startClock() + a.touchLiveTurn() return tea.Batch(waitEvent(ch, a.gen), a.wake()) } @@ -6673,6 +6742,7 @@ func (a *app) applyEvent(ev session.Event, lump bool) tea.Cmd { if a.state == stateWorking { a.startClock() } + a.touchLiveTurn() // THE COLLAPSE RULE (thinking.go): the first thing a turn says that is not // reasoning ends the reasoning block. EventThinking is exempt because it is // the marker that OPENED the run — collapsing on it would close the block @@ -7483,6 +7553,7 @@ func (a *app) noteWritten(text string, block bool, facts []string) { if n := len(a.entries); n > 0 && a.entries[n-1].kind == entryNote { a.entries[n-1].told = true a.entries[n-1].stale = true + a.entries[n-1].local = true } if a.echoHome && a.at(pageHome) { a.home.say(firstLine(text), "") @@ -7623,6 +7694,7 @@ func (a *app) submittingShown(text, shown string, plain []segment, start func() // The turn is open and the first request is out with nothing back from it. a.awaited = time.Now() a.startClock() + a.touchLive() a.follow() a.touch() ctx, agent := a.ctx, a.agent @@ -8915,6 +8987,15 @@ func (a *app) takeUp(conv Conversation, whole bool) { if !whole { return } + // A LIVE VIEW'S FOLDER IS ON ANOTHER COMPUTER, and it is written over + // [app.workspace] because everything inside that conversation (its paths, its + // place, its files) is about that folder. Home is about this computer, so the + // folder this window stood in is kept for [app.ownWorkspace] at the moment a + // live view first takes the front. Leaving a live view for a local + // conversation writes that conversation's own folder back as usual. + if conv.Live != nil && a.liveView == nil { + a.workspaceBeforeLive = a.workspace + } if workspace := strings.TrimSpace(conv.Workspace); workspace != "" { a.workspace = workspace } @@ -8970,6 +9051,9 @@ func (a *app) takeUp(conv Conversation, whole bool) { if conv.Link != nil { a.link = *conv.Link } + a.liveView = conv.Live + a.liveTurnTouchAt = time.Time{} + a.syncLiveOlder() } // freshAndEmpty is the conversation nobody has used yet: nothing on screen, no diff --git a/internal/tui3/approve.go b/internal/tui3/approve.go index d0e9613c4a..8f2e3c50d1 100644 --- a/internal/tui3/approve.go +++ b/internal/tui3/approve.go @@ -50,6 +50,19 @@ type PendingDevice struct { ExpiresAt time.Time } +// DevicePermit is what another computer in this person's roster may do with +// chats on this computer. Drive is permission to type into them. +type DevicePermit struct { + Watch, Drive bool +} + +// PermitSetter is an optional face of the Approvals door that changes what +// another paired computer may do with chats on this computer. A nil pointer +// leaves that half of the permit as it is. +type PermitSetter interface { + SetPermit(id string, watch, drive *bool) error +} + // DeviceRow is one device of the fleet as the device list shows it. type DeviceRow struct { ID string @@ -57,8 +70,9 @@ type DeviceRow struct { Platform string Self bool Revoked bool - Online bool // set by the screen from the feed, not by the door - LastSeen time.Time // zero when never seen + Online bool // set by the screen from the feed, not by the door + LastSeen time.Time // zero when never seen + Permit *DevicePermit // nil when this door does not offer the switches } // Approvals is the door onto answering and revoking devices. Nil in [Options] @@ -95,7 +109,6 @@ const ( // approveAnswerTimeout covers an answer's steps: the device record, the // relay's decision, and the lookup when that reply is lost. approveAnswerTimeout = 20 * time.Second - joinedFleetWord = "%s is now paired. Your chats can continue there." ) // ErrAnswerNotArrived is an answer the door looked for after a timeout and @@ -287,6 +300,7 @@ func (c *approveCard) rows(width int, now time.Time, pal palette) []string { out = append(out, pal.accent(fit(" "+pal.glyph(info.icon)+" "+r.Name+" · "+info.word, width))) out = append(out, pal.dim(fit(" "+requestAge(r, now), width))) out = append(out, dressed(wrap(fmt.Sprintf(approveCheckWord, r.Check), max(width, 4)), pal.ink)...) + out = append(out, dressed(wrap(pair.PairedControlLine(r.Name), max(width, 4)), pal.ink)...) line := c.line if line == "" && !r.ExpiresAt.After(now) { line = approveGone @@ -413,7 +427,7 @@ func (a *app) cardKey(msg tea.KeyPressMsg) tea.Cmd { // second time. func (a *app) toastJoined(name, device string) { a.approve.markApproved(device) - a.toast(fmt.Sprintf(joinedFleetWord, name)) + a.toast(pair.ApprovedLine(name)) } // toast says a sentence where it is seen at once: in the transcript, and on @@ -459,7 +473,7 @@ func (a *app) announceJoined() { } a.approve.seq = j.Seq if !a.approve.told(j.Device) { - a.toast(fmt.Sprintf(joinedFleetWord, a.approvals.DeviceName(j.Name))) + a.toast(pair.ApprovedLine(a.approvals.DeviceName(j.Name))) } } } diff --git a/internal/tui3/approve_test.go b/internal/tui3/approve_test.go index 21f33ae8d0..e5dcf0899f 100644 --- a/internal/tui3/approve_test.go +++ b/internal/tui3/approve_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Agent-Field/codeaf/internal/dirwatch" + "github.com/Agent-Field/codeaf/internal/pair" ) // The approve screen and the device list (approve.go, devices.go). The door is @@ -136,7 +137,7 @@ func TestApproveToastsAndClosesAndTheJoinedEventIsNotToldTwice(t *testing.T) { if !strings.Contains(door.did(), "approve:k7m2q9xd") { t.Fatalf("door: %s", door.did()) } - if notes := updateNotes(a); !strings.Contains(notes, "tower is now paired. Your chats can continue there.") { + if notes := updateNotes(a); !strings.Contains(notes, pair.ApprovedLine("tower")) { t.Fatalf("no toast:\n%s", notes) } if !a.approve.told("dev_B") { @@ -144,6 +145,18 @@ func TestApproveToastsAndClosesAndTheJoinedEventIsNotToldTwice(t *testing.T) { } } +func TestApproveScreenSaysTheNewDeviceCanControlChats(t *testing.T) { + door := &fakeApprovals{pending: tower(time.Now())} + a, r := approveApp(t, door) + r.slash("/pair " + testLink) + r.until("the card", func() bool { c, ok := a.pair.card.(*approveCard); return ok && c.req != nil }) + shown := plain(frame(a)) + want := pair.PairedControlLine("tower") + if !strings.Contains(shown, want) { + t.Fatalf("approve screen lacks %q:\n%s", want, shown) + } +} + func TestDenyTurnsAwayAndEscLeavesItUndecided(t *testing.T) { door := &fakeApprovals{pending: tower(time.Now())} a, r := approveApp(t, door) @@ -232,7 +245,7 @@ func TestJoinedEventFromAnotherDeviceIsToldOnce(t *testing.T) { a.dirFeed = stillFeed{joined: []dirwatch.Joined{{Seq: 1, Device: "dev_D", Name: "sealed"}}} a.announceJoined() a.announceJoined() - if n := strings.Count(updateNotes(a), "n:sealed is now paired. Your chats can continue there."); n != 1 { + if n := strings.Count(updateNotes(a), pair.ApprovedLine("n:sealed")); n != 1 { t.Fatalf("told %d times:\n%s", n, updateNotes(a)) } } diff --git a/internal/tui3/continue_2070_test.go b/internal/tui3/continue_2070_test.go index 3460de083e..4774194c3f 100644 --- a/internal/tui3/continue_2070_test.go +++ b/internal/tui3/continue_2070_test.go @@ -257,8 +257,8 @@ func TestContinueThreeRemoteChatsInOneWindowShowsContinuingAndFullHistory(t *tes if a.homeTaking != rc.id { t.Fatalf("%s: homeTaking = %q immediately after confirm, want %q", rc.id, a.homeTaking, rc.id) } - if text := homeText(a); !strings.Contains(text, continuing) { - t.Fatalf("%s: Home did not show %q while take ran:\n%s", rc.id, continuing, text) + if text := homeText(a); !strings.Contains(text, movingHere) { + t.Fatalf("%s: Home did not show %q while take ran:\n%s", rc.id, movingHere, text) } drain(t, a, takeCmd) @@ -345,7 +345,7 @@ func TestHomeTakingClearedOnEveryEndingAndBusyPressExplainsOnCard(t *testing.T) // Press enter on another row while the first take is still running. standOn(t, a, "0000000000000204") card := strings.Join(cardRows(a), "\n") - if !strings.Contains(card, continueAlreadyRunning) { + if !strings.Contains(card, moveAlreadyRunning) { t.Fatalf("busy press did not explain on the card:\n%s\nfull Home:\n%s", card, homeText(a)) } @@ -390,7 +390,7 @@ func TestHomeTakingClearedOnEveryEndingAndBusyPressExplainsOnCard(t *testing.T) } // The card itself must remain open with the failure reason and retry. card := strings.Join(cardRows(a), "\n") - if !strings.Contains(card, continueFails) || !strings.Contains(card, continueRetry) { + if !strings.Contains(card, moveFails) || !strings.Contains(card, moveRetry) { t.Fatalf("failure not shown on card with retry:\n%s", card) } @@ -401,7 +401,7 @@ func TestHomeTakingClearedOnEveryEndingAndBusyPressExplainsOnCard(t *testing.T) if a.homeTaking != "" { t.Fatalf("chat-page failed take left homeTaking=%q", a.homeTaking) } - if notes := strings.Join(noteTexts(a), "\n"); !strings.Contains(notes, continueFails) { + if notes := strings.Join(noteTexts(a), "\n"); !strings.Contains(notes, moveFails) { t.Fatalf("chat-page failed take missing from chat notes: %q", notes) } }) @@ -454,8 +454,8 @@ func TestBusyStoreNamedWithHolderAndOffersRetry(t *testing.T) { } exeBase := filepath.Base(os.Args[0]) for _, want := range []string{ - "could not continue this chat here because the engine store is busy (held by " + exeBase + ", pid ", - continueRetry, + "could not move this chat here because the engine store is busy (held by " + exeBase + ", pid ", + moveRetry, } { if !strings.Contains(card, want) { t.Fatalf("busy store card missing %q:\n%s", want, card) @@ -473,7 +473,7 @@ func TestBusyStoreNamedWithHolderAndOffersRetry(t *testing.T) { } } -// Contract 3: Under `--host`, `continue here` is not offered and a chat the +// Contract 3: Under `--host`, `move here` is not offered and a chat the // remote host already holds never shows as held elsewhere or duplicated. func TestHostedSurfaceNeverOffersContinueOrShowsHeldElsewhere(t *testing.T) { lab := newHomeLab(t) @@ -509,7 +509,7 @@ func TestHostedSurfaceNeverOffersContinueOrShowsHeldElsewhere(t *testing.T) { } screen := homeText(a) - if strings.Contains(screen, "held on host-b") || strings.Contains(screen, chatlist.OfferContinue) || strings.Contains(screen, "Other Remote") { + if strings.Contains(screen, "held on host-b") || strings.Contains(screen, chatlist.OfferMove) || strings.Contains(screen, "Other Remote") { t.Fatalf("hosted Home showed held-elsewhere or continue offer:\n%s", screen) } if got := countHomeRowsForID(a, heldCell); got != 1 { diff --git a/internal/tui3/continue_check_failure_test.go b/internal/tui3/continue_check_failure_test.go index db27b88f3d..d1cf513053 100644 --- a/internal/tui3/continue_check_failure_test.go +++ b/internal/tui3/continue_check_failure_test.go @@ -34,7 +34,7 @@ func TestAFailedLookAtThisComputersCopyIsNotBlamedOnTheFolder(t *testing.T) { screen := homeText(a) card := strings.Join(strings.Fields(strings.NewReplacer("│", " ").Replace(strings.Join(cardRows(a), " "))), " ") - if !strings.Contains(card, continueCheckFails) { + if !strings.Contains(card, moveCheckFails) { t.Fatalf("automatic=%v: the card does not say the check failed:\n%s", automatic, screen) } if strings.Contains(screen, "could not be put in this folder") || noted(a, "could not be put in this folder") { @@ -50,7 +50,7 @@ func TestAFailedLookAtThisComputersCopyIsNotBlamedOnTheFolder(t *testing.T) { a.autoContinue = true a.machineRead.rows = []chatlist.Row{row} a.continuationReady(continuationChecked{row: row, automatic: true, generation: a.continueGeneration, err: directory.ErrLeaseHeld}) - if strings.Contains(homeText(a), continueCheckFails) { + if strings.Contains(homeText(a), moveCheckFails) { t.Fatal("a lease taken meanwhile was reported as a failed check") } } diff --git a/internal/tui3/continue_conflict_test.go b/internal/tui3/continue_conflict_test.go index e6ff2f1d97..5296b240c9 100644 --- a/internal/tui3/continue_conflict_test.go +++ b/internal/tui3/continue_conflict_test.go @@ -35,7 +35,7 @@ func TestALostRaceKeepsItsRetryCardAndDraft(t *testing.T) { } confirm(t, a) q, ok := a.homeAsking() - if !ok || q.question.Options[0].Label != continueRetry || q.question.Options[1].Label != continueStay { + if !ok || q.question.Options[0].Label != moveRetry || q.question.Options[1].Label != moveStay { t.Fatalf("missing retry card: %+v", q) } if !strings.Contains(homeText(a), lostRaceWord) || q.question.Subject.Name != src.row.Title { @@ -64,7 +64,7 @@ func TestARefreshedHoldAsksAgainInsteadOfBlamingAnotherDevice(t *testing.T) { if !ok { t.Fatalf("no refreshed card:\n%s", homeText(a)) } - if a.home.msg != "tower picked this chat up again; press enter to continue it here" { + if a.home.msg != "tower picked this chat up again; press enter to move it here" { t.Fatal(a.home.msg) } if len(taker.seen) != 1 { @@ -113,7 +113,7 @@ func TestALostRaceFromASilentReturnKeepsItsCardAndDraft(t *testing.T) { want := a.mainComposer() drive(t, a, key("enter")) q, ok := a.homeAsking() - if !a.at(pageHome) || !ok || q.question.Options[0].Label != continueRetry { + if !a.at(pageHome) || !ok || q.question.Options[0].Label != moveRetry { t.Fatalf("silent refusal has no card: %s", homeText(a)) } if len(old.sent) != 0 || !reflect.DeepEqual(a.mainComposer(), want) { diff --git a/internal/tui3/continue_fix_round_test.go b/internal/tui3/continue_fix_round_test.go index 9ec2c42870..5bdf56add0 100644 --- a/internal/tui3/continue_fix_round_test.go +++ b/internal/tui3/continue_fix_round_test.go @@ -139,7 +139,7 @@ func TestAlreadyHereRecoveryRetriesOnlyOnceAndKeepsTheDraft(t *testing.T) { cmd = tea.Batch(next...) } q, ok := a.homeAsking() - if len(f.seen) != 2 || !ok || q.question.Reason != continueFails || q.question.Options[0].Label != continueRetry || !reflect.DeepEqual(a.mainComposer(), want) { + if len(f.seen) != 2 || !ok || q.question.Reason != moveFails || q.question.Options[0].Label != moveRetry || !reflect.DeepEqual(a.mainComposer(), want) { t.Fatalf("already-here disagreement: attempts=%d card=%+v draft=%+v", len(f.seen), q, a.mainComposer()) } for _, seen := range f.seen { diff --git a/internal/tui3/continue_intent_test.go b/internal/tui3/continue_intent_test.go index 4a1528ce26..cfa96dbd4b 100644 --- a/internal/tui3/continue_intent_test.go +++ b/internal/tui3/continue_intent_test.go @@ -100,7 +100,7 @@ func TestAPersonsPickIsTheChatThatOpens(t *testing.T) { // Confirm the captured row, even if a later listing has a different ownership. standOn(t, a, rows[1].Cell) confirm(t, a) - if a.home.msg != "continuing chosen chat next; automatic chat is still on its way here" { + if a.home.msg != "moving chosen chat next; automatic chat is still on its way here" { t.Fatalf("waiting choice: %q", a.home.msg) } select { @@ -141,7 +141,7 @@ func TestPickingTheArrivingChatJoinsItsMove(t *testing.T) { cmd := beginAutomatic(t, a) a.offerContinue(rows[0], chatlist.OfferFor(rows[0])) confirm(t, a) - if strings.Contains(a.home.msg, continueAlreadyRunning) { + if strings.Contains(a.home.msg, moveAlreadyRunning) { t.Fatal(a.home.msg) } close(f.proceed) @@ -157,7 +157,7 @@ func TestAnExplicitMoveKeepsTheBusyAnswer(t *testing.T) { standOn(t, a, rows[1].Cell) confirm(t, a) q, ok := a.homeAsking() - if !ok || q.question.Reason != continueAlreadyRunning || a.home.msg != continueAlreadyRunning { + if !ok || q.question.Reason != moveAlreadyRunning || a.home.msg != moveAlreadyRunning { t.Fatalf("explicit move lost its busy card: %s", homeText(a)) } close(f.proceed) @@ -206,7 +206,7 @@ func TestAResumeChordKeepsItsChoiceBehindAnAutomaticMove(t *testing.T) { cmd := beginAutomatic(t, a) a.leftOff.row = &rows[1] drive(t, a, key(resumeKey)) - if a.home.msg != "continuing chosen chat next; automatic chat is still on its way here" { + if a.home.msg != "moving chosen chat next; automatic chat is still on its way here" { t.Fatal(a.home.msg) } close(f.proceed) diff --git a/internal/tui3/contract_real_path_test.go b/internal/tui3/contract_real_path_test.go index 2c3a49f290..041acf0f00 100644 --- a/internal/tui3/contract_real_path_test.go +++ b/internal/tui3/contract_real_path_test.go @@ -14,7 +14,7 @@ func TestC5DisplacedCellWindowOffersContinuation(t *testing.T) { typeText(t, a, "hello") drive(t, a, key("enter")) if len(agent.sent) != 0 { - t.Fatalf("cell-layout stale window sent %v instead of offering continue here; file=%s", agent.sent, a.file) + t.Fatalf("cell-layout stale window sent %v instead of offering move here; file=%s", agent.sent, a.file) } if !a.at(pageHome) { t.Fatal("no move door was shown") diff --git a/internal/tui3/defaulton_arrival_test.go b/internal/tui3/defaulton_arrival_test.go index 470b7c384c..e2abf59779 100644 --- a/internal/tui3/defaulton_arrival_test.go +++ b/internal/tui3/defaulton_arrival_test.go @@ -24,7 +24,7 @@ func TestD6EarlyBringWaitsForTheCatalog(t *testing.T) { } a.tookMachines(homeMachinesMsg{rows: []chatlist.Row{{Cell: "d6", Title: "arrived", Device: "tower", DeviceID: "dev_tower", Status: chatlist.Running}}}) ask, ok := a.homeAsking() - if !ok || !strings.Contains(ask.question.Head, "Continue this chat here?") { + if !ok || !strings.Contains(ask.question.Head, "Move this chat here?") { t.Fatalf("arrival never offered confirmation: %+v", ask) } if a.devRow.bringPending { diff --git a/internal/tui3/detach.go b/internal/tui3/detach.go index b592cd6262..b08fbce678 100644 --- a/internal/tui3/detach.go +++ b/internal/tui3/detach.go @@ -253,6 +253,7 @@ func (a *app) front() Conversation { TaskRoom: a.farRoomRecord, TaskIndex: a.farTasks, Link: &link, + Live: a.liveView, } } @@ -400,6 +401,7 @@ func (a *app) clearConversation() { // transcript being put down. [app.replay] rebuilds both on the way back — // clearing them here is what makes that the design rather than luck. a.replayFrom, a.replayFloor = 0, 0 + a.transcriptBase, a.olderMore = 0, false a.earlier, a.earlierFloor, a.earlierFrom, a.earlierSeam = nil, 0, 0, false a.transcript = nil a.historyGen++ @@ -671,7 +673,7 @@ func (a *app) attachConversation(conv Conversation, side *aside) tea.Cmd { // armed are parked on the previous one's channels and discard themselves by // generation (watching.go's [followingMsg]). cmds := []tea.Cmd{a.watchTasks(), a.watchWakes(), a.watchDesigns(), a.watchTitles(), a.watchRuns(), a.watchQuestions(), a.loadTasks(), - a.askHeld(), a.watchDriving(), a.watchFollowing(), + a.askHeld(), a.watchDriving(), a.watchFollowing(), a.armLive(), // The program rows are the engine's, so they follow the conversation (delegate.go). a.installDelegates()} diff --git a/internal/tui3/devices.go b/internal/tui3/devices.go index 716e14003d..1567e1b2aa 100644 --- a/internal/tui3/devices.go +++ b/internal/tui3/devices.go @@ -36,21 +36,39 @@ import ( ) const ( - devicesNameKey = "n rename" - devicesGoneKey = "r remove" - devicesMoveKey = "↑↓ choose" - devicesCloseKey = "esc close" - devicesNameKeys = "enter save · ctrl+u clear · esc cancel" - devicesNameAsk = "name this device: " - devicesNameOwn = "a device renames itself — choose this device's row, or open /devices on the one you mean." - devicesLoading = "looking up your devices…" - devicesRemoveKeys = "y removes · any other key keeps it" - devicesRemoveAsk = "remove %s? it must pair again to come back · " + devicesRemoveKeys - devicesRevoked = "%s was removed — it can no longer reach your chats." - devicesSelf = "this device" - devicesOwnRow = "this device cannot remove itself — choose another row." + devicesNameKey = "n rename" + devicesGoneKey = "r remove" + devicesWatchKey = "w watch" + devicesTypeKey = "t type" + devicesMoveKey = "↑↓ choose" + devicesCloseKey = "esc close" + devicesNameKeys = "enter save · ctrl+u clear · esc cancel" + devicesNameAsk = "name this device: " + devicesNameOwn = "a device renames itself — choose this device's row, or open /devices on the one you mean." + devicesLoading = "looking up your devices…" + devicesRemoveKeys = "y removes · any other key keeps it" + devicesRemoveAsk = "remove %s? it must pair again to come back · " + devicesRemoveKeys + devicesRevoked = "%s was removed — it can no longer reach your chats." + devicesSelf = "this device" + devicesOwnRow = "this device cannot remove itself — choose another row." + devicesAccessBoth = "watch and type" + devicesAccessWatch = "watch only" + devicesAccessNone = "not shared" + devicesTypeKeys = "y turns it on, any other key keeps it off" + devicesTypeAsk = "let %s type into chats on this computer? " + devicesTypeKeys + devicesWatchOnWord = "%s can watch chats on this computer." + devicesWatchOffWord = "%s can no longer watch chats on this computer." + devicesTypeOnWord = "%s can type into chats on this computer." + devicesTypeOffWord = "%s can watch, not type." + devicesPermitNoSetter = "this build cannot change that" ) +func devicesTypeAskFor(name string) string { return fmt.Sprintf(devicesTypeAsk, name) } +func devicesWatchOnFor(name string) string { return fmt.Sprintf(devicesWatchOnWord, name) } +func devicesWatchOffFor(name string) string { return fmt.Sprintf(devicesWatchOffWord, name) } +func devicesTypeOnFor(name string) string { return fmt.Sprintf(devicesTypeOnWord, name) } +func devicesTypeOffFor(name string) string { return fmt.Sprintf(devicesTypeOffWord, name) } + // deviceCard is the list's state. Online comes from the feed when the card opens. type deviceCard struct { // presence reads who is online and whether the feed can say, at each draw, @@ -68,6 +86,8 @@ type deviceCard struct { naming *string // removing freezes the chosen device across asynchronous roster refreshes. removing *DeviceRow + // allowingType freezes the chosen device while confirming permission to type. + allowingType *DeviceRow // notShared reads this computer's chats not shared yet; nil draws nothing. notShared func() (NotShared, bool) // read is the newest directory version the rows were read at, so a change another computer @@ -251,16 +271,37 @@ func (c *deviceCard) mark(id string) { } } +func (c *deviceCard) confirming() bool { + return c.removing != nil || c.allowingType != nil +} + func (c *deviceCard) hint() string { if c.removing != nil { return devicesRemoveKeys } + if c.allowingType != nil { + return devicesTypeKeys + } if c.naming != nil { return devicesNameKeys } return c.keys() } +// rowActionKeys returns the action keys offered for one device row: removal on +// another computer that is not yet removed, plus watch and type switches when +// that row carries permit information. +func (c *deviceCard) rowActionKeys(row DeviceRow) []string { + if row.Self || row.Revoked { + return nil + } + out := []string{devicesGoneKey} + if row.Permit != nil { + out = append(out, devicesWatchKey, devicesTypeKey) + } + return out +} + // keys names only what the row under the cursor can do: `r` is absent on this // device's own row and on one already removed, and the arrows when there is // no other row to walk to. @@ -273,8 +314,8 @@ func (c *deviceCard) keys() string { out = append(out, devicesMoveKey) } out = append(out, devicesNameKey) - if row, ok := c.pick(); ok && !row.Self && !row.Revoked { - out = append(out, devicesGoneKey) + if row, ok := c.pick(); ok { + out = append(out, c.rowActionKeys(row)...) } return strings.Join(append(out, devicesCloseKey), " · ") } @@ -450,18 +491,43 @@ func (d DeviceRow) dot(pal palette) string { return pal.glyph(tokens.GQueued) } +func (d DeviceRow) canEditPermit() bool { + return !d.Self && !d.Revoked && d.Permit != nil +} + +func (d DeviceRow) permitWord() string { + if !d.canEditPermit() { + return "" + } + switch { + case d.Permit.Watch && d.Permit.Drive: + return devicesAccessBoth + case d.Permit.Watch: + return devicesAccessWatch + default: + return devicesAccessNone + } +} + func (d DeviceRow) tails(now time.Time) []string { switch { case d.Revoked: return []string{"removed"} case d.Self: return []string{devicesSelf} + } + var out []string + switch { case d.Online: - return nil case d.LastSeen.IsZero(): - return []string{"offline"} + out = append(out, "offline") + default: + out = append(out, seenTail(d.LastSeen, now)) + } + if word := d.permitWord(); word != "" { + out = append(out, word) } - return []string{seenTail(d.LastSeen, now)} + return out } // seenTail is when an away device was last seen, in words that read whole: @@ -487,6 +553,16 @@ func (c *deviceCard) key(a *app, name string) (tea.Cmd, bool) { } return nil, false } + if c.allowingType != nil { + row := *c.allowingType + c.allowingType, c.line = nil, "" + c.keepCursorOn(row.ID, true) + if name == "y" { + a.setDevicePermit(c, row, boolPtr(true), boolPtr(true), DevicePermit{Watch: true, Drive: true}, devicesTypeOnFor(c.shownName(row))) + } + a.syncSheetDeviceCard(c, false) + return nil, false + } move, isMove := cursorMoves[name] switch { case name == "esc": @@ -500,10 +576,77 @@ func (c *deviceCard) key(a *app, name string) (tea.Cmd, bool) { c.startNaming() case name == "r": return a.revoke(c), false + case name == "w": + a.toggleDeviceWatch(c) + case name == "t": + a.toggleDeviceType(c) } return nil, false } +func boolPtr(v bool) *bool { return &v } + +func (a *app) permitSetter() PermitSetter { + setter, _ := a.approvals.(PermitSetter) + return setter +} + +func (a *app) toggleDeviceWatch(c *deviceCard) { + row, ok := c.pick() + if !ok || !row.canEditPermit() { + return + } + name := c.shownName(row) + if row.Permit.Watch { + a.setDevicePermit(c, row, boolPtr(false), boolPtr(false), DevicePermit{Watch: false, Drive: false}, devicesWatchOffFor(name)) + return + } + a.setDevicePermit(c, row, boolPtr(true), nil, DevicePermit{Watch: true, Drive: row.Permit.Drive}, devicesWatchOnFor(name)) +} + +func (a *app) toggleDeviceType(c *deviceCard) { + row, ok := c.pick() + if !ok || !row.canEditPermit() { + return + } + name := c.shownName(row) + if row.Permit.Drive { + a.setDevicePermit(c, row, nil, boolPtr(false), DevicePermit{Watch: true, Drive: false}, devicesTypeOffFor(name)) + return + } + if a.permitSetter() == nil { + c.line = devicesPermitNoSetter + a.syncSheetDeviceCard(c, false) + return + } + c.allowingType = &row + c.line = devicesTypeAskFor(name) + a.syncSheetDeviceCard(c, false) +} + +func (a *app) setDevicePermit(c *deviceCard, row DeviceRow, watch, drive *bool, next DevicePermit, said string) { + setter := a.permitSetter() + if setter == nil { + c.line = devicesPermitNoSetter + a.syncSheetDeviceCard(c, false) + return + } + if err := setter.SetPermit(row.ID, watch, drive); err != nil { + c.line = err.Error() + a.syncSheetDeviceCard(c, false) + return + } + for i := range c.rowsOf { + if c.rowsOf[i].ID == row.ID { + permit := next + c.rowsOf[i].Permit = &permit + break + } + } + c.line = said + a.syncSheetDeviceCard(c, false) +} + var cursorMoves = map[string]int{"up": -1, "k": -1, "down": 1, "j": 1} // revoke asks about the picked device before any membership changes. Its own diff --git a/internal/tui3/devices_permit_test.go b/internal/tui3/devices_permit_test.go new file mode 100644 index 0000000000..2bd697fca8 --- /dev/null +++ b/internal/tui3/devices_permit_test.go @@ -0,0 +1,392 @@ +package tui3 + +import ( + "errors" + "strings" + "testing" + "time" +) + +type fakePermitApprovals struct { + *fakeApprovals + setErr error +} + +func (f *fakePermitApprovals) SetPermit(id string, watch, drive *bool) error { + w := "nil" + if watch != nil { + if *watch { + w = "true" + } else { + w = "false" + } + } + d := "nil" + if drive != nil { + if *drive { + d = "true" + } else { + d = "false" + } + } + f.log("permit:" + id + ":w=" + w + ":d=" + d) + if f.setErr != nil { + return f.setErr + } + f.mu.Lock() + defer f.mu.Unlock() + for i := range f.devices { + if f.devices[i].ID == id && f.devices[i].Permit != nil { + p := *f.devices[i].Permit + if watch != nil { + p.Watch = *watch + } + if drive != nil { + p.Drive = *drive + } + f.devices[i].Permit = &p + } + } + return nil +} + +func permitDevicesDoor(now time.Time) *fakePermitApprovals { + return &fakePermitApprovals{ + fakeApprovals: &fakeApprovals{ + devices: []DeviceRow{ + {ID: "dev_A", Name: "this mac", Platform: "darwin", Self: true, Permit: &DevicePermit{Watch: true, Drive: true}}, + {ID: "dev_B", Name: "tower", Platform: "linux", Permit: &DevicePermit{Watch: true, Drive: true}}, + {ID: "dev_C", Name: "desk", Platform: "darwin", LastSeen: now.Add(-3 * time.Hour), Permit: &DevicePermit{Watch: true, Drive: false}}, + {ID: "dev_D", Name: "vault", Platform: "linux", LastSeen: now.Add(-5 * time.Hour), Permit: &DevicePermit{Watch: false, Drive: false}}, + {ID: "dev_E", Name: "plain", Platform: "linux", LastSeen: now.Add(-6 * time.Hour)}, + {ID: "dev_F", Name: "old", Platform: "linux", Revoked: true, Permit: &DevicePermit{Watch: true, Drive: true}}, + }, + }, + } +} + +// V11/V25/T13 (contract 1): another computer's row with Permit != nil shows its +// access word (`watch and type`, `watch only`, or `not shared`) and adds +// `w watch` and `t type` before `esc close`, while this computer's own row, an +// `Add another device` row, a removed row, and rows with Permit == nil show neither. +func TestDevicesPermitRowsAndKeysAppearOnlyForAnotherComputerWithPermit(t *testing.T) { + now := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) + door := permitDevicesDoor(now) + a, r := approveApp(t, door) + a.width = 110 + a.clock = func() time.Time { return now } + a.dirFeed = stillFeed{online: []string{"dev_B"}} + + r.slash("/devices") + r.until("the device list", func() bool { c, ok := a.pair.card.(*deviceCard); return ok && c.loaded }) + + screen := plain(frame(a)) + for _, want := range []string{ + "tower", devicesAccessBoth, + "desk", devicesAccessWatch, + "vault", devicesAccessNone, + } { + if !strings.Contains(screen, want) { + t.Fatalf("/devices screen lacked %q:\n%s", want, screen) + } + } + for _, line := range strings.Split(screen, "\n") { + if strings.Contains(line, "this mac") || strings.Contains(line, "plain") || strings.Contains(line, "old") || strings.Contains(line, addDeviceWord) { + for _, access := range []string{devicesAccessBoth, devicesAccessWatch, devicesAccessNone} { + if strings.Contains(line, access) { + t.Fatalf("row %q unexpectedly drew access word %q", line, access) + } + } + } + } + + // Row 0: this mac (Self) -> no w watch or t type. + if hint := a.hintWord(); strings.Contains(hint, devicesWatchKey) || strings.Contains(hint, devicesTypeKey) { + t.Fatalf("own row offered watch/type keys: %q", hint) + } + + // Row 1: tower (online, Permit != nil) -> w watch and t type before esc close. + r.press("down") + hint := a.hintWord() + wAt := strings.Index(hint, devicesWatchKey) + tAt := strings.Index(hint, devicesTypeKey) + closeAt := strings.Index(hint, devicesCloseKey) + if wAt < 0 || tAt < 0 || closeAt < 0 || !(wAt < tAt && tAt < closeAt) { + t.Fatalf("tower row keys = %q, want %q and %q before %q", hint, devicesWatchKey, devicesTypeKey, devicesCloseKey) + } + + // Row 2: desk (offline, Permit != nil) -> offers w watch and t type. + r.press("down") + if hint := a.hintWord(); !strings.Contains(hint, devicesWatchKey) || !strings.Contains(hint, devicesTypeKey) { + t.Fatalf("desk row keys = %q, want watch and type keys", hint) + } + + // Row 3: old (Revoked) -> no w watch or t type. + r.press("down") + if hint := a.hintWord(); strings.Contains(hint, devicesWatchKey) || strings.Contains(hint, devicesTypeKey) { + t.Fatalf("revoked row offered watch/type keys: %q", hint) + } + + // Row 4: plain (Permit == nil) -> no w watch or t type. + r.press("down") + if hint := a.hintWord(); strings.Contains(hint, devicesWatchKey) || strings.Contains(hint, devicesTypeKey) { + t.Fatalf("row with Permit == nil offered watch/type keys: %q", hint) + } + + // Row 5: vault (Permit != nil) -> offers w watch and t type. + r.press("down") + if hint := a.hintWord(); !strings.Contains(hint, devicesWatchKey) || !strings.Contains(hint, devicesTypeKey) { + t.Fatalf("vault row keys = %q, want watch and type keys", hint) + } + + // Row 6: Add another device -> no w watch or t type. + r.press("down") + if hint := a.hintWord(); strings.Contains(hint, devicesWatchKey) || strings.Contains(hint, devicesTypeKey) { + t.Fatalf("Add another device row offered watch/type keys: %q", hint) + } +} + +// V11/V25/T13 (contract 2 and 3): `w` toggles watch on and off at once, and `t` +// turns type off at once and asks for `y` confirmation before turning type on. +func TestDevicesPermitWatchAndTypeSwitchesUpdateAtOnceAndConfirmTurningTypeOn(t *testing.T) { + now := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) + door := &fakePermitApprovals{ + fakeApprovals: &fakeApprovals{ + devices: []DeviceRow{ + {ID: "dev_A", Name: "this mac", Platform: "darwin", Self: true}, + {ID: "dev_B", Name: "tower", Platform: "linux", Permit: &DevicePermit{Watch: true, Drive: true}}, + }, + }, + } + a, r := approveApp(t, door) + a.width = 110 + a.clock = func() time.Time { return now } + a.dirFeed = stillFeed{online: []string{"dev_B"}} + + r.slash("/devices") + r.until("the device list", func() bool { c, ok := a.pair.card.(*deviceCard); return ok && c.loaded }) + + // Move to tower (watch and type). + r.press("down") + if !strings.Contains(plain(frame(a)), devicesAccessBoth) { + t.Fatalf("expected tower to start as %q:\n%s", devicesAccessBoth, plain(frame(a))) + } + + // 1. w: watch on -> off calls SetPermit(id, &false, &false), updates row to not shared. + r.press("w") + if got := door.did(); got != "permit:dev_B:w=false:d=false" { + t.Fatalf("w on->off calls = %q, want permit:dev_B:w=false:d=false", got) + } + screen := plain(frame(a)) + if !strings.Contains(screen, devicesAccessNone) || !strings.Contains(screen, devicesWatchOffFor("tower")) { + t.Fatalf("after watch off screen lacked %q or %q:\n%s", devicesAccessNone, devicesWatchOffFor("tower"), screen) + } + + // 2. w: watch off -> on calls SetPermit(id, &true, nil), updates row to watch only. + door.calls = nil + r.press("w") + if got := door.did(); got != "permit:dev_B:w=true:d=nil" { + t.Fatalf("w off->on calls = %q, want permit:dev_B:w=true:d=nil", got) + } + screen = plain(frame(a)) + if !strings.Contains(screen, devicesAccessWatch) || !strings.Contains(screen, devicesWatchOnFor("tower")) { + t.Fatalf("after watch on screen lacked %q or %q:\n%s", devicesAccessWatch, devicesWatchOnFor("tower"), screen) + } + + // 3. t: type off -> on first asks confirmation; any key other than y (including n and esc) cancels. + door.calls = nil + r.press("t") + if door.did() != "" { + t.Fatalf("t off->on called SetPermit before confirmation: %s", door.did()) + } + wantAsk := devicesTypeAskFor("tower") + if !strings.Contains(plain(frame(a)), wantAsk) || a.hintWord() != devicesTypeKeys { + t.Fatalf("t off->on did not show confirmation %q (hint=%q):\n%s", wantAsk, a.hintWord(), plain(frame(a))) + } + r.press("n") + if door.did() != "" || !a.pair.open || !strings.Contains(plain(frame(a)), devicesAccessWatch) { + t.Fatalf("n did not cancel cleanly: calls=%q open=%t\n%s", door.did(), a.pair.open, plain(frame(a))) + } + + // esc also cancels the confirmation without closing /devices. + r.press("t", "esc") + if door.did() != "" || !a.pair.open || !strings.Contains(plain(frame(a)), devicesAccessWatch) { + t.Fatalf("esc during type confirmation closed /devices or changed permit: calls=%q open=%t\n%s", door.did(), a.pair.open, plain(frame(a))) + } + + // 4. t then y confirms: calls SetPermit(id, &true, &true) and says tower can type. + r.press("t", "y") + if got := door.did(); got != "permit:dev_B:w=true:d=true" { + t.Fatalf("t+y calls = %q, want permit:dev_B:w=true:d=true", got) + } + screen = plain(frame(a)) + if !strings.Contains(screen, devicesAccessBoth) || !strings.Contains(screen, devicesTypeOnFor("tower")) { + t.Fatalf("after t+y screen lacked %q or %q:\n%s", devicesAccessBoth, devicesTypeOnFor("tower"), screen) + } + + // 5. t: type on -> off is immediate: calls SetPermit(id, nil, &false) and says tower can watch, not type. + door.calls = nil + r.press("t") + if got := door.did(); got != "permit:dev_B:w=nil:d=false" { + t.Fatalf("t on->off calls = %q, want permit:dev_B:w=nil:d=false", got) + } + screen = plain(frame(a)) + if !strings.Contains(screen, devicesAccessWatch) || !strings.Contains(screen, devicesTypeOffFor("tower")) { + t.Fatalf("after t on->off screen lacked %q or %q:\n%s", devicesAccessWatch, devicesTypeOffFor("tower"), screen) + } +} + +// V11/T13 (contract 4): when the Approvals door has no PermitSetter or +// SetPermit returns an error, `w` and `t` say the error (or `this build cannot +// change that`) and nothing changes on screen. +func TestDevicesPermitErrorsAndMissingSetterLeaveTheScreenUnchanged(t *testing.T) { + now := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) + + // 1. Door without PermitSetter. + noSetter := &fakeApprovals{ + devices: []DeviceRow{ + {ID: "dev_A", Name: "this mac", Platform: "darwin", Self: true}, + {ID: "dev_B", Name: "tower", Platform: "linux", Permit: &DevicePermit{Watch: true, Drive: false}}, + }, + } + a, r := approveApp(t, noSetter) + a.width = 110 + a.clock = func() time.Time { return now } + r.slash("/devices") + r.until("the device list", func() bool { c, ok := a.pair.card.(*deviceCard); return ok && c.loaded }) + + r.press("down", "w") + if !strings.Contains(plain(frame(a)), devicesPermitNoSetter) || !strings.Contains(plain(frame(a)), devicesAccessWatch) { + t.Fatalf("w without PermitSetter did not say %q or changed row:\n%s", devicesPermitNoSetter, plain(frame(a))) + } + a.openDevicesCard().line = "" + r.press("t") + if !strings.Contains(plain(frame(a)), devicesPermitNoSetter) || !strings.Contains(plain(frame(a)), devicesAccessWatch) { + t.Fatalf("t without PermitSetter did not say %q or changed row:\n%s", devicesPermitNoSetter, plain(frame(a))) + } + + // 2. Door whose SetPermit returns an error. + wantErr := "could not save device permissions" + failing := &fakePermitApprovals{ + fakeApprovals: &fakeApprovals{ + devices: []DeviceRow{ + {ID: "dev_A", Name: "this mac", Platform: "darwin", Self: true}, + {ID: "dev_B", Name: "tower", Platform: "linux", Permit: &DevicePermit{Watch: true, Drive: false}}, + }, + }, + setErr: errors.New(wantErr), + } + a2, r2 := approveApp(t, failing) + a2.width = 110 + a2.clock = func() time.Time { return now } + r2.slash("/devices") + r2.until("the device list", func() bool { c, ok := a2.pair.card.(*deviceCard); return ok && c.loaded }) + + r2.press("down", "w") + if !strings.Contains(plain(frame(a2)), wantErr) || !strings.Contains(plain(frame(a2)), devicesAccessWatch) { + t.Fatalf("w error did not show %q or changed row:\n%s", wantErr, plain(frame(a2))) + } + a2.openDevicesCard().line = "" + r2.press("t", "y") + if !strings.Contains(plain(frame(a2)), wantErr) || !strings.Contains(plain(frame(a2)), devicesAccessWatch) { + t.Fatalf("t+y error did not show %q or changed row:\n%s", wantErr, plain(frame(a2))) + } +} + +// V11/V25/T13 (contract 1-4): the Settings > Devices tab shares the same words, +// key legend, confirmation and permit updates as the `/devices` card. +func TestTheDevicesCardAndTheSettingsTabOfferTheSameSwitches(t *testing.T) { + now := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) + door := &fakePermitApprovals{ + fakeApprovals: &fakeApprovals{ + devices: []DeviceRow{ + {ID: "dev_A", Name: "this mac", Platform: "darwin", Self: true}, + {ID: "dev_B", Name: "tower", Platform: "linux", Permit: &DevicePermit{Watch: true, Drive: false}}, + }, + }, + } + a, r := openSettingsDevices(t, door, now) + a.width = 120 + + // Own row has no watch or type keys. + if keys := a.sheet.keysLine(); strings.Contains(keys, devicesWatchKey) || strings.Contains(keys, devicesTypeKey) { + t.Fatalf("Settings Devices own row offered watch/type keys: %q", keys) + } + + // Move to tower (watch only). + r.press("down") + keys := a.sheet.keysLine() + if !strings.Contains(keys, devicesWatchKey) || !strings.Contains(keys, devicesTypeKey) { + t.Fatalf("Settings Devices tower row keys = %q", keys) + } + if !strings.Contains(plain(frame(a)), devicesAccessWatch) { + t.Fatalf("Settings Devices lacked %q:\n%s", devicesAccessWatch, plain(frame(a))) + } + + // t asks confirmation; esc cancels without closing Settings. + r.press("t") + if got := a.sheet.keysLine(); got != devicesTypeKeys { + t.Fatalf("Settings Devices type confirmation keys = %q, want %q", got, devicesTypeKeys) + } + if !strings.Contains(plain(frame(a)), devicesTypeAskFor("tower")) { + t.Fatalf("Settings Devices lacked confirmation ask:\n%s", plain(frame(a))) + } + r.press("esc") + if !a.at(pageSettings) || !a.sheet.onDevices() || door.did() != "" { + t.Fatalf("esc during Settings Devices type confirmation closed settings or called door: atSettings=%t calls=%q", a.at(pageSettings), door.did()) + } + + // t then y turns type on. + r.press("t", "y") + if got := door.did(); got != "permit:dev_B:w=true:d=true" { + t.Fatalf("Settings Devices t+y calls = %q", got) + } + screen := plain(frame(a)) + if !strings.Contains(screen, devicesAccessBoth) || !strings.Contains(screen, devicesTypeOnFor("tower")) { + t.Fatalf("Settings Devices after t+y lacked %q or %q:\n%s", devicesAccessBoth, devicesTypeOnFor("tower"), screen) + } + + // w turns watch (and type) off. + door.calls = nil + r.press("w") + if got := door.did(); got != "permit:dev_B:w=false:d=false" { + t.Fatalf("Settings Devices w calls = %q", got) + } + screen = plain(frame(a)) + if !strings.Contains(screen, devicesAccessNone) || !strings.Contains(screen, devicesWatchOffFor("tower")) { + t.Fatalf("Settings Devices after w lacked %q or %q:\n%s", devicesAccessNone, devicesWatchOffFor("tower"), screen) + } +} + +// V14/T13 (absent path): when DeviceRow.Permit is nil on every row, both the +// `/devices` card and the Settings > Devices tab are unchanged. +func TestWithoutPermitInfoTheDevicesScreensAreUnchanged(t *testing.T) { + now := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) + door := devicesFake() + a, r := approveApp(t, door) + a.clock = func() time.Time { return now } + + r.slash("/devices") + r.until("the device list", func() bool { c, ok := a.pair.card.(*deviceCard); return ok && c.loaded }) + r.press("down") + + screen := plain(frame(a)) + for _, access := range []string{devicesAccessBoth, devicesAccessWatch, devicesAccessNone} { + if strings.Contains(screen, access) { + t.Fatalf("/devices without Permit drew %q:\n%s", access, screen) + } + } + if hint := a.hintWord(); strings.Contains(hint, devicesWatchKey) || strings.Contains(hint, devicesTypeKey) { + t.Fatalf("/devices without Permit offered watch/type keys: %q", hint) + } + r.press("w", "t") + if door.did() != "" || a.openDevicesCard().line != "" { + t.Fatalf("w/t on row with nil Permit acted: calls=%q line=%q", door.did(), a.openDevicesCard().line) + } + + sApp, sRig := openSettingsDevices(t, devicesFake(), now) + sRig.press("down") + if keys := sApp.sheet.keysLine(); strings.Contains(keys, devicesWatchKey) || strings.Contains(keys, devicesTypeKey) { + t.Fatalf("Settings Devices without Permit offered watch/type keys: %q", keys) + } +} diff --git a/internal/tui3/displaced_watch_test.go b/internal/tui3/displaced_watch_test.go index 82f6039121..b16cfe7a6a 100644 --- a/internal/tui3/displaced_watch_test.go +++ b/internal/tui3/displaced_watch_test.go @@ -48,7 +48,7 @@ func TestKnownDisplacementOutranksTheCachedWriterHold(t *testing.T) { desk.Say(chatlist.Superseded("other computer")) a.saidNotices() } - if !strings.Contains(plain(lastNote(t, a)), "continued this chat") { + if !strings.Contains(plain(lastNote(t, a)), "moved this chat") { t.Fatal("displacement was not shown") } a.input.setText("keep these words unsent") diff --git a/internal/tui3/foot.go b/internal/tui3/foot.go index 994eed6f64..33762a0551 100644 --- a/internal/tui3/foot.go +++ b/internal/tui3/foot.go @@ -519,14 +519,14 @@ func (a *app) seamPieces(width int) seamPieces { // AND A PINNED LANE RIDES THE ID AS `@lane` ([app.modelWord]), which is the // one place the pin is written on the chrome: the status row and the phone // deck take the same word from the same function. - pieces := seamPieces{host: a.host, model: a.modelWord(), exchange: a.modelCycleSuffix(), + pieces := seamPieces{host: a.seamHost(), model: a.modelWord(), exchange: a.modelCycleSuffix(), project: a.seamProjectWord()} // AND IN A MANAGED TEAM THE SLOT SAYS WHERE THE WORDS GO, once there are // words: the empty box says it as its placeholder (teamrailpointer.go's // [app.trafficHint]), and the first keystroke took the placeholder away with // the one fact a person typing to a team needs. `to ◆ manager`, or // `to @web` with a member in front. - if !a.input.empty() { + if !a.input.empty() && a.liveFront() == nil { pieces.name = a.trafficHint() } if pieces.model != "" { diff --git a/internal/tui3/home.go b/internal/tui3/home.go index d87d23e843..f1f6993786 100644 --- a/internal/tui3/home.go +++ b/internal/tui3/home.go @@ -747,7 +747,8 @@ type homeView struct { // nil (homeconfirm.go). It is not on the block: home takes the frame whole, // so the block's rows are not on screen here, and a card home raised about a // row on home is not a thing to meet after walking away from home. - ask *questionShown + ask *questionShown + permitAsked bool // tier is which of home's three shapes this frame has room for — the list // alone, the list and a card, or the zones in a column of their own beside @@ -1262,7 +1263,7 @@ func (a *app) newHomeView(world session.World, known bool) homeView { // wears `here` instead of an age (place_home.go). bucket: homeBucketOf(a.file), here: homeSessionDirOf(a.file), - launch: a.workspace, + launch: a.ownWorkspace(), // AND THE CONVERSATION THIS WINDOW HAS ASKED FOR, if there is one. // Raising home builds a fresh [homeView], and a claim that survived // somebody walking to another page and back must survive with it — @@ -1343,6 +1344,7 @@ func (a *app) furnishHome() { // on the beat this is a rescan and a rebuild and nothing else. a.home.build() a.rememberHomeReading() + a.considerPermitAsk() } // placesRoot is where the projects live. The field is the test's door and @@ -2540,7 +2542,7 @@ func (a *app) homeKey(msg tea.KeyPressMsg) tea.Cmd { if a.cancelTakeover() { return nil } - if a.cancelHomeTake() { + if a.liveMoveFrom == "" && a.cancelHomeTake() { return nil } // THE @ LIST IS INNER TO THE BOX, and so it goes first. It is drawn diff --git a/internal/tui3/home_async.go b/internal/tui3/home_async.go index d965fd9177..7122987df8 100644 --- a/internal/tui3/home_async.go +++ b/internal/tui3/home_async.go @@ -42,6 +42,7 @@ func (a *app) furnishHomeCached() { } a.machine.hands, a.machine.wants = machineCounts(a.now(), a.home.world.Sessions(), a.exchanges) a.home.build() + a.considerPermitAsk() } func (a *app) refreshHomeLater() tea.Cmd { diff --git a/internal/tui3/home_local_open.go b/internal/tui3/home_local_open.go index 1a602b3420..438a0a10a1 100644 --- a/internal/tui3/home_local_open.go +++ b/internal/tui3/home_local_open.go @@ -74,7 +74,7 @@ func (a *app) homeLocalOpenReady(msg homeLocalOpenMsg) tea.Cmd { continue } if row.AutoOpen || heldElsewhere(row) && msg.line.row.Transcript != a.file && !a.holding(msg.line.row.Transcript) { - return tea.Batch(recorded, a.homeMachineEnter(homeLine{remote: &row})) + return tea.Batch(recorded, a.homeMachineMove(homeLine{remote: &row})) } break } diff --git a/internal/tui3/homeband_devices.go b/internal/tui3/homeband_devices.go index cdf8b23098..66fb1df729 100644 --- a/internal/tui3/homeband_devices.go +++ b/internal/tui3/homeband_devices.go @@ -15,8 +15,8 @@ package tui3 // // ONE CHORD OFFERS THE WORK. It picks the newest chat an online device holds // and raises the takeover card home already has ([app.homeMachineEnter]): the -// verb is Move here for a chat that device is running and Continue here for one -// it let go of ([chatlist.VerbFor]). With several devices in reach the chord +// verb is Move here, whether that device is running the chat or let it go +// ([chatlist.MoveHere]). With several devices in reach the chord // asks which first. import ( @@ -39,9 +39,9 @@ type Roster interface { const ( // deviceKey is the chord that brings a device's work here. deviceKey = "alt+m" - deviceBring = deviceKey + " bring work here" + deviceBring = deviceKey + " move here" deviceArriving = "chats are still arriving from your other computer; this opens when they are ready" - deviceNothing = "no other device that is online has a chat to bring here" + deviceNothing = "no other device that is online has a chat to move here" devicePickAsk = "Which device?" devicePickLeav = "leave it there" deviceGap = " " @@ -60,12 +60,21 @@ type deviceRoster struct { devices []chatlist.Device asking bool bringPending bool + // Asked counts the reads started, so an answer can say which ask it is. + asked uint64 + // Enter is an Enter on a chat held elsewhere that is waiting for a roster + // read begun after it, and EnterAfter is the first ask that counts. See + // [app.homeMachineEnter] for why Enter waits. + enter *homeLine + enterAfter uint64 } -// rosterMsg is one answer from the [Roster]. +// rosterMsg is one answer from the [Roster], carrying the count of the ask it +// answers. type rosterMsg struct { devices []chatlist.Device err error + seq uint64 } // askRoster lists the devices, off the update loop. One ask is out at a time. @@ -78,11 +87,13 @@ func (a *app) askRoster() tea.Cmd { return nil } a.devRow.asking = true + a.devRow.asked++ + seq := a.devRow.asked return func() tea.Msg { ctx, cancel := context.WithTimeout(context.Background(), fleetAskTimeout) defer cancel() devices, err := src.Roster(ctx) - return rosterMsg{devices: devices, err: err} + return rosterMsg{devices: devices, err: err, seq: seq} } } @@ -94,10 +105,83 @@ func (a *app) tookRoster(msg rosterMsg) tea.Cmd { a.devRow.version++ } a.devRow.devices = msg.devices + a.machineRead.rows = a.withHolderSeen(a.machineRead.rows) a.considerResume() + a.rebuildMachines() a.touch() } - return a.finishBring() + return tea.Batch(a.finishBring(), a.finishEnter(msg)) +} + +// rosterCanAdmit says a chat's holder is unknown only because the roster has not +// said so yet: everything else that makes a held chat open live is true, a +// roster can be asked, and the holder is not in the one last read. Such a chat +// waits for a fresh read instead of being refused. +func (a *app) rosterCanAdmit(row chatlist.Row) bool { + if _, ok := a.fleet.(Roster); !ok || !a.liveOffered() || a.hosted() { + return false + } + if a.machineRead.computerRemoved || row.HolderRemoved || !heldElsewhere(row) { + return false + } + for _, d := range a.devRow.devices { + if (row.DeviceID != "" && d.ID == row.DeviceID) || (row.DeviceID == "" && row.Device != "" && d.Name == row.Device) { + return false + } + } + return true +} + +// waitForRoster holds an Enter on a held chat until a roster read that began +// after the Enter has landed, and starts that read. A second Enter while one +// waits changes nothing. It answers false when no read can be asked. +func (a *app) waitForRoster(line homeLine) (tea.Cmd, bool) { + if a.devRow.enter != nil { + return nil, true + } + a.devRow.enterAfter = a.devRow.asked + 1 + if !a.devRow.asking { + ask := a.askRoster() + if ask == nil { + return nil, false + } + a.devRow.enter = &line + return ask, true + } + a.devRow.enter = &line + return nil, true +} + +// finishEnter settles the Enter that waited for the roster. An answer to a read +// begun before the Enter asks again, because it may predate the holder; the +// first answer that begun after it decides: live when the holder is a computer +// of the roster, the Move card when it is not or the roster cannot be read. +func (a *app) finishEnter(msg rosterMsg) tea.Cmd { + line := a.devRow.enter + if line == nil || line.remote == nil { + a.devRow.enter = nil + return nil + } + if msg.seq < a.devRow.enterAfter { + if ask := a.askRoster(); ask != nil { + return ask + } + } + a.devRow.enter = nil + if !a.at(pageHome) || a.hosted() { + return nil + } + row := *line.remote + for _, fresh := range a.machineRead.rows { + if fresh.Cell == row.Cell { + row = fresh + break + } + } + if a.liveEligible(row) { + return a.homeOpenLiveLater(*line, row) + } + return a.homeMachineMove(*line) } // presence is who the feed says is online, and whether it can say at all. @@ -199,7 +283,7 @@ func (a *app) bringWork() tea.Cmd { a.home.say(deviceNothing, "") return nil case 1: - return a.homeMachineEnter(machineEntry(picks[0])) + return a.homeMachineMove(machineEntry(picks[0])) } a.raiseMachineAsk(picks[0], a.devicePickShown(picks)) return nil @@ -229,7 +313,7 @@ func (a *app) devicePickShown(picks []chatlist.Row) questionShown { local: func(answer session.Answer) tea.Cmd { for i, row := range picks { if answer.FirstKey() == string(rune('1'+i)) { - return a.homeMachineEnter(machineEntry(row)) + return a.homeMachineMove(machineEntry(row)) } } return nil diff --git a/internal/tui3/homeband_devices_test.go b/internal/tui3/homeband_devices_test.go index 6bbdd93de7..89b56a4bbd 100644 --- a/internal/tui3/homeband_devices_test.go +++ b/internal/tui3/homeband_devices_test.go @@ -97,12 +97,12 @@ func TestOnlineDeviceOffersMoveHereForARunningChat(t *testing.T) { t.Fatalf("no takeover card for tower's chat: %+v", ask.question) } if ask.pick != continueYesAt { - t.Fatalf("Move here left the cursor on %d, not on `continue here`", ask.pick) + t.Fatalf("Move here left the cursor on %d, not on `move here`", ask.pick) } - if got := chatlist.VerbFor(a.machineRead.rows[0]); got != "Move here" { + if got := chatlist.VerbFrom(a.machineRead.rows[0]); !strings.HasPrefix(got, "Move here") { t.Fatalf("a running chat offers %q", got) } - if got := chatlist.VerbFor(a.machineRead.rows[1]); got != "Continue here" { + if got := chatlist.VerbFrom(a.machineRead.rows[1]); !strings.HasPrefix(got, "Move here") { t.Fatalf("a chat that went off offers %q", got) } } @@ -119,7 +119,7 @@ func TestSeveralOnlineDevicesAskWhichAndThenOfferTheCard(t *testing.T) { for _, o := range ask.question.Options { labels = append(labels, o.Label) } - if want := "Move here from tower|Continue here from desk|leave it there"; strings.Join(labels, "|") != want { + if want := "Move here from tower|Move here from desk|leave it there"; strings.Join(labels, "|") != want { t.Fatalf("picker options %q", labels) } ask.local(session.Answer{Key: "2", Picked: []string{"2"}}) diff --git a/internal/tui3/homeband_resume.go b/internal/tui3/homeband_resume.go index 30ad5fc8cd..4b81424c3a 100644 --- a/internal/tui3/homeband_resume.go +++ b/internal/tui3/homeband_resume.go @@ -52,8 +52,8 @@ const ( // where the person left off. resumeRecent = 24 * time.Hour - resumeAskFormat = "Continue %s's latest chat here?" - resumeYes = resumeKey + " continue here" + resumeAskFormat = "Move %s's latest chat here?" + resumeYes = resumeKey + " move here" resumeNo = resumeSkipKey + " not now" bandOrderResume = 2 // above everything: it is the first thing worth doing @@ -189,7 +189,7 @@ func (a *app) resumeKeyHandler(key string) (tea.Cmd, bool) { a.touch() if a.homeTaking != "" && !a.homeTakeAutomatic { a.raiseMachineAsk(*row, a.continueBusyShown(*row)) - a.home.say(continueAlreadyRunning, "") + a.home.say(moveAlreadyRunning, "") return nil, true } if a.homeTakeAutomatic && row.Cell == a.homeTaking && (!a.homeTakeAbandoned || a.homeTakeResult == nil) { @@ -237,7 +237,7 @@ func (a *app) continueIfSafe(row chatlist.Row, safe continuationSafety) tea.Cmd choice := a.nextContinueAskID() a.continueChecking = &continuationChecked{row: row, generation: choice} if a.homeTakeAutomatic && a.homeTaking != "" { - a.home.say(fmt.Sprintf("continuing %s next; %s is still on its way here", row.Title, a.homeTakeRow.Title), "") + a.home.say(fmt.Sprintf("moving %s next; %s is still on its way here", row.Title, a.homeTakeRow.Title), "") } else { a.homeMoveSaid = a.initialMoveLine() a.home.say(a.homeMoveSaid, "") diff --git a/internal/tui3/homeband_resume_test.go b/internal/tui3/homeband_resume_test.go index d176327652..9e5f9da66a 100644 --- a/internal/tui3/homeband_resume_test.go +++ b/internal/tui3/homeband_resume_test.go @@ -68,7 +68,7 @@ func TestResumeIsDecidedAgainWhenTheFeedSaysTheDeviceWentOffline(t *testing.T) { // D6: The relay's offline debounce is over: the feed drops the device. feed.state.Online = nil a.tookWatch(dirWatchMsg{from: feed}) - if got := leftOffFrame(a); !strings.Contains(got, "Continue tower's latest chat here?") { + if got := leftOffFrame(a); !strings.Contains(got, "Move tower's latest chat here?") { t.Fatalf("no card after the device went offline:\n%s", got) } // It comes back: the reason is gone and the card with it. @@ -108,7 +108,7 @@ func TestResumeOffersOnceAndLeadsToTheTakeoverCard(t *testing.T) { a := leftOffApp(&fakeTaker{}) a.tookMachines(homeMachinesMsg{rows: []chatlist.Row{leftOffRow("a", "tower", chatlist.Off, time.Hour)}}) got := leftOffFrame(a) - for _, want := range []string{"Continue tower's latest chat here?", resumeYes, resumeNo} { + for _, want := range []string{"Move tower's latest chat here?", resumeYes, resumeNo} { if !strings.Contains(got, want) { t.Fatalf("card lacks %q:\n%s", want, got) } @@ -122,7 +122,7 @@ func TestResumeOffersOnceAndLeadsToTheTakeoverCard(t *testing.T) { t.Fatal("the takeover card was not raised") } if ask.pick != continueYesAt { - t.Fatalf("alt+c left the cursor on %d, not on `continue here`", ask.pick) + t.Fatalf("alt+c left the cursor on %d, not on `move here`", ask.pick) } if leftOffFrame(a) != "" { t.Fatal("the offer stayed after it was taken up") @@ -164,7 +164,7 @@ func TestResumeAppearsWithinTheBoundWhenTheLeaseLapses(t *testing.T) { } src.rows = row(chatlist.Off) lapsed := *now - for !strings.Contains(leftOffFrame(a), "Continue tower's latest chat here?") { + for !strings.Contains(leftOffFrame(a), "Move tower's latest chat here?") { if waited := now.Sub(lapsed); waited > machinesCap+homeEvery { t.Fatalf("no card %s after the lease lapsed, want within %s", waited, machinesCap) } diff --git a/internal/tui3/homeband_standing_test.go b/internal/tui3/homeband_standing_test.go index b947652ff4..8b828bf8eb 100644 --- a/internal/tui3/homeband_standing_test.go +++ b/internal/tui3/homeband_standing_test.go @@ -16,7 +16,7 @@ func TestDevicesRowAndRescueStandOnAnEmptyHome(t *testing.T) { a.tookMachines(homeMachinesMsg{rows: []chatlist.Row{leftOffRow("a", "desk", chatlist.Off, time.Hour)}}) a.openHome() got := strings.Join(strings.Fields(homeText(a)), " ") - for _, want := range []string{"● This Mac ● tower ○ desk (offline)", "Continue desk's latest chat here?"} { + for _, want := range []string{"● This Mac ● tower ○ desk (offline)", "Move desk's latest chat here?"} { if !strings.Contains(got, want) { t.Fatalf("empty home lacks %q:\n%s", want, homeText(a)) } diff --git a/internal/tui3/homeconfirm.go b/internal/tui3/homeconfirm.go index 1de6b7e368..4f63a1f565 100644 --- a/internal/tui3/homeconfirm.go +++ b/internal/tui3/homeconfirm.go @@ -60,6 +60,9 @@ import ( // raiseHomeAsk puts one question on home's card, replacing whatever was there. func (a *app) raiseHomeAsk(q questionShown) { + if a.home.ask != nil && a.home.ask.question.Kind == homePermitKind && q.question.Kind != homePermitKind { + a.home.permitAsked = false + } if q.question.Asked.IsZero() { q.question.Asked = a.now() } @@ -181,5 +184,15 @@ func (a *app) homeAskKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { if !ok { return nil, false } + if ask.question.Kind == homePermitKind { + switch msg.String() { + case "esc": + a.dropHomeAsk() + a.home.armed = "" + return nil, true + case "1", "2", "3": + return a.questionAnswerKey(ask, msg.String()), true + } + } return a.questionKeyOn(ask, msg) } diff --git a/internal/tui3/homedraft.go b/internal/tui3/homedraft.go index 67978e51ee..eee6672d7a 100644 --- a/internal/tui3/homedraft.go +++ b/internal/tui3/homedraft.go @@ -321,7 +321,7 @@ func (a *app) targetDestinations() []string { world.Projects = a.home.everyProject() launch := a.home.launch if launch == "" { - launch = a.workspace + launch = a.ownWorkspace() } in := homeGridInput{world: world, launch: launch, bucket: a.home.bucket} out := make([]string, 0, len(world.Projects)+1) diff --git a/internal/tui3/homeexchange.go b/internal/tui3/homeexchange.go index 5d8cdbff17..f672c1a0cf 100644 --- a/internal/tui3/homeexchange.go +++ b/internal/tui3/homeexchange.go @@ -1392,7 +1392,7 @@ func (a *app) errandPlace() (workspace, bucket string) { if path := a.errandWorkspaceOf(here); path != "" { return path, here } - if path := strings.TrimSpace(a.workspace); path != "" { + if path := a.ownWorkspace(); path != "" { return path, here } } diff --git a/internal/tui3/homelive_test.go b/internal/tui3/homelive_test.go index fbfce78f6a..d02bdc9bc4 100644 --- a/internal/tui3/homelive_test.go +++ b/internal/tui3/homelive_test.go @@ -99,14 +99,14 @@ func TestHomeLiveSource(t *testing.T) { // TestReleasedChatOnAnotherMachineOffersContinue: a chat the other machine let // go of is not open on this one, so enter on it raises the takeover screen and -// the yes is `continue here`. +// the yes is `move here`. func TestReleasedChatOnAnotherMachineOffersContinue(t *testing.T) { taker := &fakeTaker{} a := continueHome(t, taker, chatlist.Static{ {Cell: "c-idle", Title: "Notes on the migration", Device: "host-a", Status: chatlist.Idle, DurableAgo: 26 * 3600e9}, }, 200) standOn(t, a, "c-idle") - if text := homeText(a); !strings.Contains(text, chatlist.OfferContinue) { + if text := homeText(a); !strings.Contains(text, chatlist.OfferMove) { t.Fatalf("a released chat does not offer to continue:\n%s", text) } confirm(t, a) @@ -128,7 +128,7 @@ func TestNoticeSeamSaysASentenceAtOnce(t *testing.T) { t.Fatal("joining a desk that holds a sentence did not ring the door") } a.route(noticesMsg{}) - if !saidNote(a, "host-a continued this chat") { + if !saidNote(a, "host-a moved this chat") { t.Fatal("the sentence said before the surface joined was lost") } diff --git a/internal/tui3/homemove.go b/internal/tui3/homemove.go index 1bcc412f96..fee7c16c88 100644 --- a/internal/tui3/homemove.go +++ b/internal/tui3/homemove.go @@ -8,6 +8,7 @@ import ( tea "charm.land/bubbletea/v2" + "github.com/Agent-Field/codeaf/internal/chatlist" "github.com/Agent-Field/codeaf/internal/session" "github.com/Agent-Field/codeaf/internal/syncsetup" ) @@ -56,7 +57,7 @@ func moveSaid(p MoveProgress) string { case p.Step == "opening": return "opening it here…" case p.Done <= 0: - return continuing + return movingHere case p.Total > 0: return fmt.Sprintf("copying to this computer: %s…", movedBytes(p.Done, p.Total)) } @@ -198,8 +199,12 @@ func (a *app) followMove(msg homeMoveTickMsg) tea.Cmd { return nil } if a.homeTaking != "" { - if p, ok := reporter.MoveProgress(a.homeTaking); ok && a.at(pageHome) && (a.home.msg == "" || a.home.msg == a.homeMoveLine() || a.home.msg == continuing || a.home.msg == "opening conversation…") { - a.homeMoveSaid = moveSaid(p) + if p, ok := reporter.MoveProgress(a.homeTaking); ok && a.at(pageHome) && (a.home.msg == "" || a.home.msg == a.homeMoveLine() || a.home.msg == movingHere || a.home.msg == chatlist.LiveMoving || a.home.msg == "opening conversation…") { + said := moveSaid(p) + if a.liveMoveFrom != "" && said == movingHere { + said = chatlist.LiveMoving + } + a.homeMoveSaid = said a.home.say(a.homeMoveSaid, "") a.touch() } @@ -219,12 +224,15 @@ func (a *app) followMove(msg homeMoveTickMsg) tea.Cmd { // initialMoveLine is the first line home shows when a continue begins. func (a *app) initialMoveLine() string { + if a.liveMoveFrom != "" { + return chatlist.LiveMoving + } if !syncsetup.MoveFilesFirst() { if _, ok := a.taker.(moveReporter); ok { return "opening conversation…" } } - return continuing + return movingHere } // homeMoveLine is the line home shows for the running continue. diff --git a/internal/tui3/homemove_test.go b/internal/tui3/homemove_test.go index 58d78deb43..042681b1fd 100644 --- a/internal/tui3/homemove_test.go +++ b/internal/tui3/homemove_test.go @@ -34,7 +34,7 @@ func TestMoveSaid(t *testing.T) { p MoveProgress want string }{ - {MoveProgress{Step: "preparing"}, continuing}, + {MoveProgress{Step: "preparing"}, movingHere}, {MoveProgress{Step: "copying", Done: 412 << 20, Total: 1433 << 20}, "copying to this computer: 412 of 1,433 MB…"}, {MoveProgress{Step: "copying", Done: 3 << 20}, "copying to this computer: 3 MB so far…"}, {MoveProgress{Step: "copying", Done: 900 << 10, Total: 1000 << 10}, "copying to this computer: 900 of 1,000 KB…"}, @@ -122,7 +122,7 @@ func TestContinueNamesTheComputerThatIsNotOn(t *testing.T) { row := continueRows[0] row.Device = "tower" got := a.continueFailure(homeTakenMsg{row: row, err: err}) - if !strings.Contains(got, "tower has this chat and is not on right now; open codeaf there, then continue here") { + if !strings.Contains(got, "tower has this chat and is not on right now; open codeaf there, then move here") { t.Fatalf("a continue whose computer is off says %q", got) } } @@ -135,7 +135,7 @@ func TestHolderOffSentenceWithoutADraftDoesNotMentionTheBox(t *testing.T) { row := continueRows[0] row.Device = "tower" err := fmt.Errorf("handoff: %w", &syncwords.HolderOfflineError{Name: "tower"}) - want := "tower has this chat and is not on right now; open codeaf there, then continue here" + want := "tower has this chat and is not on right now; open codeaf there, then move here" for name, msg := range map[string]homeTakenMsg{ "automatic continue, no draft": {row: row, err: err, automatic: true}, "a draft holding nothing": {row: row, err: err, draft: &composerState{}}, @@ -460,7 +460,7 @@ func TestR3ResumeBandAltCOpensEarly(t *testing.T) { drain(t, a, a.openHome()) drain(t, a, a.askMachines()) - if !strings.Contains(homeText(a), "Continue tower's latest chat here?") { + if !strings.Contains(homeText(a), "Move tower's latest chat here?") { t.Fatalf("expected resume band on Home:\n%s", homeText(a)) } diff --git a/internal/tui3/homepanel_askonce_test.go b/internal/tui3/homepanel_askonce_test.go new file mode 100644 index 0000000000..57cb3adb01 --- /dev/null +++ b/internal/tui3/homepanel_askonce_test.go @@ -0,0 +1,292 @@ +package tui3 + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/chatlist" +) + +type fakePermitAsker struct { + names []string + ask bool + askCalls int + answers []bool + err error +} + +func (f *fakePermitAsker) AskOnce() ([]string, bool) { + f.askCalls++ + if !f.ask { + return nil, false + } + return append([]string(nil), f.names...), true +} + +func (f *fakePermitAsker) Answer(allow bool) error { + f.answers = append(f.answers, allow) + if f.err != nil { + return f.err + } + f.ask = false + return nil +} + +// V25/T13 (Part 3): when Home opens in a local window and PermitAsk.AskOnce() +// says ask, Home raises one card naming the older paired computers; answering 1 +// calls Answer(true) and ends the question for good. +func TestHomeAsksOnceToLetAnOlderPairedDeviceControlChats(t *testing.T) { + asker := &fakePermitAsker{names: []string{"tower", "desk"}, ask: true} + a := newApp(context.Background(), Options{ + Agent: &fakeAgent{model: "m"}, + PermitAsk: asker, + Approvals: devicesFake(), + }) + a.width, a.height = 200, 70 + drain(t, a, a.openHome()) + + ask, ok := a.homeAsking() + if !ok { + t.Fatal("Home did not raise the one-time permit question on open") + } + if ask.question.Head != permitAskHead { + t.Fatalf("card head = %q, want %q", ask.question.Head, permitAskHead) + } + wantReason := "tower and desk can watch your chats here but cannot type yet." + if ask.question.Reason != wantReason { + t.Fatalf("card reason = %q, want %q", ask.question.Reason, wantReason) + } + if len(ask.question.Options) != 3 || + ask.question.Options[0].Label != permitAskOptionType || + ask.question.Options[1].Label != permitAskOptionKeep || + ask.question.Options[2].Label != permitAskOptionPick { + t.Fatalf("card options = %+v", ask.question.Options) + } + screen := homeText(a) + for _, want := range []string{permitAskHead, wantReason, permitAskOptionType, permitAskOptionKeep, permitAskOptionPick} { + if !strings.Contains(screen, want) { + t.Fatalf("Home screen lacked %q:\n%s", want, screen) + } + } + + // Refreshing Home during the same visit does not ask again. + callsBefore := asker.askCalls + a.refreshHome() + a.rebuildMachines() + if asker.askCalls != callsBefore { + t.Fatalf("refreshing Home during the same visit called AskOnce %d extra times", asker.askCalls-callsBefore) + } + + // Answering 1 calls Answer(true) and closes the card. + drive(t, a, key("1")) + if len(asker.answers) != 1 || !asker.answers[0] { + t.Fatalf("pressing 1 recorded answers %v, want [true]", asker.answers) + } + if _, ok := a.homeAsking(); ok { + t.Fatal("permit card remained open after answering 1") + } + + // Reopening Home after Answer succeeded does not raise the card again. + a.closeHome() + drain(t, a, a.openHome()) + if _, ok := a.homeAsking(); ok { + t.Fatal("Home raised the permit card again after Answer succeeded") + } +} + +// V25/T13 (Part 3): option 2 calls Answer(false), option 3 calls Answer(false) +// and opens `/devices`, `esc` leaves the card without answering so it returns +// on the next Home open, and an Answer error is shown on Home's foot without +// re-raising until Home reopens. +func TestHomeAsksOnceAnswersTwoAndThreeAndEscAndError(t *testing.T) { + t.Run("option 2 keeps them watching", func(t *testing.T) { + asker := &fakePermitAsker{names: []string{"tower"}, ask: true} + a, _ := liveHomeRig(t, "dev_tower") + a.permitAsk = asker + a.closeHome() + drain(t, a, a.openHome()) + + ask, ok := a.homeAsking() + if !ok || ask.question.Reason != "tower can watch your chats here but cannot type yet." { + t.Fatalf("unexpected ask: ok=%t question=%+v", ok, ask.question) + } + drive(t, a, key("2")) + if len(asker.answers) != 1 || asker.answers[0] { + t.Fatalf("pressing 2 recorded answers %v, want [false]", asker.answers) + } + if _, ok := a.homeAsking(); ok { + t.Fatal("card stayed open after pressing 2") + } + a.closeHome() + drain(t, a, a.openHome()) + if _, ok := a.homeAsking(); ok { + t.Fatal("card reappeared after option 2 succeeded") + } + }) + + t.Run("option 3 keeps them watching and opens devices", func(t *testing.T) { + asker := &fakePermitAsker{names: []string{"tower"}, ask: true} + a, _ := liveHomeRig(t, "dev_tower") + a.approvals = devicesFake() + a.permitAsk = asker + a.closeHome() + drain(t, a, a.openHome()) + + if _, ok := a.homeAsking(); !ok { + t.Fatal("card not raised on open") + } + drive(t, a, key("3")) + if len(asker.answers) != 1 || asker.answers[0] { + t.Fatalf("pressing 3 recorded answers %v, want [false]", asker.answers) + } + if !a.pair.open || a.openDevicesCard() == nil { + t.Fatalf("pressing 3 did not open the /devices card: pair.open=%t card=%T", a.pair.open, a.pair.card) + } + }) + + t.Run("esc leaves the card without answering and returns on next open", func(t *testing.T) { + asker := &fakePermitAsker{names: []string{"tower"}, ask: true} + a, _ := liveHomeRig(t, "dev_tower") + a.permitAsk = asker + a.closeHome() + drain(t, a, a.openHome()) + + if _, ok := a.homeAsking(); !ok { + t.Fatal("card not raised on open") + } + drive(t, a, key("esc")) + if len(asker.answers) != 0 { + t.Fatalf("esc called Answer: %v", asker.answers) + } + if _, ok := a.homeAsking(); ok { + t.Fatal("esc did not dismiss the permit card") + } + if !a.at(pageHome) { + t.Fatal("esc on the permit card closed Home instead of only the card") + } + // Refreshing on the same visit does not re-raise it. + a.refreshHome() + a.rebuildMachines() + if _, ok := a.homeAsking(); ok { + t.Fatal("card re-raised during the same Home visit after esc") + } + // Reopening Home raises it again. + a.closeHome() + drain(t, a, a.openHome()) + if _, ok := a.homeAsking(); !ok { + t.Fatal("card did not return on the next Home open after esc") + } + }) + + t.Run("Answer error is said on Home foot and not re-raised until reopen", func(t *testing.T) { + wantErr := "could not write permits.json" + asker := &fakePermitAsker{names: []string{"tower"}, ask: true, err: errors.New(wantErr)} + a, _ := liveHomeRig(t, "dev_tower") + a.permitAsk = asker + a.closeHome() + drain(t, a, a.openHome()) + + drive(t, a, key("1")) + if a.home.msg != wantErr { + t.Fatalf("Home foot message = %q, want %q", a.home.msg, wantErr) + } + if _, ok := a.homeAsking(); ok { + t.Fatal("card remained open after Answer error") + } + a.refreshHome() + a.rebuildMachines() + if _, ok := a.homeAsking(); ok { + t.Fatal("card was raised again during the same Home visit after Answer error") + } + a.closeHome() + drain(t, a, a.openHome()) + if _, ok := a.homeAsking(); !ok { + t.Fatal("card was not raised when Home reopened after an Answer error") + } + }) +} + +// V14/V25/T13 (Part 3): the permit card is never raised when PermitAsk is nil, +// never on a hosted window, and never over another open card. +func TestHomeAsksOnceNotOverAnotherCardNotWhenNilAndNotOnAHostedWindow(t *testing.T) { + t.Run("nil PermitAsk", func(t *testing.T) { + a, _ := liveHomeRig(t, "dev_tower") + if _, ok := a.homeAsking(); ok { + t.Fatal("Home raised a card with PermitAsk == nil") + } + }) + + t.Run("hosted window", func(t *testing.T) { + asker := &fakePermitAsker{names: []string{"tower"}, ask: true} + a := newApp(context.Background(), Options{ + Agent: &fakeAgent{model: "m"}, + Host: "remote-box", + PermitAsk: asker, + }) + a.width, a.height = 200, 70 + drain(t, a, a.openHome()) + a.refreshHome() + if asker.askCalls != 0 { + t.Fatalf("hosted window called AskOnce %d times", asker.askCalls) + } + if _, ok := a.homeAsking(); ok { + t.Fatal("hosted window raised the permit card") + } + }) + + t.Run("never over another open card", func(t *testing.T) { + a, _ := liveHomeRig(t, "dev_tower") + standOn(t, a, "c1") + ask, ok := a.homeAsking() + if !ok || ask.question.Head != moveAsk { + t.Fatalf("expected Move card to be open, got ok=%t question=%+v", ok, ask.question) + } + + asker := &fakePermitAsker{names: []string{"tower"}, ask: true} + a.permitAsk = asker + a.refreshHome() + a.rebuildMachines() + + ask, ok = a.homeAsking() + if !ok || ask.question.Head != moveAsk { + t.Fatalf("refreshing Home overwrote the open Move card: ok=%t question=%+v", ok, ask.question) + } + if asker.askCalls != 0 { + t.Fatalf("AskOnce was called while another card was open: %d", asker.askCalls) + } + }) +} + +// V27 (Part 4): a Home row for an offline computer shows `offline · last seen 14:02` +// when the roster knows its LastSeen timestamp and plain `offline` when not. +func TestAnOfflineRowOnHomeSaysWhenItWasLastSeenOnlyWhenKnown(t *testing.T) { + a, _ := liveHomeRig(t) + now := time.Date(2026, time.November, 23, 16, 30, 0, 0, time.Local) + seen := time.Date(2026, time.November, 23, 14, 2, 0, 0, time.Local) + a.clock = func() time.Time { return now } + a.home.world.Read = now + + a.devRow.devices = []chatlist.Device{ + {ID: "dev_me", Name: "This Mac", Self: true}, + {ID: "dev_desk", Name: "desk", LastSeen: seen}, + {ID: "dev_plain", Name: "plain"}, + } + a.fileMachines(homeMachinesMsg{ + rows: []chatlist.Row{ + {Cell: "c-desk", Title: "Desk work", Device: "desk", DeviceID: "dev_desk", Status: chatlist.Off}, + {Cell: "c-plain", Title: "Plain work", Device: "plain", DeviceID: "dev_plain", Status: chatlist.Off}, + }, + }) + a.rebuildMachines() + + screen := homeText(a) + if !strings.Contains(screen, "desk offline · last seen 14:02") { + t.Fatalf("Home screen lacked 'desk offline · last seen 14:02':\n%s", screen) + } + if !strings.Contains(screen, "plain offline") || strings.Contains(screen, "plain offline · last seen") { + t.Fatalf("Home screen did not draw plain 'plain offline' for unknown LastSeen:\n%s", screen) + } +} diff --git a/internal/tui3/homepanel_continue.go b/internal/tui3/homepanel_continue.go index 753323ad87..7c2d9653e0 100644 --- a/internal/tui3/homepanel_continue.go +++ b/internal/tui3/homepanel_continue.go @@ -31,11 +31,11 @@ import ( // card home already has for a question about a row (homeconfirm.go), with the // cursor on the answer that loses nothing, except where the person just chose to // continue (enter on the row, the left-off chord, the device chord): there it -// starts on `continue here`. The takeover sentence is the card's +// starts on `move here`. The takeover sentence is the card's // reason, quoted whole from [chatlist.TakeoverLine]. // // A VERB THAT CANNOT WORK IS ABSENT. With no [Taker] injected a chat that went -// off has no `continue here`, and a branch offers only the recovery verbs +// off has no `move here`, and a branch offers only the recovery verbs // injected here: its card never promises a verb nothing is behind. // Taken is what a takeover reports to the surface. Kept names the branch that @@ -98,26 +98,26 @@ type BranchActions struct { // The words of the two cards. The sentences that are contract copy come from // [chatlist]; these are the questions around them. const ( - continueAsk = "Continue this chat here?" - continueStay = "leave it there" - continueRetry = "retry" - continueAlreadyRunning = "a chat is already continuing here; wait for it to open" - lostRaceWord = chatlist.LostRace - continuing = "continuing here…" - continueFails = "could not continue this chat here" - continueStoreBusy = continueFails + " because the engine store is busy" - // continueUnreachable names what did not happen, not only why, because + moveAsk = "Move this chat here?" + moveStay = "leave it there" + moveRetry = "retry" + moveAlreadyRunning = "a chat is already moving here; wait for it to open" + lostRaceWord = chatlist.LostRace + movingHere = "moving here…" + moveFails = "could not move this chat here" + moveStoreBusy = moveFails + " because the engine store is busy" + // moveUnreachable names what did not happen, not only why, because // the box still holds words the person meant to send in the moved chat. - continueUnreachable = continueFails + " because " + chatlist.Unreachable + "; your words are still in the box" - branchAsk = "What should happen to these turns?" - branchLeave = "leave them" - branchFails = "could not change those turns" + moveUnreachable = moveFails + " because " + chatlist.Unreachable + "; your words are still in the box" + branchAsk = "What should happen to these turns?" + branchLeave = "leave them" + branchFails = "could not change those turns" - // continueCheckFails is the failure of the look at this computer's copy that + // moveCheckFails is the failure of the look at this computer's copy that // comes BEFORE a move. It says what was being done, because nothing had been // put in any folder yet, and a sentence about a folder sends the person to // look for a problem that is not there. - continueCheckFails = "could not check this computer's copy before continuing; your words are still in the box" + moveCheckFails = "could not check this computer's copy before moving; your words are still in the box" ) // homeContinueKind and homeBranchKind are the lanes the two questions travel @@ -132,7 +132,7 @@ const ( // sentences are contract copy and too long for a one-line foot, so a frame with // no column to draw the card in shows them on a screen of their own // ([app.machineScreen]). -var machineAsks = map[session.QuestionKind]bool{homeContinueKind: true, homeBranchKind: true} +var machineAsks = map[session.QuestionKind]bool{homeContinueKind: true, homeBranchKind: true, homePermitKind: true} // armedBy reports that a question was raised from this row. A chat on another // machine is armed by its key, which no transcript path can spell. @@ -179,8 +179,38 @@ var remoteOffers = map[chatlist.OfferKind]func(*app, chatlist.Row, chatlist.Offe chatlist.Merge: (*app).offerBranch, } -// homeMachineEnter is enter on a chat from another machine. +// homeMachineEnter is enter on a chat from another machine: it opens an +// eligible held chat as a live view first, and falls back to the Move card when +// live viewing is unavailable or fails. func (a *app) homeMachineEnter(line homeLine) tea.Cmd { + if a.hosted() || line.remote == nil { + return nil + } + if a.machineRead.computerRemoved { + a.home.say(chatlist.RemovedChat, "") + return nil + } + row := *line.remote + if a.liveEligible(row) { + return a.homeOpenLiveLater(line, row) + } + // A CHAT LISTED BEFORE THE ROSTER ANSWERS IS NOT A CHAT TO MOVE. The listing + // and the roster are two reads begun together, and either can land first; a + // holder missing from a roster that has not answered yet is not a holder + // that is not there, and the Move card for a chat that opens live is the + // wrong card, one the person never asked for. So the Enter waits for a + // roster read begun after it and decides on that. + if a.rosterCanAdmit(row) { + if cmd, waiting := a.waitForRoster(line); waiting { + return cmd + } + } + return a.homeMachineMove(line) +} + +// homeMachineMove is the continuation door for a chat on another machine when +// moving the chat here was asked for directly or live viewing is not used. +func (a *app) homeMachineMove(line homeLine) tea.Cmd { if a.hosted() || line.remote == nil { return nil } @@ -208,7 +238,7 @@ func (a *app) homeMachineEnter(line homeLine) tea.Cmd { } if a.homeTaking != "" && !a.homeTakeAutomatic && (offer.Kind == chatlist.Open || offer.Kind == chatlist.ContinueHere) && a.taker != nil { a.raiseMachineAsk(row, a.continueBusyShown(row)) - a.home.say(continueAlreadyRunning, "") + a.home.say(moveAlreadyRunning, "") return nil } if a.idleOpenEnabled() && row.AutoOpen { @@ -225,7 +255,7 @@ func (a *app) sayOffer(_ chatlist.Row, offer chatlist.Offer) tea.Cmd { return nil } -// ── continue here ─────────────────────────────────────────────────────────── +// ── move here ─────────────────────────────────────────────────────────── // The two places the takeover card's cursor can start. const ( @@ -257,6 +287,7 @@ func (a *app) finishHomeTake(restoreDraft bool) { a.homeTaking, a.homeTakeDraft, a.homeTakenSaid, a.homeMoveSaid = "", nil, nil, "" a.homeTakeAutomatic, a.homeTakeOriginAutomatic, a.homeTakeAbandoned = false, false, false a.homeTakeResult = nil + a.liveMoveFrom = "" } // cancelHomeTake withdraws the choice. An automatic acquisition still settles @@ -312,7 +343,7 @@ func (a *app) spendHomeTakeFor(line homeLine) tea.Cmd { // offerContinue raises the takeover screen for a person who chose to continue // (enter on the row, the left-off chord, the device chord): the cursor starts -// on `continue here`, so enter completes the move they just asked for. +// on `move here`, so enter completes the move they just asked for. func (a *app) offerContinue(row chatlist.Row, _ chatlist.Offer) tea.Cmd { return a.raiseContinue(row, continueYesAt) } @@ -336,22 +367,22 @@ func (a *app) raiseContinue(row chatlist.Row, at int) tea.Cmd { return nil } if a.taker == nil { - return a.sayOffer(row, chatlist.Offer{Line: chatlist.StatusLine(row)}) + return a.sayOffer(row, chatlist.Offer{Line: chatlist.StatusLineAt(a.presentRow(row), a.now())}) } if a.homeTaking != "" && !a.homeTakeAutomatic { a.raiseMachineAsk(row, a.continueBusyShown(row)) - a.home.say(continueAlreadyRunning, "") + a.home.say(moveAlreadyRunning, "") return nil } a.raiseMachineAsk(row, a.continueShown(row, at)) return nil } -// continueShown is the takeover question: `continue here` as the yes, and the +// continueShown is the takeover question: `move here` as the yes, and the // takeover sentence as the reason. The cursor starts on option `at`. func (a *app) continueShown(row chatlist.Row, at int) questionShown { row = a.presentRow(row) - card := a.continueCardFor(row, at == continueStayAt) + card := a.continueCardFor(row, at == continueStayAt || a.liveMoveFrom != "") return questionShown{ continuation: card, question: session.Question{ @@ -360,12 +391,12 @@ func (a *app) continueShown(row chatlist.Row, at int) questionShown { Ask: session.AskConfirmation, Form: session.FormCard, Asker: session.Asker{Kind: session.AskerSurface}, - Head: continueAsk, + Head: moveAsk, Reason: continueReason(row), Subject: session.SubjectRef{Name: row.Title}, Options: []session.AnswerOption{ - {Key: "1", Label: chatlist.OfferContinue}, - {Key: "2", Label: continueStay, Safe: true}, + {Key: "1", Label: chatlist.OfferMove}, + {Key: "2", Label: moveStay, Safe: true}, }, Stakes: session.StakesReversible, Asked: a.now(), @@ -373,6 +404,7 @@ func (a *app) continueShown(row chatlist.Row, at int) questionShown { pick: at, local: func(answer session.Answer) tea.Cmd { if answer.FirstKey() != "1" { + a.liveMoveFrom = "" if card.returnFile != "" && a.file == card.returnFile { a.closeHome() } @@ -380,7 +412,7 @@ func (a *app) continueShown(row chatlist.Row, at int) questionShown { } if a.homeTaking != "" && !a.homeTakeAutomatic { a.raiseMachineAsk(row, a.continueBusyShown(row)) - a.home.say(continueAlreadyRunning, "") + a.home.say(moveAlreadyRunning, "") return nil } return a.takeRemote(row) @@ -410,12 +442,12 @@ func (a *app) continueBusyShown(row chatlist.Row) questionShown { Ask: session.AskConfirmation, Form: session.FormCard, Asker: session.Asker{Kind: session.AskerSurface}, - Head: continueAsk, - Reason: continueAlreadyRunning, + Head: moveAsk, + Reason: moveAlreadyRunning, Subject: session.SubjectRef{Name: row.Title}, Options: []session.AnswerOption{ - {Key: "1", Label: chatlist.OfferContinue}, - {Key: "2", Label: continueStay, Safe: true}, + {Key: "1", Label: chatlist.OfferMove}, + {Key: "2", Label: moveStay, Safe: true}, }, Stakes: session.StakesReversible, Asked: a.now(), @@ -430,7 +462,7 @@ func (a *app) continueBusyShown(row chatlist.Row) questionShown { } if a.homeTaking != "" && !a.homeTakeAutomatic { a.raiseMachineAsk(row, a.continueBusyShown(row)) - a.home.say(continueAlreadyRunning, "") + a.home.say(moveAlreadyRunning, "") return nil } return a.takeRemote(row) @@ -457,12 +489,12 @@ func (a *app) continueRetryShown(msg homeTakenMsg, failure string) questionShown Ask: session.AskConfirmation, Form: session.FormCard, Asker: session.Asker{Kind: session.AskerSurface}, - Head: continueAsk, + Head: moveAsk, Reason: failure, Subject: session.SubjectRef{Name: row.Title}, Options: []session.AnswerOption{ - {Key: "1", Label: continueRetry}, - {Key: "2", Label: continueStay, Safe: true}, + {Key: "1", Label: moveRetry}, + {Key: "2", Label: moveStay, Safe: true}, }, Stakes: session.StakesReversible, Asked: a.now(), @@ -477,7 +509,7 @@ func (a *app) continueRetryShown(msg homeTakenMsg, failure string) questionShown } if a.homeTaking != "" && !a.homeTakeAutomatic { a.raiseMachineAsk(row, a.continueBusyShown(row)) - a.home.say(continueAlreadyRunning, "") + a.home.say(moveAlreadyRunning, "") return nil } a.machineRead.down = false @@ -497,7 +529,10 @@ func (a *app) presentRow(row chatlist.Row) chatlist.Row { self := a.resumeState().self row.Mine = row.Mine || self != "" && row.DeviceID == self if a.resumeState().away(row) { - return row.Quiet() + row = row.Quiet() + } + if row.HolderSeen.IsZero() { + row.HolderSeen = a.holderSeenFor(row.DeviceID) } return row } @@ -550,16 +585,16 @@ func (a *app) takeRemoteState(msg homeTakenMsg) tea.Cmd { } a.abandonAutomaticTake() a.homeTakePending = &msg - a.home.say(fmt.Sprintf("continuing %s next; %s is still on its way here", msg.row.Title, a.homeTakeRow.Title), "") + a.home.say(fmt.Sprintf("moving %s next; %s is still on its way here", msg.row.Title, a.homeTakeRow.Title), "") return nil } if a.homeTaking != "" { a.restoreTakeDraft(msg) if a.at(pageHome) { a.raiseMachineAsk(msg.row, a.continueBusyShown(msg.row)) - a.home.say(continueAlreadyRunning, "") + a.home.say(moveAlreadyRunning, "") } else { - a.note(continueAlreadyRunning) + a.note(moveAlreadyRunning) } return nil } @@ -568,6 +603,13 @@ func (a *app) takeRemoteState(msg homeTakenMsg) tea.Cmd { a.homeTaking = msg.row.Cell a.homeTakeAutomatic, a.homeTakeOriginAutomatic, a.homeTakeAbandoned = msg.automatic, msg.automatic, false a.homeTakeRow = msg.row + if live := a.liveFront(); live != nil && a.liveMatchesRow(live, msg.row) { + if a.liveMoveFrom == "" { + a.liveMoveFrom = a.liveMoveIdentity(live, msg.row) + } + } else { + a.liveMoveFrom = "" + } a.homeMoveSaid = a.initialMoveLine() a.home.say(a.homeMoveSaid, "") baseCtx := a.ctx @@ -577,7 +619,7 @@ func (a *app) takeRemoteState(msg homeTakenMsg) tea.Cmd { ctx, cancel := context.WithCancel(baseCtx) a.homeTakeCancel = cancel taker := a.taker - if a.file != "" && filepath.Base(session.DirOf(a.file)) == msg.row.Cell { + if a.file != "" && (filepath.Base(session.DirOf(a.file)) == msg.row.Cell || a.liveMoveFrom != "") { msg.fromFile = a.file // The displaced session may retire during the move, so its unsent words travel with the answer. composer := a.mainComposer() @@ -714,6 +756,7 @@ func (a *app) tookTakeover(msg homeTakenMsg) tea.Cmd { a.homeTakeCancel() a.homeTakeCancel = nil } + fromLive := a.liveMoveFrom != "" if msg.err != nil { a.finishHomeTake(false) } @@ -733,6 +776,23 @@ func (a *app) tookTakeover(msg homeTakenMsg) tea.Cmd { return a.chooseTakeRoots(msg, missing.Roots) } } + if msg.err != nil && fromLive { + a.liveMoveFrom = "" + if errors.Is(msg.err, directory.ErrUnreachable) || (msg.row.AutoOpen && errors.Is(msg.err, context.DeadlineExceeded)) { + a.machineRead.down = true + } + failure := a.failedTake(msg) + a.restoreTakeDraft(msg) + a.dropHomeAsk() + a.home.armed = "" + a.home.say("", "") + if a.at(pageHome) { + a.closeHome() + } + a.note(failure) + a.touch() + return nil + } var failure string if msg.err != nil { failure = a.failedTake(msg) @@ -814,7 +874,7 @@ func (a *app) lostRace(msg homeTakenMsg) tea.Cmd { opened = a.openHome() } msg.send = nil - a.showTakeFailure(msg, continueFails) + a.showTakeFailure(msg, moveFails) src, seq := a.machines, a.homeTakeSeq file := "" if line, ok := a.homeLineOf(msg.row.Cell); ok { @@ -865,7 +925,7 @@ func (a *app) continueConflictRead(msg continueConflictMsg) tea.Cmd { } } failed := msg.take - failure := continueFails + failure := moveFails if msg.err == nil { for _, row := range msg.rows { if row.Cell != failed.row.Cell { @@ -880,7 +940,7 @@ func (a *app) continueConflictRead(msg continueConflictMsg) tea.Cmd { } sameHolder := row.DeviceID != "" && row.DeviceID == failed.row.DeviceID || row.DeviceID == "" && failed.row.DeviceID == "" && row.Device == failed.row.Device if sameHolder && row.Fence != failed.row.Fence && row.Device != "" { - failure = fmt.Sprintf(chatlist.PickedUpAgain+"; press enter to continue it here", nonemptyDevice(row.Device)) + failure = fmt.Sprintf(chatlist.PickedUpAgain+"; press enter to move it here", nonemptyDevice(row.Device)) } else if !sameHolder && !row.Mine { failure = lostRaceWord } @@ -903,6 +963,7 @@ func (a *app) rebuildMachines() { if a.home.gridOn() || a.home.phone { a.home.build() } + a.considerPermitAsk() a.touch() } @@ -970,6 +1031,10 @@ func (a *app) openTaken(msg homeTakenMsg) tea.Cmd { a.conversationRequest++ } a.homeTakeDraft = &msg + var liveAgent Agent + if a.liveFront() != nil { + liveAgent = a.agent + } a.homeTakenSaid = func() tea.Cmd { if !msg.automatic { a.foldHomeBoxIntoDraft(&msg) @@ -982,10 +1047,22 @@ func (a *app) openTaken(msg homeTakenMsg) tea.Cmd { if held.watch != nil { held.watch.stop() } + if held.conv.Live != nil && held.conv.Agent != nil { + if held.conv.Agent == liveAgent { + liveAgent = nil + } + leaveAgent(held.conv.Agent) + } delete(a.behind, key) - a.forget(key) + if key != a.convKey(a.file) { + a.forget(key) + } } } + if liveAgent != nil && liveAgent != a.agent && !msg.taken.AlreadyHere { + leaveAgent(liveAgent) + liveAgent = nil + } a.finishHomeTake(false) a.note(joinSaid(moved, kept)) if !msg.taken.AlreadyHere && !msg.fromComposer { @@ -1033,7 +1110,7 @@ func (a *app) openTaken(msg homeTakenMsg) tea.Cmd { return nil } var cmd tea.Cmd - if !msg.taken.AlreadyHere && msg.taken.Transcript != "" && a.holding(line.row.Transcript) { + if !msg.taken.AlreadyHere && (msg.taken.Transcript != "" || a.liveFront() != nil || a.liveMoveFrom != "") && a.holding(line.row.Transcript) { // The transcript was replaced by the handoff. Reattach through the // real door instead of bringing the superseded in-memory session back. cmd = a.homeOpenLater(line, false) @@ -1175,6 +1252,14 @@ func (a *app) takenLine(msg homeTakenMsg) (homeLine, bool) { return line, true } if t.Transcript == "" { + world, _ := a.readWorldKnown() + for _, project := range world.Projects { + for _, row := range project.Sessions { + if homeSessionID(row) == msg.row.Cell { + return homeLine{kind: homeSession, project: project.Name, dir: project.Dir, row: row}, true + } + } + } return homeLine{}, false } return homeLine{kind: homeSession, row: session.SessionRow{ID: msg.row.Cell, Transcript: t.Transcript, ProjectDir: t.Resume.Now}}, true @@ -1383,13 +1468,13 @@ func (a *app) runBranchVerb(v branchVerb, row chatlist.Row) tea.Cmd { if v.label == "open separately" { if a.homeTaking != "" { a.raiseMachineAsk(row, a.continueBusyShown(row)) - a.home.say(continueAlreadyRunning, "") + a.home.say(moveAlreadyRunning, "") return nil } a.homeTakeSeq++ seq := a.homeTakeSeq a.homeTaking = row.Cell - a.home.say(continuing, "") + a.home.say(movingHere, "") baseCtx := a.ctx if baseCtx == nil { baseCtx = context.Background() @@ -1421,6 +1506,7 @@ func (a *app) othersNow() machineReading { return machineReading{} } reading := a.machineRead + reading.rows = a.withHolderSeen(reading.rows) reading.away = a.resumeState().away return reading } diff --git a/internal/tui3/homepanel_continue_live_test.go b/internal/tui3/homepanel_continue_live_test.go new file mode 100644 index 0000000000..9baf98f0da --- /dev/null +++ b/internal/tui3/homepanel_continue_live_test.go @@ -0,0 +1,386 @@ +package tui3 + +import ( + "errors" + "fmt" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/directory" + "github.com/Agent-Field/codeaf/internal/dirwatch" + machine "github.com/Agent-Field/codeaf/internal/preflight" +) + +// V8 (contract 4, contract 5, contract 6): pressing alt+m in a live view opens +// Home and raises the Move card for the live view's row even when a managed +// team is active; answering 1 shows "Moving here…" on Home and on the live +// view's composer-position bar with highest precedence; on completion the live +// agent is closed, the live seam is gone, and the moved chat runs here with the +// Moved from banner. +func TestMoveFromALiveViewShowsMovingHereThenTheTranscriptThenRunsHere(t *testing.T) { + lab := newHomeLab(t) + workspace := lab.workspace("project") + initial := lab.session("project", "0000000000000001", "Mine", workspace, time.Now()) + a := lab.app(initial) + t.Cleanup(a.doorLine.close) + a.width, a.height = 200, 70 + a.dirFeed = &fakeFeed{state: dirwatch.State{Up: true, Online: []string{"dev_tower"}}} + a.devRow.devices = rosterOf + + cellID := "0000000000000042" + remoteRow := chatlist.Row{ + Cell: cellID, + Title: "Port the parser", + Device: "tower", + DeviceID: "dev_tower", + Status: chatlist.Running, + } + src := &continuationListing{row: remoteRow} + a.machines = src + + liveAgent := &fakeAgent{model: "m"} + hostSessionFile := filepath.Join(t.TempDir(), cellID, "session.jsonl") + a.takeUp(Conversation{ + Agent: liveAgent, + SessionFile: hostSessionFile, + Live: &LiveSeam{ + Host: "tower", + Device: "dev_tower", + Cell: cellID, + Row: remoteRow, + // Even if the seam reports another state, Moving here… takes highest precedence. + Read: func() LiveRead { return LiveRead{Kind: LiveWentOffline} }, + }, + Link: &LinkSeam{}, + }, true) + + // Wire a managed team overlay to prove alt+m in a live view is handled before trafficKeyPress. + a.wall.loaded = true + a.wall.activeID = "team-1" + a.wall.teams = []team{{ + ID: "team-1", + Name: "harbor", + Manager: "other-key", + Members: []teamMember{{Key: a.frontTabKey(), Handle: "worker"}}, + }} + + entered, release := make(chan struct{}), make(chan struct{}) + t.Cleanup(func() { + select { + case <-release: + default: + close(release) + } + }) + var localTranscript string + a.taker = &fakeTaker{ + taken: Taken{ + Device: "This Mac", + Elapsed: 1200 * time.Millisecond, + Resume: machine.Resume{From: "tower", Now: workspace}, + }, + on: func(cell string) { + localTranscript = lab.session("project", cell, "Port the parser", workspace, time.Now()) + src.change(func(row *chatlist.Row) { row.Mine, row.Status = true, chatlist.Here }) + close(entered) + <-release + }, + } + + // Pressing alt+m in the live view opens Home and raises Move this chat here? with cursor on move here. + drive(t, a, key("alt+m")) + if !a.at(pageHome) { + t.Fatal("alt+m in a live view did not open Home") + } + ask, ok := a.homeAsking() + if !ok || ask.question.Head != moveAsk || ask.question.Subject.Name != "Port the parser" || ask.pick != continueYesAt { + t.Fatalf("alt+m did not raise Move card at continueYesAt: ok=%v pick=%d question=%+v", ok, ask.pick, ask.question) + } + if a.liveMoveFrom == "" { + t.Fatal("alt+m did not mark a.liveMoveFrom") + } + + // Answering 1 starts the Move and shows "Moving here…" on Home and on the live bar. + _, moveCmd := a.Update(key("enter")) + if a.home.msg != chatlist.LiveMoving { + t.Fatalf("Home progress line during live move = %q, want %q", a.home.msg, chatlist.LiveMoving) + } + if !strings.Contains(homeText(a), chatlist.LiveMoving) { + t.Fatalf("Home screen does not show %q:\n%s", chatlist.LiveMoving, homeText(a)) + } + bar, barOn := a.liveBar() + if !barOn || bar != chatlist.LiveMoving { + t.Fatalf("liveBar() during move = (%q, %v), want (%q, true)", bar, barOn, chatlist.LiveMoving) + } + + // Pressing esc on Home returns to the live chat view where the bar shows "Moving here…". + _, _ = a.Update(key("esc")) + if a.at(pageHome) { + t.Fatal("esc on Home during a live move did not return to the live view") + } + if screen := plain(frame(a)); !strings.Contains(screen, chatlist.LiveMoving) { + t.Fatalf("live chat frame while moving did not draw %q:\n%s", chatlist.LiveMoving, screen) + } + + // Let the Move finish and drain the completion commands. + close(release) + drain(t, a, moveCmd) + + if a.at(pageHome) { + t.Fatalf("completed move left the person on Home:\n%s", homeText(a)) + } + if liveAgent.closes != 1 { + t.Fatalf("retired live agent Close count = %d, want 1", liveAgent.closes) + } + if a.liveFront() != nil { + t.Fatalf("moved chat kept a live seam: %+v", a.liveFront()) + } + if a.liveMoveFrom != "" { + t.Fatalf("a.liveMoveFrom was not cleared after move success: %q", a.liveMoveFrom) + } + if a.file != localTranscript { + t.Fatalf("front conversation file = %q, want %q", a.file, localTranscript) + } + wantMoved := chatlist.Moved("tower", 1200*time.Millisecond, false) + if got := plain(lastNote(t, a)); got != wantMoved { + t.Fatalf("moved banner note = %q, want %q", got, wantMoved) + } +} + +// V9 (contract 7): when a Move started from a live view fails (including a lost +// race), Home closes, the live view is in front again with its agent open, its +// composer words untouched, its bar back to what it was, and the failure +// sentence said once as a note. +func TestAFailedMoveLeavesTheChatThereAndReturnsToTheLiveView(t *testing.T) { + cases := []struct { + name string + takeErr error + wantNote string + }{ + { + name: "holder error", + takeErr: errors.New("disk full"), + wantNote: moveFails + " because the chat could not be put in this folder; your words are still in the box. Try move here again.", + }, + { + name: "lost race", + takeErr: fmt.Errorf("take: %w", directory.ErrLeaseHeld), + wantNote: chatlist.LostRace, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + a, taker := liveHomeRig(t, "dev_tower") + a.closeHome() + taker.err = tc.takeErr + + cellID := "c1" + remoteRow := a.machineRead.rows[0] + liveAgent := &fakeAgent{model: "m"} + hostSessionFile := filepath.Join(t.TempDir(), cellID, "session.jsonl") + a.takeUp(Conversation{ + Agent: liveAgent, + SessionFile: hostSessionFile, + Live: &LiveSeam{ + Host: "tower", + Device: "dev_tower", + Cell: cellID, + Row: remoteRow, + Read: func() LiveRead { return LiveRead{Kind: LiveOn} }, + }, + Link: &LinkSeam{}, + }, true) + a.input.setText("keep these live words") + + drive(t, a, key("alt+m")) + if !a.at(pageHome) { + t.Fatal("alt+m did not open Home") + } + confirm(t, a) + + if a.at(pageHome) { + t.Fatal("failed move from a live view left Home open") + } + if _, asking := a.homeAsking(); asking { + t.Fatal("failed move from a live view left a retry card on Home") + } + if a.liveFront() == nil || a.liveFront().Host != "tower" { + t.Fatalf("live front was lost after failed move: %+v", a.liveFront()) + } + if liveAgent.closes != 0 { + t.Fatalf("live agent was closed on a failed move: closes=%d", liveAgent.closes) + } + if a.liveMoveFrom != "" { + t.Fatalf("a.liveMoveFrom = %q, want empty", a.liveMoveFrom) + } + if bar, on := a.liveBar(); on || bar != "" { + t.Fatalf("liveBar() after failed move = (%q, %v), want (\"\", false)", bar, on) + } + if got := a.input.String(); got != "keep these live words" { + t.Fatalf("composer words = %q, want %q", got, "keep these live words") + } + + notes := 0 + for _, e := range a.entries { + if e.kind == entryNote && e.text == tc.wantNote { + notes++ + } + } + if notes != 1 { + t.Fatalf("note %q appeared %d times in entries %+v, want 1", tc.wantNote, notes, a.entries) + } + }) + } +} + +// V14 (contract 7 and contract 9): a Move not started from a live view still +// stays on Home with the retry card when it fails. +func TestAMoveNotStartedFromALiveViewFailsAsItDidBefore(t *testing.T) { + taker := &fakeTaker{err: errors.New("boom")} + a := continueHome(t, taker, continueRows, 200) + standOn(t, a, "c-off") + confirm(t, a) + + if !a.at(pageHome) { + t.Fatal("failed move from Home closed Home") + } + ask, ok := a.homeAsking() + if !ok || ask.question.Options[0].Label != moveRetry || ask.question.Options[1].Label != moveStay { + t.Fatalf("failed move from Home did not keep the retry card: ok=%v question=%+v", ok, ask.question) + } +} + +// V8 (contract 8): when recordMachines learns that another paired computer took +// this window's open local chat, the window opens a live view of the new holder +// in place of the stale local conversation, closes the old local agent, keeps +// the typed words in the composer box, and prints no Superseded note; when +// OpenLive fails or is nil, the Superseded note is printed as before. +func TestTheOldHoldersWindowBecomesALiveViewOfTheNewHolder(t *testing.T) { + cellID := "0000000000000042" + remoteRow := chatlist.Row{ + Cell: cellID, + Title: "Parser work", + Device: "tower", + DeviceID: "dev_tower", + Status: chatlist.Running, + } + + t.Run("follows to a live view of the new holder", func(t *testing.T) { + oldAgent := &fakeAgent{model: "m"} + a := newTestApp(oldAgent) + t.Cleanup(a.doorLine.close) + a.dismissWelcome() + a.devRow.devices = rosterOf + localFile := filepath.Join(t.TempDir(), cellID, "session.jsonl") + a.takeUp(Conversation{ + Agent: oldAgent, + SessionFile: localFile, + }, true) + a.input.setText("words already in the box") + + calls, liveAgents := wireFakeOpenLive(t, a, nil) + drain(t, a, a.recordMachines(homeMachinesMsg{rows: []chatlist.Row{remoteRow}})) + + if len(*calls) != 1 || (*calls)[0].Cell != cellID { + t.Fatalf("OpenLive calls = %+v, want 1 call for %s", *calls, cellID) + } + if oldAgent.closes != 1 { + t.Fatalf("old local agent closes = %d, want 1", oldAgent.closes) + } + if a.liveFront() == nil || a.liveFront().Host != "tower" || a.agent != (*liveAgents)[0] { + t.Fatalf("front conversation did not become the live view: live=%+v", a.liveFront()) + } + if got := a.input.String(); got != "words already in the box" { + t.Fatalf("composer words after following holder = %q, want %q", got, "words already in the box") + } + for _, e := range a.entries { + if e.kind == entryNote && strings.Contains(e.text, chatlist.Superseded("tower")) { + t.Fatalf("recordMachines printed a Superseded note after opening live: %q", e.text) + } + } + + // A second listing for the same holder does not call OpenLive again or loop. + drain(t, a, a.recordMachines(homeMachinesMsg{rows: []chatlist.Row{remoteRow}})) + if len(*calls) != 1 { + t.Fatalf("repeated recordMachines called OpenLive %d times, want 1", len(*calls)) + } + }) + + t.Run("falls back to Superseded when OpenLive fails", func(t *testing.T) { + oldAgent := &fakeAgent{model: "m"} + a := newTestApp(oldAgent) + t.Cleanup(a.doorLine.close) + a.dismissWelcome() + a.devRow.devices = rosterOf + localFile := filepath.Join(t.TempDir(), cellID, "session.jsonl") + a.takeUp(Conversation{ + Agent: oldAgent, + SessionFile: localFile, + }, true) + a.input.setText("words already in the box") + + calls, _ := wireFakeOpenLive(t, a, errors.New("live door refused")) + drain(t, a, a.recordMachines(homeMachinesMsg{rows: []chatlist.Row{remoteRow}})) + + if len(*calls) != 1 { + t.Fatalf("OpenLive calls = %d, want 1", len(*calls)) + } + if a.liveFront() != nil { + t.Fatalf("liveFront() = %+v after failed OpenLive, want nil", a.liveFront()) + } + if got := a.input.String(); got != "words already in the box" { + t.Fatalf("composer words = %q, want %q", got, "words already in the box") + } + found := false + for _, e := range a.entries { + if e.kind == entryNote && strings.Contains(e.text, chatlist.Superseded("tower")) { + found = true + } + } + if !found { + t.Fatalf("failed OpenLive did not fall back to the Superseded note: %+v", a.entries) + } + + // A second listing for the same transition does not retry OpenLive in a loop. + drain(t, a, a.recordMachines(homeMachinesMsg{rows: []chatlist.Row{remoteRow}})) + if len(*calls) != 1 { + t.Fatalf("repeated recordMachines after failure called OpenLive %d times, want 1", len(*calls)) + } + }) + + t.Run("absent path with OpenLive nil prints Superseded as before", func(t *testing.T) { + oldAgent := &fakeAgent{model: "m"} + a := newTestApp(oldAgent) + t.Cleanup(a.doorLine.close) + a.dismissWelcome() + a.devRow.devices = rosterOf + localFile := filepath.Join(t.TempDir(), cellID, "session.jsonl") + a.takeUp(Conversation{ + Agent: oldAgent, + SessionFile: localFile, + }, true) + a.input.setText("words already in the box") + + drain(t, a, a.recordMachines(homeMachinesMsg{rows: []chatlist.Row{remoteRow}})) + + if a.liveFront() != nil { + t.Fatalf("liveFront() = %+v with openLive == nil, want nil", a.liveFront()) + } + if got := a.input.String(); got != "words already in the box" { + t.Fatalf("composer words = %q, want %q", got, "words already in the box") + } + found := false + for _, e := range a.entries { + if e.kind == entryNote && strings.Contains(e.text, chatlist.Superseded("tower")) { + found = true + } + } + if !found { + t.Fatalf("openLive == nil did not print the Superseded note: %+v", a.entries) + } + }) +} diff --git a/internal/tui3/homepanel_continue_test.go b/internal/tui3/homepanel_continue_test.go index 83a63ac710..eca0661fd1 100644 --- a/internal/tui3/homepanel_continue_test.go +++ b/internal/tui3/homepanel_continue_test.go @@ -86,7 +86,7 @@ func TestTakeoverScreenCopy(t *testing.T) { text := homeText(a) for _, want := range []string{ "last saved turn 3h ago; up to 3 turns may still be on host-a", - chatlist.OfferContinue, + chatlist.OfferMove, } { if !strings.Contains(text, want) { t.Errorf("the takeover screen does not say %q:\n%s", want, text) @@ -137,7 +137,7 @@ func TestTakeoverScreenEscLeavesIt(t *testing.T) { } func TestTakeoverCardCursorByEntryPoint(t *testing.T) { - // An explicit continue starts on `continue here`; a card nobody asked for + // An explicit continue starts on `move here`; a card nobody asked for // starts on `leave it there`. entries := map[string]struct { raise func(*app, chatlist.Row) tea.Cmd @@ -209,11 +209,11 @@ func TestTakeoverScreenLostRace(t *testing.T) { standOn(t, a, "c-off") confirm(t, a) text := homeText(a) - if !strings.Contains(text, "another device continued this chat first") { + if !strings.Contains(text, "another device moved this chat first") { t.Fatalf("R25 visible refusal changed:\n%s", text) } q, card := a.homeAsking() - if !card || q.question.Options[0].Label != continueRetry || q.question.Options[1].Label != continueStay { + if !card || q.question.Options[0].Label != moveRetry || q.question.Options[1].Label != moveStay { t.Fatalf("the refusal did not stay on its retry card:\n%s", text) } found := false @@ -240,7 +240,7 @@ func TestTakeoverScreenRefusedWhenUnreachable(t *testing.T) { if len(taker.cells) != 0 || !strings.Contains(text, chatlist.Unreachable) { t.Fatalf("the offer was not disabled with its reason:\n%s", text) } - if strings.Contains(text, continueAsk) { + if strings.Contains(text, moveAsk) { t.Fatalf("a takeover was offered with the directory out of reach:\n%s", text) } } @@ -248,7 +248,7 @@ func TestTakeoverScreenRefusedWhenUnreachable(t *testing.T) { func TestTakeoverScreenAbsentWithoutATaker(t *testing.T) { a := continueHome(t, nil, continueRows, 200) standOn(t, a, "c-off") - if strings.Contains(homeText(a), continueAsk) { + if strings.Contains(homeText(a), moveAsk) { t.Fatalf("an offer with nothing behind it was drawn:\n%s", homeText(a)) } } @@ -363,7 +363,7 @@ func TestC7HomeExplainsAnOldSyncService(t *testing.T) { a := continueHome(t, &fakeTaker{err: directory.ErrConditionalTake}, continueRows, 220) standOn(t, a, "c-off") confirm(t, a) - if !strings.Contains(homeText(a), "waits for a sync service update") { + if !strings.Contains(homeText(a), "waits for a relay update") { t.Fatalf("old service refusal missing:\n%s", homeText(a)) } } @@ -407,24 +407,24 @@ func cardRows(a *app) []string { func TestTakeoverScreenGolden(t *testing.T) { golden := map[int][]string{ 80: { - "╭─ ? Continue this chat here? ────────────────────────────────────────────────╮", + "╭─ ? Move this chat here? ────────────────────────────────────────────────────╮", "│ host-a offline; last saved turn 3h ago; up to 3 turns may still be on host- │", "│ a │", "│ │", - "│ ▸ 1 continue here │", + "│ ▸ 1 move here │", "│ 2 leave it there safe answer │", "│ │", "╰─ esc leave it there ────────────────────────────────────────────────────────╯", }, 40: { - "╭─ ? Continue this chat here? ────────╮", + "╭─ ? Move this chat here? ────────────╮", "│ host-a offline; last saved turn 3h │", "│ ago; up to 3 turns may still be on │", // The sentence is whole: this golden once ended it at `still be on`, // which was the card cutting its own words after two rows. "│ host-a │", "│ │", - "│ ▸ 1 continue here │", + "│ ▸ 1 move here │", "│ 2 leave it there safe answer │", "│ │", "╰─ esc leave it there ────────────────╯", diff --git a/internal/tui3/homepanel_heldelsewhere.go b/internal/tui3/homepanel_heldelsewhere.go index 635429f3f7..8a008be506 100644 --- a/internal/tui3/homepanel_heldelsewhere.go +++ b/internal/tui3/homepanel_heldelsewhere.go @@ -26,14 +26,14 @@ import ( // A message typed into a chat whose lease another machine holds would not reach // the chat: it would make a branch nobody asked for. So enter shows the door // instead: home, with the chat's row from that machine under the cursor and the -// `Continue here` card up. The words stay in the box. +// `Move here` card up. The words stay in the box. // // Local authority lets an ordinary message send without a relay request. A copy // without that authority asks once off the loop before choosing its door. // heldElsewhere is the row of the chat on screen when another machine holds it. func (a *app) heldElsewhere() (chatlist.Row, bool) { - if a.file == "" || a.hosted() { + if a.file == "" || a.hosted() || a.liveFront() != nil { return chatlist.Row{}, false } cell := filepath.Base(session.DirOf(a.file)) @@ -121,6 +121,12 @@ func (a *app) needsOwnershipRead() bool { } func (a *app) checkBeforeSendWith(resume func() tea.Cmd) tea.Cmd { + if a.liveFront() != nil { + if resume != nil { + return resume() + } + return nil + } src, file, draft, agent := a.machines, a.file, a.input.String(), a.agent // A read that only ran out of time does not show the connection is down, // so the next Enter asks again rather than replaying the cached failure. @@ -465,6 +471,17 @@ func (a *app) blockDisplacedSend(text string) { if a.file == "" || !strings.HasSuffix(text, displacedSendSuffix) { return } + // A LIVE VIEW HAS NO SEND HOLD OF ITS OWN TO BLOCK. It shows the host's chat + // and sends through the host, so its words need no ownership check, and the + // displaced sentence it carries ([app.takeLinkNotice]) is the host's, said + // about the host's chat. It matters in the moment after this window moved the + // chat here: the host's sentence (the chat was moved, and by this very + // computer) can still arrive while the live view is the front, and keyed by + // the chat's id it blocked the hold the move had just made. The words typed + // next were then refused with a Move card for a chat that was already here. + if a.liveFront() != nil { + return + } if a.machineRead.sendHolds == nil { a.machineRead.sendHolds = map[string]sendHold{} } @@ -546,7 +563,7 @@ func (a *app) continueFailure(msg homeTakenMsg) string { // that request's error reads as an unreachable relay. return fmt.Sprintf("stopped: nothing came through for 2 minutes; the chat is still on %s", nonemptyDevice(msg.row.Device)) case errors.Is(msg.err, directory.ErrUnreachable), msg.row.AutoOpen && errors.Is(msg.err, context.DeadlineExceeded): - return continueUnreachable + return moveUnreachable case errors.Is(msg.err, directory.ErrConditionalTake): return directory.ErrConditionalTake.Error() case errors.Is(msg.err, directory.ErrRevoked): @@ -556,18 +573,18 @@ func (a *app) continueFailure(msg homeTakenMsg) string { var busy *cellstore.StoreBusyError if errors.As(msg.err, &busy) { if who := busy.Holder.Describe(); who != "" { - return continueFails + " because the engine store is busy (held by " + who + ")" + return moveFails + " because the engine store is busy (held by " + who + ")" } } - return continueStoreBusy + return moveStoreBusy case strings.Contains(msg.err.Error(), "rewind cancelled"), strings.Contains(msg.err.Error(), "changed during rewind"): - return continueFails + " because the folder changed during the move; your words are still in the box" + return moveFails + " because the folder changed during the move; your words are still in the box" case errors.As(msg.err, new(*continueCheckError)): log.Printf("continue chat %s: could not check this computer's copy: %v", msg.row.Cell, msg.err) - return continueCheckFails + return moveCheckFails default: log.Printf("continue chat %s: %v", msg.row.Cell, msg.err) - return continueFails + " because the chat could not be put in this folder; your words are still in the box. Try continue here again." + return moveFails + " because the chat could not be put in this folder; your words are still in the box. Try move here again." } } diff --git a/internal/tui3/homepanel_live_test.go b/internal/tui3/homepanel_live_test.go index ade0252230..65ed710b7a 100644 --- a/internal/tui3/homepanel_live_test.go +++ b/internal/tui3/homepanel_live_test.go @@ -1,13 +1,16 @@ package tui3 import ( + "context" "encoding/json" + "errors" "os" "path/filepath" "strings" "testing" "time" + "github.com/Agent-Field/codeaf/internal/chatlist" "github.com/Agent-Field/codeaf/internal/session" ) @@ -510,3 +513,290 @@ func homeAttentionRows(a *app) []*homeCell { } return out } + +func liveHomeRig(t *testing.T, online ...string) (*app, *fakeTaker) { + t.Helper() + a, _ := devicesRig(online...) + t.Cleanup(a.doorLine.close) + a.width, a.height = 200, 70 + taker := a.taker.(*fakeTaker) + drain(t, a, a.openHome()) + a.rebuildMachines() + return a, taker +} + +func wireFakeOpenLive(t *testing.T, a *app, fail error) (calls *[]chatlist.Row, agents *[]*fakeAgent) { + t.Helper() + var seen []chatlist.Row + var built []*fakeAgent + root := t.TempDir() + a.openLive = func(_ context.Context, row chatlist.Row) (Conversation, error) { + seen = append(seen, row) + if fail != nil { + return Conversation{}, fail + } + agent := &fakeAgent{model: "m"} + built = append(built, agent) + return Conversation{ + Agent: agent, + SessionFile: filepath.Join(root, row.Cell, "session.jsonl"), + Live: &LiveSeam{ + Host: row.Device, + Device: row.DeviceID, + Cell: row.Cell, + Row: row, + Read: func() LiveRead { return LiveRead{Kind: LiveOn} }, + }, + Link: &LinkSeam{}, + }, nil + } + return &seen, &built +} + +// V1 (contract 1): pressing Enter on a held row of an online paired computer +// opens a live view of that chat through OpenLive without calling the taker or +// changing the hold, and closes Home into the live conversation. +func TestEnterOnAHeldRowOfAnOnlineDeviceOpensItLiveAndLeavesTheHold(t *testing.T) { + a, taker := liveHomeRig(t, "dev_tower") + calls, _ := wireFakeOpenLive(t, a, nil) + + standOn(t, a, "c1") + + if len(*calls) != 1 || (*calls)[0].Cell != "c1" || (*calls)[0].DeviceID != "dev_tower" { + t.Fatalf("OpenLive calls = %+v, want one call for c1 on dev_tower", *calls) + } + if len(taker.cells) != 0 { + t.Fatalf("taker was called during a live open: %v", taker.cells) + } + if a.liveFront() == nil || a.liveFront().Host != "tower" || a.liveFront().Cell != "c1" { + t.Fatalf("front conversation live seam = %+v, want live view of tower c1", a.liveFront()) + } + if a.at(pageHome) { + t.Fatal("Home stayed open after a successful live open") + } + if a.homeTaking != "" { + t.Fatalf("homeTaking = %q, want empty", a.homeTaking) + } + if a.machineRead.rows[0].Status != chatlist.Running || a.machineRead.rows[0].DeviceID != "dev_tower" { + t.Fatalf("live open altered the held row: %+v", a.machineRead.rows[0]) + } + + // Phone sheet's open door on a machine row also takes the live road. + phoneApp, phoneTaker := liveHomeRig(t, "dev_tower") + phoneCalls, _ := wireFakeOpenLive(t, phoneApp, nil) + phoneApp.width, phoneApp.height = 44, 24 + phoneApp.rebuildMachines() + for i, line := range phoneApp.home.lines { + if line.remote != nil && line.remote.Cell == "c1" { + phoneApp.home.cursor = i + break + } + } + phoneApp.openHomeSheet() + drain(t, phoneApp, phoneApp.homeSheetOpen()) + if len(*phoneCalls) != 1 || len(phoneTaker.cells) != 0 || phoneApp.liveFront() == nil || phoneApp.at(pageHome) { + t.Fatalf("phone sheet open did not open live: calls=%d takes=%v live=%+v home=%v", len(*phoneCalls), phoneTaker.cells, phoneApp.liveFront(), phoneApp.at(pageHome)) + } +} + +// V1 (contract 2): when OpenLive returns an error, Home shows the error's text +// on its foot and raises the Move card for that row as fallback. +func TestEnterOnAHeldRowFallsBackToTheMoveCardWhenTheLiveOpenFails(t *testing.T) { + a, taker := liveHomeRig(t, "dev_tower") + wantErr := "tower is not running this chat right now." + calls, _ := wireFakeOpenLive(t, a, errors.New(wantErr)) + + standOn(t, a, "c1") + + if len(*calls) != 1 { + t.Fatalf("OpenLive called %d times, want 1", len(*calls)) + } + if len(taker.cells) != 0 { + t.Fatalf("fallback to the Move card already ran taker: %v", taker.cells) + } + if !a.at(pageHome) { + t.Fatal("Home closed when OpenLive failed") + } + if a.home.msg != wantErr { + t.Fatalf("Home foot message = %q, want %q", a.home.msg, wantErr) + } + ask, ok := a.homeAsking() + if !ok || ask.question.Kind != homeContinueKind || ask.question.Head != moveAsk || ask.question.Subject.Name != "Port" { + t.Fatalf("Move card was not raised on OpenLive failure: ok=%v question=%+v", ok, ask.question) + } +} + +// V27 (contract 2): a door that has nothing to open live and nothing to say, +// such as a computer that is off with no copy kept, answers ErrNoLiveView, and +// Enter asks the Move card with nothing on Home's foot, as it did before remote +// control. +func TestEnterOnAHeldRowWhoseDoorHasNothingToOpenAsksTheMoveCardInSilence(t *testing.T) { + a, taker := liveHomeRig(t, "dev_tower") + calls, _ := wireFakeOpenLive(t, a, ErrNoLiveView) + + standOn(t, a, "c1") + + if len(*calls) != 1 { + t.Fatalf("OpenLive called %d times, want 1", len(*calls)) + } + if len(taker.cells) != 0 { + t.Fatalf("the quiet fallback already ran the taker: %v", taker.cells) + } + if a.home.msg != "" && a.home.msg != conversationOpeningWord { + t.Fatalf("Home's foot says %q after a door with nothing to say", a.home.msg) + } + ask, ok := a.homeAsking() + if !ok || ask.question.Kind != homeContinueKind || ask.question.Head != moveAsk { + t.Fatalf("Move card was not raised: ok=%v question=%+v", ok, ask.question) + } +} + +// V14 (contract 2 and contract 9): when OpenLive is nil (remote control off), +// pressing Enter on a held row raises the Move card exactly as before. +func TestWithoutTheLiveSeamEnterOnAHeldRowAsksTheMoveCardAsBefore(t *testing.T) { + a, taker := liveHomeRig(t, "dev_tower") + if a.openLive != nil { + t.Fatal("expected default a.openLive to be nil") + } + + standOn(t, a, "c1") + + if len(taker.cells) != 0 { + t.Fatalf("Enter raised a take before confirmation: %v", taker.cells) + } + if !a.at(pageHome) || a.liveFront() != nil { + t.Fatalf("unexpected state: atHome=%v liveFront=%+v", a.at(pageHome), a.liveFront()) + } + ask, ok := a.homeAsking() + if !ok || ask.question.Kind != homeContinueKind || ask.question.Head != moveAsk || ask.question.Subject.Name != "Port" || ask.pick != continueYesAt { + t.Fatalf("Move card not raised as before: ok=%v pick=%d question=%+v", ok, ask.pick, ask.question) + } +} + +// V8 (contract 3): with OpenLive wired, the Move chords (alt+m bringWork and +// device picker, alt+c resume offer, and a local Home row that turns out held +// elsewhere) still raise the Move card and never call OpenLive. +func TestTheMoveChordsStillOfferTheMoveCardWhenLiveIsAvailable(t *testing.T) { + // 1. alt+m with one online device (bringWork). + a, _ := liveHomeRig(t, "dev_tower") + calls, _ := wireFakeOpenLive(t, a, nil) + if cmd := a.bringWork(); cmd != nil { + t.Fatalf("bringWork started work: %v", cmd) + } + if len(*calls) != 0 { + t.Fatalf("bringWork called OpenLive %d times, want 0", len(*calls)) + } + ask, ok := a.homeAsking() + if !ok || ask.question.Head != moveAsk || ask.question.Subject.Name != "Port" { + t.Fatalf("bringWork did not raise the Move card: ok=%v question=%+v", ok, ask.question) + } + + // 2. alt+m with several online devices (devicePickShown). + multi, _ := liveHomeRig(t, "dev_tower", "dev_desk") + multiCalls, _ := wireFakeOpenLive(t, multi, nil) + multi.bringWork() + pickAsk, ok := multi.homeAsking() + if !ok || pickAsk.question.Head != devicePickAsk { + t.Fatalf("several online devices did not raise picker: ok=%v question=%+v", ok, pickAsk.question) + } + pickAsk.local(session.Answer{Key: "1", Picked: []string{"1"}}) + if len(*multiCalls) != 0 { + t.Fatalf("device picker called OpenLive %d times, want 0", len(*multiCalls)) + } + if ask, ok = multi.homeAsking(); !ok || ask.question.Head != moveAsk || ask.question.Subject.Name != "Port" { + t.Fatalf("device picker did not raise the Move card: ok=%v question=%+v", ok, ask.question) + } + + // 3. alt+c from the resume card (offerContinue). + resumeApp, _ := liveHomeRig(t, "dev_tower") + resumeCalls, _ := wireFakeOpenLive(t, resumeApp, nil) + resumeApp.considerResume() + if resumeApp.leftOff.row == nil { + t.Fatal("expected resume offer for offline desk's chat") + } + cmd, took := resumeApp.resumeKeyHandler(resumeKey) + if !took || cmd != nil { + t.Fatalf("resumeKeyHandler(alt+c) took=%v cmd=%v", took, cmd) + } + if len(*resumeCalls) != 0 { + t.Fatalf("alt+c called OpenLive %d times, want 0", len(*resumeCalls)) + } + if ask, ok = resumeApp.homeAsking(); !ok || ask.question.Head != moveAsk || ask.question.Subject.Name != "Docs" { + t.Fatalf("alt+c did not raise the Move card: ok=%v question=%+v", ok, ask.question) + } + + // 4. A local Home row that turns out held elsewhere on open (homeLocalOpenReady). + localApp, _ := liveHomeRig(t, "dev_tower") + localCalls, _ := wireFakeOpenLive(t, localApp, nil) + heldRow := localApp.machineRead.rows[0] + localLine := homeLine{ + kind: homeSession, + row: session.SessionRow{ID: heldRow.Cell, Transcript: filepath.Join(t.TempDir(), heldRow.Cell, "session.jsonl")}, + } + drain(t, localApp, localApp.homeLocalOpenReady(homeLocalOpenMsg{ + line: localLine, + fromFile: localApp.file, + generation: localApp.continueGeneration, + reading: homeMachinesMsg{rows: []chatlist.Row{heldRow}}, + })) + if len(*localCalls) != 0 { + t.Fatalf("homeLocalOpenReady called OpenLive %d times, want 0", len(*localCalls)) + } + if ask, ok = localApp.homeAsking(); !ok || ask.question.Head != moveAsk || ask.question.Subject.Name != "Port" { + t.Fatalf("homeLocalOpenReady did not raise the Move card: ok=%v question=%+v", ok, ask.question) + } +} + +// V1/V10 (contract 1 and contract 2): Enter on a row whose computer is not in +// the roster, is this computer itself, or when this computer is marked removed +// does not call OpenLive and takes the existing non-live road. +func TestEnterIsNotLiveForAnOfflineOrRemovedOrUnknownComputer(t *testing.T) { + t.Run("unknown computer not in roster", func(t *testing.T) { + a, _ := liveHomeRig(t, "dev_tower") + calls, _ := wireFakeOpenLive(t, a, nil) + a.machineRead.rows = []chatlist.Row{ + {Cell: "c-unknown", Title: "Unknown box", Device: "stranger", DeviceID: "dev_stranger", Status: chatlist.Running}, + } + a.rebuildMachines() + + standOn(t, a, "c-unknown") + + if len(*calls) != 0 { + t.Fatalf("OpenLive called %d times for a computer not in the roster", len(*calls)) + } + ask, ok := a.homeAsking() + if !ok || ask.question.Head != moveAsk || ask.question.Subject.Name != "Unknown box" { + t.Fatalf("unknown computer did not raise the Move card: ok=%v question=%+v", ok, ask.question) + } + }) + + t.Run("this computer in roster", func(t *testing.T) { + a, _ := liveHomeRig(t, "dev_tower") + calls, _ := wireFakeOpenLive(t, a, nil) + selfRow := chatlist.Row{Cell: "c-self", Title: "Own chat", Device: "This Mac", DeviceID: "dev_me", Status: chatlist.Running} + drain(t, a, a.homeMachineEnter(homeLine{kind: homeMachineRow, remote: &selfRow})) + + if len(*calls) != 0 { + t.Fatalf("OpenLive called %d times for this computer itself", len(*calls)) + } + ask, ok := a.homeAsking() + if !ok || ask.question.Head != moveAsk || ask.question.Subject.Name != "Own chat" { + t.Fatalf("self row did not fall back to the Move card: ok=%v question=%+v", ok, ask.question) + } + }) + + t.Run("computer marked removed", func(t *testing.T) { + a, _ := liveHomeRig(t, "dev_tower") + calls, _ := wireFakeOpenLive(t, a, nil) + a.machineRead.computerRemoved = true + + standOn(t, a, "c1") + + if len(*calls) != 0 { + t.Fatalf("OpenLive called %d times when computerRemoved was true", len(*calls)) + } + if !strings.Contains(a.home.msg, chatlist.RemovedChat) { + t.Fatalf("removed computer foot = %q, want %q", a.home.msg, chatlist.RemovedChat) + } + }) +} diff --git a/internal/tui3/homepanel_machines.go b/internal/tui3/homepanel_machines.go index 50b891adab..21b41150f3 100644 --- a/internal/tui3/homepanel_machines.go +++ b/internal/tui3/homepanel_machines.go @@ -170,8 +170,12 @@ func (a *app) recordMachines(msg homeMachinesMsg) tea.Cmd { a.fileMachines(msg) a.machineRead.err = msg.err a.machineRead.readWithin = msg.readWithin + var liveCmd tea.Cmd if row, elsewhere := a.heldElsewhere(); msg.err == nil && elsewhere && (!wasElsewhere || before.DeviceID != row.DeviceID || before.Device != row.Device) { - a.note(chatlist.Superseded(nonemptyDevice(row.Device))) + var followed bool + if liveCmd, followed = a.followHolderLive(row); !followed { + a.note(chatlist.Superseded(nonemptyDevice(row.Device))) + } } a.machineRead.down = msg.err != nil && !a.machineRead.computerRemoved a.machineRead.merge = a.branches.Merge != nil @@ -182,7 +186,7 @@ func (a *app) recordMachines(msg homeMachinesMsg) tea.Cmd { if !a.machinesAsking { owed = a.readOwedByFrames(msg.err == nil) } - return tea.Batch(owed, a.finishBring(), a.continueAfterQuit(msg.err)) + return tea.Batch(owed, liveCmd, a.finishBring(), a.continueAfterQuit(msg.err)) } // into merges the other machines' chats into the panel's own lines, newest @@ -384,7 +388,7 @@ func machineLineWithDesc(row chatlist.Row, readAt, now time.Time, desc, merge bo now = readAt } at := readAt.Add(-row.DurableAgo) - note, short := chatlist.StatusLine(row), "" + note, short := chatlist.StatusLineAt(row, now), "" if row.Status == chatlist.Branch { // A branch's sentence names what can be done with it and has a narrow // spelling for frames that cannot hold the whole. diff --git a/internal/tui3/homepanel_takedoor_test.go b/internal/tui3/homepanel_takedoor_test.go index a462daca2f..06c07d65d0 100644 --- a/internal/tui3/homepanel_takedoor_test.go +++ b/internal/tui3/homepanel_takedoor_test.go @@ -80,8 +80,8 @@ func TestEnterOnTheDoorTakesTheListedChat(t *testing.T) { taker := &fakeTaker{} a, _ := heldLab(t, &flipping{status: chatlist.Running}, taker) standOn(t, a, heldCell) - if !strings.Contains(homeText(a), chatlist.OfferContinue) { - t.Fatalf("the card does not say %q:\n%s", chatlist.OfferContinue, homeText(a)) + if !strings.Contains(homeText(a), chatlist.OfferMove) { + t.Fatalf("the card does not say %q:\n%s", chatlist.OfferMove, homeText(a)) } confirm(t, a) if fmt.Sprint(taker.cells) != "["+heldCell+"]" { @@ -124,7 +124,7 @@ func TestTypingIntoAStaleWindowShowsTheDoorAndSendsNothing(t *testing.T) { if len(agent.sent) != 0 { t.Fatalf("a stale window sent %v", agent.sent) } - if !a.at(pageHome) || !strings.Contains(homeText(a), chatlist.OfferContinue) { + if !a.at(pageHome) || !strings.Contains(homeText(a), chatlist.OfferMove) { t.Fatalf("no door was shown:\n%s", homeText(a)) } if got := a.input.String(); got != "hello" { diff --git a/internal/tui3/homesheet.go b/internal/tui3/homesheet.go index 0944e92a0f..1cbced03f8 100644 --- a/internal/tui3/homesheet.go +++ b/internal/tui3/homesheet.go @@ -707,6 +707,8 @@ func (a *app) homeSheetOpen() tea.Cmd { // would raise the sheet a person is standing in. The session half of it // is one function below, and it is the one the door needs. return a.homeOpenRow(line.row, line.dir) + case homeMachineRow: + return a.homeMachineEnter(line) } return nil } diff --git a/internal/tui3/hostreplay.go b/internal/tui3/hostreplay.go index 1b900958b5..efa101a82b 100644 --- a/internal/tui3/hostreplay.go +++ b/internal/tui3/hostreplay.go @@ -37,6 +37,11 @@ func (a *app) refreshHostedReplay() tea.Cmd { } a.gen++ a.stream = nil + // THE SENTENCES THIS WINDOW SAID ABOUT ITSELF ARE NOT IN THE HOST'S + // RECORD, so the rebuild below would take them away: a refused move's + // `could not move this chat here` was read and then gone, because a + // road swapped under it. They are lifted out now and put back below. + kept := a.takeLocalNotes() // The new observer starts at the current turn's beginning. Its // earlier visible prefix is replaced, not retained as "in the gap". a.entries = nil @@ -50,6 +55,7 @@ func (a *app) refreshHostedReplay() tea.Cmd { a.hudStale = true a.dropHover() a.replayList(entries) + a.putLocalNotes(kept) var joined tea.Cmd if events != nil { joined = a.adoptTurn(events, stop) @@ -134,3 +140,121 @@ func (a *app) hostStreamCovered(ch <-chan session.Event) func() bool { } return nil } + +// ── THE SENTENCES A LIVE VIEW SAID ABOUT ITSELF ───────────────────────────── + +// heldNote is one local note lifted out of the entry list across a snapshot +// refresh, with where it stood: the entry it followed, and how many entries of +// the host's record came before it. +type heldNote struct { + note entry + after entryKey + hasPrev bool + before int +} + +// entryKey is what names a drawn entry well enough to find it again after the +// list was rebuilt from the record: the same kind, the same words, the same +// tool. The record and the live stream draw one conversation, so a finished +// entry has the same key whichever of them drew it. +type entryKey struct { + kind entryKind + text string + tool string +} + +func keyOfEntry(e entry) entryKey { return entryKey{kind: e.kind, text: e.text, tool: e.tool} } + +// takeLocalNotes lifts the notes this window wrote about itself out of the +// drawn entries, in order, before a live view's snapshot refresh rebuilds them +// from the host's record. It answers nothing for any window that is not a live +// view: a conversation held over ssh keeps the refresh it always had. +func (a *app) takeLocalNotes() []heldNote { + if a.liveFront() == nil { + return nil + } + var ( + held []heldNote + prev entryKey + hasPrev bool + before int + ) + for _, e := range a.entries { + if e.kind == entryNote && e.local { + held = append(held, heldNote{note: e, after: prev, hasPrev: hasPrev, before: before}) + continue + } + prev, hasPrev = keyOfEntry(e), true + before++ + } + return held +} + +// putLocalNotes puts the lifted notes back into the rebuilt entries, each right +// after the entry it followed and never before one it came after, so a sentence +// the person has read stays where they read it and the host's own news that +// arrived during the refresh lands below it. +// +// A NOTE THE RECORD ALREADY SAYS IS NOT PUT BACK, because the record is the +// authority: the same words twice would be the surface repeating itself. An +// entry that cannot be found again (the one it followed was part of a running +// turn, which the stream redraws from its first event) is placed by how many +// entries of the record came before it, and failing that at the end. +func (a *app) putLocalNotes(held []heldNote) { + if len(held) == 0 { + return + } + base := a.entries + said := make(map[string]bool, len(held)) + for _, e := range base { + if e.kind == entryNote { + said[e.text] = true + } + } + slots := make([]int, 0, len(held)) + kept := make([]heldNote, 0, len(held)) + floor := 0 + for _, h := range held { + if said[h.note.text] { + continue + } + at := min(h.before, len(base)) + if !h.hasPrev { + at = 0 + } else { + for i := len(base) - 1; i >= 0; i-- { + if base[i].kind != entryNote && keyOfEntry(base[i]) == h.after { + at = i + 1 + break + } + } + } + at = max(at, floor) + floor = at + slots = append(slots, at) + kept = append(kept, h) + } + if len(kept) == 0 { + return + } + merged := make([]entry, 0, len(base)+len(kept)) + next := 0 + for i := 0; i <= len(base); i++ { + for next < len(kept) && slots[next] == i { + note := kept[next].note + if i > 0 { + note.turn = base[i-1].turn + } + merged = append(merged, note) + next++ + } + if i < len(base) { + merged = append(merged, base[i]) + } + } + a.entries = merged + // EVERYTHING ON SCREEN NOW CAME FROM THE RECORD OR WAS LIFTED OUT OF IT, so + // nothing is "said since the replay" ([app.recordRows]): a notes row sitting + // among the record's would otherwise make the rows after it look like the gap. + a.recordRows = len(merged) +} diff --git a/internal/tui3/idle_open_test.go b/internal/tui3/idle_open_test.go index 603c99f84c..75d44f1cd2 100644 --- a/internal/tui3/idle_open_test.go +++ b/internal/tui3/idle_open_test.go @@ -34,8 +34,8 @@ func TestIdleOpen_C6_C7_C10_TerminalEnterUsesTheFreeDoorOnly(t *testing.T) { } command := a.homeMachineEnter(homeLine{remote: &row}) if automatic { - if strings.Contains(homeText(a), continueAsk) { - t.Fatal("C6 free open raised Continue here") + if strings.Contains(homeText(a), moveAsk) { + t.Fatal("C6 free open raised Move here") } if command == nil { t.Fatal("C6 free open did not start") @@ -46,7 +46,7 @@ func TestIdleOpen_C6_C7_C10_TerminalEnterUsesTheFreeDoorOnly(t *testing.T) { if taker.opens != 1 || len(taker.cells) != 0 || taker.seen == nil || taker.seen.Fence != 7 || taker.seen.Device != "A" { t.Fatalf("C6 wrong open door: %+v", taker) } - } else if taker.opens != 0 || len(taker.cells) != 0 || !strings.Contains(homeText(a), continueAsk) { + } else if taker.opens != 0 || len(taker.cells) != 0 || !strings.Contains(homeText(a), moveAsk) { t.Fatal("C7/C10 held chat no longer waits for the person's choice") } }) @@ -58,8 +58,8 @@ func TestIdleOpen_DefaultOff_ReleasedRowRequiresContinueHereAndLocalRowOpensLoca a, _ := heldLab(t, &flipping{status: chatlist.Idle}, taker) row := chatlist.Row{Cell: heldCell, Title: "saved chat", Device: "tower", DeviceID: "A", Fence: 7, Head: "saved", Status: chatlist.Idle, Released: true, AutoOpen: true} command := a.homeMachineEnter(homeLine{remote: &row}) - if command != nil || taker.opens != 0 || len(taker.cells) != 0 || !strings.Contains(homeText(a), continueAsk) { - t.Fatalf("default-off released remote row must require Continue here: opens=%d cells=%v home=%s", taker.opens, taker.cells, homeText(a)) + if command != nil || taker.opens != 0 || len(taker.cells) != 0 || !strings.Contains(homeText(a), moveAsk) { + t.Fatalf("default-off released remote row must require Move here: opens=%d cells=%v home=%s", taker.opens, taker.cells, homeText(a)) } source := &r5bHomeSource{read: func(context.Context) ([]chatlist.Row, uint64, error) { diff --git a/internal/tui3/idle_r10_retry_test.go b/internal/tui3/idle_r10_retry_test.go index 6f2dbb5df0..54726260f3 100644 --- a/internal/tui3/idle_r10_retry_test.go +++ b/internal/tui3/idle_r10_retry_test.go @@ -93,7 +93,7 @@ func r10RetryTakeBack(t *testing.T, first error, unknown int) { t.Fatal("uncertain take-back spent the draft") } if _, card := a.homeAsking(); card { - t.Fatal("uncertain take-back offered Continue here") + t.Fatal("uncertain take-back offered Move here") } var notes strings.Builder for _, entry := range a.entries { @@ -110,7 +110,7 @@ func r10RetryTakeBack(t *testing.T, first error, unknown int) { t.Fatal("live uncertain fence spent the draft") } if _, card := a.homeAsking(); card { - t.Fatal("live uncertain own fence offered Continue here") + t.Fatal("live uncertain own fence offered Move here") } // The relay listing now reports expiry; the next admission must // return a newly acquired fence rather than the uncertain fence. @@ -126,6 +126,6 @@ func r10RetryTakeBack(t *testing.T, first error, unknown int) { } } if _, card := a.homeAsking(); card { - t.Fatal("own held fence offered Continue here") + t.Fatal("own held fence offered Move here") } } diff --git a/internal/tui3/idle_r5_return_open_test.go b/internal/tui3/idle_r5_return_open_test.go index ecab8c5269..acce8d6e98 100644 --- a/internal/tui3/idle_r5_return_open_test.go +++ b/internal/tui3/idle_r5_return_open_test.go @@ -76,7 +76,7 @@ func TestIdleOpen_R5_RestartedHomeTakesFreeChatOnFirstOpen(t *testing.T) { drive(t, a, key("enter")) if expires != 0 { raw, err := os.ReadFile(file) - if err != nil || string(raw) != string(original) || taker.opens != 0 || len(taker.cells) != 0 || !strings.Contains(homeText(a), continueAsk) { + if err != nil || string(raw) != string(original) || taker.opens != 0 || len(taker.cells) != 0 || !strings.Contains(homeText(a), moveAsk) { t.Fatalf("lapsed working hold bypassed consent: free=%d takes=%v err=%v", taker.opens, taker.cells, err) } return @@ -92,7 +92,7 @@ func TestIdleOpen_R5_RestartedHomeTakesFreeChatOnFirstOpen(t *testing.T) { if !rows[0].Mine || rows[0].Status != chatlist.Here || rows[0].Fence != 4 { t.Fatalf("no new ownership fence: %+v", rows) } - if a.file != file || strings.Contains(homeText(a), continueAsk) { + if a.file != file || strings.Contains(homeText(a), moveAsk) { t.Fatalf("first open did not arrive directly: file=%q", a.file) } return @@ -151,7 +151,7 @@ func TestIdleOpen_R5_LocalRowKeepsLiveConsentAndUnpairedOpening(t *testing.T) { } switch mode { case "live": - if taker.opens != 0 || !a.at(pageHome) || !strings.Contains(homeText(a), continueAsk) { + if taker.opens != 0 || !a.at(pageHome) || !strings.Contains(homeText(a), moveAsk) { t.Fatal("live hold did not retain consent") } case "unpaired": diff --git a/internal/tui3/idle_r5b_local_open_test.go b/internal/tui3/idle_r5b_local_open_test.go index 8613cd1c3c..92dfa32fb4 100644 --- a/internal/tui3/idle_r5b_local_open_test.go +++ b/internal/tui3/idle_r5b_local_open_test.go @@ -73,7 +73,7 @@ func TestIdleOpen_R5b_LocalOpenWithUnreachableSyncOpensLocal(t *testing.T) { } source.read = func(ctx context.Context) ([]chatlist.Row, uint64, error) { if mode != "timeout" { - return nil, 0, errors.New("fixture sync service unreachable") + return nil, 0, errors.New("fixture relay unreachable") } deadline, ok := ctx.Deadline() if !ok || time.Until(deadline) > 2500*time.Millisecond { @@ -137,7 +137,7 @@ func TestIdleOpen_R5b_LocalOpenUsesDisplayWhenItAnswers(t *testing.T) { t.Fatalf("free row did not open directly: opens=%d file=%q", taker.opens, a.file) } case "held elsewhere": - if taker.opens != 0 || !a.at(pageHome) || !strings.Contains(homeText(a), continueAsk) { + if taker.opens != 0 || !a.at(pageHome) || !strings.Contains(homeText(a), moveAsk) { t.Fatal("live hold did not keep the existing choice") } default: diff --git a/internal/tui3/idle_r6_open_test.go b/internal/tui3/idle_r6_open_test.go index 9894c68658..a13cdd1ae0 100644 --- a/internal/tui3/idle_r6_open_test.go +++ b/internal/tui3/idle_r6_open_test.go @@ -18,7 +18,7 @@ func TestIdleOpen_R6_LapsedWhileWorkingKeepsTheCard(t *testing.T) { a, _ := heldLab(t, &flipping{status: chatlist.Off}, taker) command := a.homeMachineEnter(homeLine{remote: &row}) drain(t, a, command) - if row.AutoOpen || taker.opens != 0 || len(taker.cells) != 0 || !strings.Contains(homeText(a), continueAsk) { + if row.AutoOpen || taker.opens != 0 || len(taker.cells) != 0 || !strings.Contains(homeText(a), moveAsk) { t.Fatalf("lapsed working hold opened without consent: row=%+v free opens=%d takes=%v\n%s", row, taker.opens, taker.cells, homeText(a)) } } @@ -32,7 +32,7 @@ func TestIdleOpen_R6_ReleasedStillOpensDirectly(t *testing.T) { taker := &idleOpenTaker{} a, _ := heldLab(t, &flipping{status: chatlist.Idle}, taker) command := a.homeMachineEnter(homeLine{remote: &row}) - if !row.AutoOpen || command == nil || strings.Contains(homeText(a), continueAsk) { + if !row.AutoOpen || command == nil || strings.Contains(homeText(a), moveAsk) { t.Fatal("released hold did not enter direct opening") } _ = command() diff --git a/internal/tui3/idle_r8_send_test.go b/internal/tui3/idle_r8_send_test.go index 2d932f6836..2069d89813 100644 --- a/internal/tui3/idle_r8_send_test.go +++ b/internal/tui3/idle_r8_send_test.go @@ -90,7 +90,7 @@ func TestIdleOpen_R8_OwnLiveRowAfterBlipSendsNoCard(t *testing.T) { if agent.checks != 1 || len(agent.sent) != 1 || agent.sent[0] != "send after the blip" || rows[0].Fence != wantFence || a.at(pageHome) || a.agent != agent { t.Fatalf("own live send: checks=%d sent=%v rows=%+v home=%v notes=%v", agent.checks, agent.sent, rows, a.at(pageHome), noteTexts(a)) } - if strings.Contains(homeText(a), continueAsk) || strings.Contains(strings.Join(noteTexts(a), "\n"), "last held here") { + if strings.Contains(homeText(a), moveAsk) || strings.Contains(strings.Join(noteTexts(a), "\n"), "last held here") { t.Fatal("own live row raised a continuation card") } }) @@ -109,7 +109,7 @@ func TestIdleOpen_R8_OtherHolderStillGetsCard(t *testing.T) { }) a.input.setText("keep this draft") drive(t, a, key("enter")) - if agent.checks != 0 || len(agent.sent) != 0 || !a.at(pageHome) || !strings.Contains(homeText(a), continueAsk) || a.input.String() != "keep this draft" { + if agent.checks != 0 || len(agent.sent) != 0 || !a.at(pageHome) || !strings.Contains(homeText(a), moveAsk) || a.input.String() != "keep this draft" { t.Fatalf("changed holder skipped its card: checks=%d sent=%v home=%s draft=%q", agent.checks, agent.sent, homeText(a), a.input.String()) } }) diff --git a/internal/tui3/idle_r9_send_test.go b/internal/tui3/idle_r9_send_test.go index 43c9ea6318..8a891d4bc0 100644 --- a/internal/tui3/idle_r9_send_test.go +++ b/internal/tui3/idle_r9_send_test.go @@ -108,7 +108,7 @@ func TestIdleOpen_R9_EnterMatrix(t *testing.T) { t.Fatalf("reopen lost exact observed expectation: %+v", taker.seen) } arrived, ok := a.agent.(*switchAgent) - if len(old.sent) != 0 || !ok || len(arrived.sent) != 1 || arrived.sent[0] != words || !a.input.empty() || a.at(pageHome) || strings.Contains(homeText(a), continueAsk) { + if len(old.sent) != 0 || !ok || len(arrived.sent) != 1 || arrived.sent[0] != words || !a.input.empty() || a.at(pageHome) || strings.Contains(homeText(a), moveAsk) { t.Fatalf("first Enter did not reopen and send without a card: old=%v new=%T box=%q notes=%v", old.sent, a.agent, a.input.String(), noteTexts(a)) } if source.reads != 1 { @@ -160,7 +160,7 @@ func TestIdleOpen_R9_RelayOutcomes(t *testing.T) { t.Fatalf("refusal spent words: sent=%v box=%q error=%v", agent.sent, a.input.String(), err) } if service == "answering" { - if !a.at(pageHome) || !strings.Contains(homeText(a), continueAsk) || taker.seen != nil { + if !a.at(pageHome) || !strings.Contains(homeText(a), moveAsk) || taker.seen != nil { t.Fatalf("other holder needs consent: %s", homeText(a)) } drive(t, a, key("esc")) @@ -176,7 +176,7 @@ func TestIdleOpen_R9_RelayOutcomes(t *testing.T) { source.err = nil if other { drive(t, a, key("enter")) - if !strings.Contains(homeText(a), continueAsk) || len(agent.sent) != 0 { + if !strings.Contains(homeText(a), moveAsk) || len(agent.sent) != 0 { t.Fatal("recovery bypassed consent") } return @@ -210,7 +210,7 @@ func TestIdleOpen_R9_FreeHigherOwnFenceNeedsConsent(t *testing.T) { }) a.input.setText("keep this choice mine") drive(t, a, key("enter")) - if agent.checks != 0 || taker.seen != nil || len(agent.sent) != 0 || a.input.String() != "keep this choice mine" || !strings.Contains(homeText(a), continueAsk) { + if agent.checks != 0 || taker.seen != nil || len(agent.sent) != 0 || a.input.String() != "keep this choice mine" || !strings.Contains(homeText(a), moveAsk) { t.Fatalf("higher fence skipped consent: checks=%d take=%+v sent=%v box=%q", agent.checks, taker.seen, agent.sent, a.input.String()) } }) @@ -303,7 +303,7 @@ func TestIdleOpen_R9_RetiredReceiptProbeKeepsWordsOnFailure(t *testing.T) { if err != nil || string(before) != string(after) || len(old.sent) != 0 || taker.seen != nil || a.input.String() != words || source.reads != 1 || source.within <= 0 || source.within > idleSendProbeTimeout { t.Fatalf("failed receipt probe spent the gesture: sent=%v take=%+v box=%q probes=%d budget=%v error=%v", old.sent, taker.seen, a.input.String(), source.reads, source.within, err) } - if notes := strings.Join(noteTexts(a), "\n"); strings.Count(notes, chatlist.TakeBackUnreachable) != 1 || strings.Contains(homeText(a), continueAsk) { + if notes := strings.Join(noteTexts(a), "\n"); strings.Count(notes, chatlist.TakeBackUnreachable) != 1 || strings.Contains(homeText(a), moveAsk) { t.Fatalf("failed receipt probe needs one honest line and no card: %s", notes) } source.err = nil @@ -350,7 +350,7 @@ func TestIdleOpen_P9X1_BashCommandRunsOwnershipCheckAndKeepsWords(t *testing.T) } }) - t.Run("held elsewhere raises Continue here and keeps bash line in box", func(t *testing.T) { + t.Run("held elsewhere raises Move here and keeps bash line in box", func(t *testing.T) { a, old, source := r8OwnLiveWindow(t, false) bash := &p9xBashAgent{r9SendAgent: &r9SendAgent{r8SendAgent: old}} a.agent = bash @@ -361,8 +361,8 @@ func TestIdleOpen_P9X1_BashCommandRunsOwnershipCheckAndKeepsWords(t *testing.T) const cmdLine = "!sleep 400" a.input.setText(cmdLine) drive(t, a, key("enter")) - if len(bash.bashSent) != 0 || !a.at(pageHome) || !strings.Contains(homeText(a), continueAsk) || a.input.String() != cmdLine { - t.Fatalf("displaced bash did not offer Continue here: bashSent=%v home=%v box=%q", bash.bashSent, a.at(pageHome), a.input.String()) + if len(bash.bashSent) != 0 || !a.at(pageHome) || !strings.Contains(homeText(a), moveAsk) || a.input.String() != cmdLine { + t.Fatalf("displaced bash did not offer Move here: bashSent=%v home=%v box=%q", bash.bashSent, a.at(pageHome), a.input.String()) } }) diff --git a/internal/tui3/idle_walk_test.go b/internal/tui3/idle_walk_test.go index 3bb10918b2..5ade7c3dff 100644 --- a/internal/tui3/idle_walk_test.go +++ b/internal/tui3/idle_walk_test.go @@ -194,7 +194,7 @@ func TestIdleOpen_C7_D2_LocalViewerKeepsLiveHoldChoice(t *testing.T) { source.change(func(r *chatlist.Row) { r.Status, r.Released, r.AutoOpen = chatlist.Running, false, false }) drain(t, a, a.askMachines()) drain(t, a, a.homeOpenLine(selected)) - if taker.opens != 0 || len(taker.cells) != 0 || strings.Contains(homeText(a), continueAsk) { + if taker.opens != 0 || len(taker.cells) != 0 || strings.Contains(homeText(a), moveAsk) { t.Fatal("a live local viewer changed the base open shortcut") } } diff --git a/internal/tui3/input.go b/internal/tui3/input.go index b31b55483e..1130d33d2e 100644 --- a/internal/tui3/input.go +++ b/internal/tui3/input.go @@ -340,8 +340,9 @@ func (e *editor) down() { // two typed overlays are read before the editor, because while a list is up the // four keys that move and commit it are the list's. func (a *app) key(msg tea.KeyPressMsg) tea.Cmd { - // The removal question consumes its answer whole, including cancellation chords. - if c := a.openDevicesCard(); c != nil && c.removing != nil { + a.touchLive() + // The removal or type-permission question consumes its answer whole, including cancellation chords. + if c := a.openDevicesCard(); c != nil && c.confirming() { cmd, _ := c.key(a, msg.String()) a.touch() return cmd @@ -1510,7 +1511,7 @@ func (a *app) enterCheckedLine(ownershipRead bool) tea.Cmd { // window that is not holding the keyboard. The draft is untouched: not // cleared, not sent, exactly where it was. if a.watching() { - return a.takeKeyboard() + return a.liveBarEnter() } if a.openSelectedPaste() { return nil diff --git a/internal/tui3/l4_pair_test.go b/internal/tui3/l4_pair_test.go index 0037d4bcc8..8aaff4b777 100644 --- a/internal/tui3/l4_pair_test.go +++ b/internal/tui3/l4_pair_test.go @@ -24,7 +24,7 @@ func TestL4HomePairCommand(t *testing.T) { // L4-H3d: an outage already said by either producer suppresses the second sentence. func TestL4OneSyncOutageNotice(t *testing.T) { a := &app{file: "chat"} - line := "the sync service at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back" + line := "the relay at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back" if !a.acceptSyncNotice(line) || a.acceptSyncNotice(line) { t.Fatal("outage repeated") } @@ -42,7 +42,7 @@ func TestL4SyncRecoveryRequiresNewSuccess(t *testing.T) { a.syncService = "http://127.0.0.1:8901" now := time.Now() a.clock = func() time.Time { return now } - a.note("the sync service at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back") + a.note("the relay at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back") a.takeRenewalNotice() if !a.syncOutages[a.file] { t.Fatal("an unchanged healthy renewal reading recovered a newer outage") @@ -54,7 +54,7 @@ func TestL4SyncRecoveryRequiresNewSuccess(t *testing.T) { if a.syncOutages[a.file] { t.Fatal("a completed successful renewal did not recover the outage") } - a.note("the sync service at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back") + a.note("the relay at 127.0.0.1:8901 is not answering; this chat keeps working here and catches up when it is back") a.takeRenewalNotice() if !a.syncOutages[a.file] { t.Fatal("evidence from the previous outage recovered the next one") diff --git a/internal/tui3/l4b2_devices_test.go b/internal/tui3/l4b2_devices_test.go index 131569f777..f4ad08e3fc 100644 --- a/internal/tui3/l4b2_devices_test.go +++ b/internal/tui3/l4b2_devices_test.go @@ -86,7 +86,7 @@ func TestL4B2DeviceListsAgree(t *testing.T) { c := a.pair.card.(*deviceCard) listFrame := plain(frame(a)) text := plain(strings.Join(c.rows(160, now, a.pal), "\n")) - if !strings.Contains(text, "sync service: 127.0.0.1:8901 (your own)") || !strings.Contains(text, addDeviceWord) { + if !strings.Contains(text, "relay: 127.0.0.1:8901 (your own)") || !strings.Contains(text, addDeviceWord) { t.Fatal(text) } a.pair.close() @@ -99,7 +99,7 @@ func TestL4B2DeviceListsAgree(t *testing.T) { t.Fatalf("device row differs between the actual screens: %q\n%s", words, plain(frame(a))) } } - if !strings.Contains(plain(frame(a)), "sync service: 127.0.0.1:8901 (your own)") { + if !strings.Contains(plain(frame(a)), "relay: 127.0.0.1:8901 (your own)") { t.Fatal("settings omitted the service") } } diff --git a/internal/tui3/l4fix_devices_test.go b/internal/tui3/l4fix_devices_test.go index fbdaeacbc5..34eb08deaf 100644 --- a/internal/tui3/l4fix_devices_test.go +++ b/internal/tui3/l4fix_devices_test.go @@ -13,14 +13,14 @@ func TestL4FixDeviceCardsSyncOff(t *testing.T) { a.syncService = "off" r.run(a.openDevices()) r.until("devices", func() bool { c, ok := a.pair.card.(*deviceCard); return ok && c.loaded }) - if text := plain(frame(a)); strings.Contains(text, "sync service:") { + if text := plain(frame(a)); strings.Contains(text, "relay:") { t.Fatal(text) } a.pair.close() a.openSettings() walkToDevicesTab(t, a, r) r.until("settings devices", func() bool { return a.sheet.dev != nil && a.sheet.dev.loaded }) - if text := plain(frame(a)); strings.Contains(text, "sync service:") { + if text := plain(frame(a)); strings.Contains(text, "relay:") { t.Fatal(text) } } diff --git a/internal/tui3/l4fix_sync_words_test.go b/internal/tui3/l4fix_sync_words_test.go index 7049f6961b..04c08ba112 100644 --- a/internal/tui3/l4fix_sync_words_test.go +++ b/internal/tui3/l4fix_sync_words_test.go @@ -32,8 +32,8 @@ func TestL4FixSyncOutageWords(t *testing.T) { err error want string }{ - {directory.ErrUnreachable, "the sync service is not answering"}, - {context.DeadlineExceeded, "the sync service did not answer in time"}, + {directory.ErrUnreachable, "the relay is not answering"}, + {context.DeadlineExceeded, "the relay did not answer in time"}, } { got := (machineReading{err: tc.err}).unavailableWord() if got != tc.want { @@ -48,8 +48,8 @@ func TestL4FixSyncOutageWords(t *testing.T) { if strings.Count(notes, "this chat keeps working here") != 1 || strings.Contains(notes, "other machines") { t.Fatal(notes) } - if !strings.Contains(continueUnreachable, "because the sync service is not answering; your words are still in the box") { - t.Fatal(continueUnreachable) + if !strings.Contains(moveUnreachable, "because the relay is not answering; your words are still in the box") { + t.Fatal(moveUnreachable) } } @@ -71,7 +71,7 @@ func TestL4FixResumeCardExplainsOutage(t *testing.T) { // Fresh evidence restores the offer, rather than preserving an obsolete failure. feed.state = dirwatch.State{Up: true} a.tookWatch(dirWatchMsg{from: feed}) - if got := leftOffFrame(a); !strings.Contains(got, "Continue desk-b's latest chat here?") { + if got := leftOffFrame(a); !strings.Contains(got, "Move desk-b's latest chat here?") { t.Fatal(got) } } diff --git a/internal/tui3/live.go b/internal/tui3/live.go new file mode 100644 index 0000000000..e412e123d0 --- /dev/null +++ b/internal/tui3/live.go @@ -0,0 +1,676 @@ +package tui3 + +import ( + "context" + "errors" + "path/filepath" + "strings" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/session" +) + +// ErrNoLiveView is what a door answers when there is simply nothing to open +// live and nothing to say about it, such as a computer that is off with no +// last-seen copy kept. Home then asks the Move card as it always did, without +// a sentence on its foot that would only repeat what the card already says. +var ErrNoLiveView = errors.New("no live view") + +// LiveKind is the state of a live view. The zero value is a healthy live view. +type LiveKind int + +const ( + LiveOn LiveKind = iota + LiveReconnecting + LiveWentOffline + LiveIdle + LiveRevoked + LiveBudget + LiveCopy +) + +// LiveRead is what the door says about a live view right now. It is answered +// from fields already held because it is asked on the draw path. +type LiveRead struct { + Kind LiveKind + Reason string + SeenAt time.Time + // Road is how the bytes of this view travel right now ("direct" or "relay"), + // said by the door on every draw so that a swap of the road shows on the next + // frame. It wins over [LiveSeam.Road] when set; the seam's field is only what + // the first paint knows before the door has been asked. + Road string +} + +// LiveSeam travels on Conversation.Live. A nil seam means the conversation is +// not a live view and every behaviour in this file is absent. +type LiveSeam struct { + Host string + Device string + Cell string + Road string + Row chatlist.Row + Read func() LiveRead + Touch func() + Reconnect func() + Changed func() <-chan struct{} +} + +// liveFront returns the live seam for the conversation currently in front, or +// nil when the front conversation is not a live view. +func (a *app) liveFront() *LiveSeam { + return a.liveView +} + +// liveRead asks the front live seam for its held state, defaulting to LiveOn +// when no reader closure is wired. +func (a *app) liveRead() LiveRead { + live := a.liveFront() + if live == nil || live.Read == nil { + return LiveRead{} + } + return live.Read() +} + +func liveMessageHint(host string) string { + return "Message " + host +} + +func liveLegendHost(host string, on bool) string { + if on { + return "on " + host + " · live" + } + return "on " + host +} + +// seamHost returns the host label for the seam line above the composer. A live +// conversation names the computer it runs on and adds the live word while the +// connection is healthy; every other conversation uses the window-wide host. +func (a *app) seamHost() string { + live := a.liveFront() + if live == nil || live.Host == "" { + return a.host + } + return liveLegendHost(live.Host, a.liveRead().Kind == LiveOn) +} + +// liveMoving reports whether a Move started from the front live view is +// currently running, giving chatlist.LiveMoving the highest bar precedence. +func (a *app) liveMoving() bool { + return a.liveFront() != nil && a.liveMoveFrom != "" && (a.homeTaking != "" || a.homeTakeOpening || a.conversationOpening) +} + +// liveBar returns the dim sentence that stands in the composer's place for a +// live view when typing is not open right now, in the contract's precedence +// order, and false when the composer box itself should stand. +func (a *app) liveBar() (string, bool) { + live := a.liveFront() + if live == nil { + return "", false + } + if a.liveMoving() { + return chatlist.LiveMoving, true + } + read := a.liveRead() + switch read.Kind { + case LiveWentOffline: + return chatlist.LiveWentOffline(live.Host), true + case LiveCopy: + return chatlist.LiveOfflineSeen(live.Host, chatlist.LiveSeenAt(read.SeenAt, a.now())), true + case LiveIdle: + return chatlist.LiveIdle, true + case LiveRevoked: + return chatlist.LiveSaid(read.Reason, live.Host), true + case LiveBudget: + return chatlist.LiveBudget, true + } + if a.link.Driving != nil { + driving := a.link.Driving() + if driving.ReadOnly != "" { + return driving.ReadOnly, true + } + // A VIEW THAT DOES NOT HOLD THE KEYBOARD SAYS SO, WHOEVER HOLDS IT, AND + // WHETHER OR NOT THE BOX HAS WORDS IN IT. The bar stands in the box's place + // ([app.watchBar]), so a draft cannot hide it. What used to hide it was a + // holder with no name: the engine had said another window typed, the + // holder's name had not arrived, and the old condition read an empty name + // as "this view types". The box was then drawn with the keyboard + // elsewhere, no cue anywhere on the frame, and the first enter was a send + // the host refused. [chatlist.LiveTypingFrom] already has a word for a + // holder it cannot name, so the fact is told and the name is optional. + if !driving.Yours { + return chatlist.LiveTypingFrom(driving.Holder), true + } + } + return "", false +} + +// liveBarEnter handles the Enter key while a composer-position bar stands: on a +// live view only LiveIdle reconnects and only a LiveTypingFrom bar takes the +// keyboard, while every other bar leaves the draft untouched and sends nothing. +func (a *app) liveBarEnter() tea.Cmd { + live := a.liveFront() + if live == nil { + return a.takeKeyboard() + } + if a.liveMoving() { + return nil + } + read := a.liveRead() + switch read.Kind { + case LiveIdle: + return a.liveReconnect() + case LiveWentOffline, LiveCopy, LiveRevoked, LiveBudget: + return nil + } + if a.link.Driving != nil { + driving := a.link.Driving() + if driving.ReadOnly != "" { + return nil + } + // ENTER ON A VIEW THAT WATCHES TAKES THE KEYBOARD AND SENDS NOTHING, for the + // reason [app.liveBar] states it: a person can be typing at the host's own + // window, so one keyboard means one enter moves it and a LATER enter sends + // what is in the box. The draft is not touched. + if !driving.Yours { + return a.takeKeyboard() + } + } + return nil +} + +// liveReconnect asks the door to reattach an idle live view off the update loop +// so the UI never blocks on a wire call. +func (a *app) liveReconnect() tea.Cmd { + live := a.liveFront() + if live == nil || live.Reconnect == nil { + return nil + } + reconnect := live.Reconnect + return func() tea.Msg { + reconnect() + return nil + } +} + +// liveRoadWord formats the road value for /status when the front conversation +// is a live view other than an offline copy and the seam names its road. +func (a *app) liveRoadWord() string { + live := a.liveFront() + if live == nil { + return "" + } + read := a.liveRead() + if read.Kind == LiveCopy { + return "" + } + road := read.Road + if road == "" { + road = live.Road + } + return chatlist.LiveRoad(road) +} + +// liveTurnTouchEvery bounds how often a running turn reports activity on a live +// view so streaming deltas do not flood the activity tracker. +const liveTurnTouchEvery = time.Second + +// touchLive reports a person's action on a live front conversation at most once +// per routed message, keeping the idle timer informed without duplicate calls +// when a keystroke also scrolls or sends. +func (a *app) touchLive() { + live := a.liveFront() + if live == nil || live.Touch == nil { + return + } + if a.inRoute && a.liveTouchedInRoute { + return + } + if a.inRoute { + a.liveTouchedInRoute = true + } + a.liveTurnTouchAt = a.now() + live.Touch() +} + +// touchLiveTurn reports activity while a turn is running on a live front +// conversation at most once a second on the surface clock, and never when the +// view is idle. +func (a *app) touchLiveTurn() { + live := a.liveFront() + if live == nil || live.Touch == nil { + return + } + if a.state != stateWorking && a.stream == nil { + return + } + now := a.now() + if !a.liveTurnTouchAt.IsZero() && now.Sub(a.liveTurnTouchAt) < liveTurnTouchEvery { + return + } + a.liveTurnTouchAt = now + live.Touch() +} + +// liveChangedMsg wakes the update loop when a live view's state changes, tagged +// with the conversation generation so an arrival from a conversation no longer +// in front is dropped. +type liveChangedMsg struct { + gen int +} + +// armLive waits for the next change on the front live seam through watchDriving +// so the test harness classifies the channel wait beside DrivingChanged. +func (a *app) armLive() tea.Cmd { + live := a.liveFront() + if live == nil || live.Changed == nil { + return nil + } + a.armingLive = true + cmd := a.watchDriving() + a.armingLive = false + return cmd +} + +// liveMoved repaints the surface and re-arms the wait when the front live +// conversation's state changes, ignoring arrivals from an older generation. +func (a *app) liveMoved(msg liveChangedMsg) tea.Cmd { + if msg.gen != a.convGen { + return nil + } + a.touch() + return tea.Batch(a.wake(), a.armLive()) +} + +// liveOffered says this window may open a live view right now: the opener is +// wired and remote control is switched on. THE SETTING IS ASKED EACH TIME AND +// NEVER KEPT, because a person turns it on in /settings while the window is +// open and the very next Enter on a held chat must open it live; a window that +// remembered the answer from its start was the one that needed a restart. +// With the setting off the answer is false and every caller below does exactly +// what a window with no opener does. +func (a *app) liveOffered() bool { + return a.openLive != nil && (a.remoteControl == nil || a.remoteControl()) +} + +// liveEligible reports whether a chat row held on another computer may be +// opened as a live view in this window: live views are offered +// ([app.liveOffered]), this window is not itself a hosted session, the row is +// held elsewhere, neither this computer nor the holder is marked removed, and +// the holder is another computer in this person's roster. +func (a *app) liveEligible(row chatlist.Row) bool { + if !a.liveOffered() || a.hosted() || a.machineRead.computerRemoved || row.HolderRemoved || !heldElsewhere(row) { + return false + } + for _, d := range a.devRow.devices { + if (row.DeviceID != "" && d.ID == row.DeviceID) || (row.DeviceID == "" && row.Device != "" && d.Name == row.Device) { + return !d.Self + } + } + return false +} + +// homeOpenLiveLater asks the door to open a held chat as a live view off the +// update loop, taking it beside the current conversation on success and falling +// back to the Move card with the door's error on Home's foot when the live open +// fails. +func (a *app) homeOpenLiveLater(line homeLine, row chatlist.Row) tea.Cmd { + a.teamViewSet("") + openLive := a.openLive + baseCtx := a.ctx + if baseCtx == nil { + baseCtx = context.Background() + } + say := func(text string) { + a.home.say(text, "") + } + return a.conversationLater(func() (Conversation, error) { + return openLive(baseCtx, row) + }, say, func(conv Conversation) tea.Cmd { + opened := a.takeBeside(conv) + a.closeHome() + return opened + }, func(err error) tea.Cmd { + cmd := a.homeMachineMove(line) + if !errors.Is(err, ErrNoLiveView) { + a.home.say(err.Error(), "") + } + return cmd + }) +} + +// liveMoveRow returns the directory row for the front live conversation, +// filling any missing identity fields from the live seam and transcript path. +func (a *app) liveMoveRow(live *LiveSeam) chatlist.Row { + row := live.Row + if row.Cell == "" { + row.Cell = live.Cell + } + if row.Cell == "" && a.file != "" { + row.Cell = filepath.Base(session.DirOf(a.file)) + } + if row.Device == "" { + row.Device = live.Host + } + if row.DeviceID == "" { + row.DeviceID = live.Device + } + if row.Status == "" { + row.Status = chatlist.Running + } + return row +} + +// liveMoveIdentity returns the file path or cell identifier that marks a Move +// as having been started from the given live view. +func (a *app) liveMoveIdentity(live *LiveSeam, row chatlist.Row) string { + if a.file != "" { + return a.file + } + if row.Cell != "" { + return row.Cell + } + if live != nil { + return live.Cell + } + return "" +} + +// liveMatchesRow reports whether the front live conversation is viewing the +// same chat as row. +func (a *app) liveMatchesRow(live *LiveSeam, row chatlist.Row) bool { + if live == nil || row.Cell == "" { + return false + } + if live.Cell == row.Cell || live.Row.Cell == row.Cell { + return true + } + return a.file != "" && filepath.Base(session.DirOf(a.file)) == row.Cell +} + +// liveMoveKeyPress handles alt+m in a live front conversation before any +// chat-level use of that key, opening Home and raising the Move card for the +// live conversation's row with the cursor on move here. +func (a *app) liveMoveKeyPress(msg tea.KeyPressMsg) (tea.Cmd, bool) { + if msg.String() != deviceKey { + return nil, false + } + live := a.liveFront() + if live == nil { + return nil, false + } + if a.asking() || a.pageShowing() || a.deckShowing() || a.expandShowing() || + a.pick.open || a.effPick.open || a.roster.open || a.folder.open || + a.shelf.open || a.connPanel.open || a.addPanel.open || a.harnPanel.open || + a.crewUI.open || a.draftPage.open || a.permPanel.open || a.pair.open || + a.subPage.open || a.rewSheet.open || a.rew.on || a.copy.on || + a.welcome.open || a.startingChat() || a.menu.open || a.comp.open || + a.wall.on || a.railHold || a.roomOpen() || a.questionRoomOpen() { + return nil, false + } + row := a.liveMoveRow(live) + a.liveMoveFrom = a.liveMoveIdentity(live, row) + cmd := a.openHome() + asked := a.raiseContinue(row, continueYesAt) + if _, ok := a.homeAsking(); !ok { + a.liveMoveFrom = "" + } + return tea.Batch(cmd, asked), true +} + +// followHolderLive replaces a displaced local front conversation with a live +// view of the new holder when remote control is available and the row is +// eligible, keeping any words already typed in the composer box and retiring +// the old local agent. +// +// THE DOOR IS ASKED OFF THE LOOP, because opening a live view dials another +// computer and a dial may take seconds; the swap itself is the fold, which runs +// on the loop for the conversation that was in front when this was asked and +// for no other. A refusal says the Superseded note the window always said, so a +// window that cannot follow is the window it was. +// +// THE FIRST TRY IS OFTEN EARLY, AND IT IS NOT THE LAST. The directory says the +// chat moved the instant the new holder wins it, and that computer is still +// opening the chat, so its live door is shut for a second or two. A window that +// asked once and gave up stayed read-only for good, because the displacement is +// news only once. [followRetry] asks again a few times, quietly: the sentence +// above is said on the first refusal and never repeated. +func (a *app) followHolderLive(row chatlist.Row) (tea.Cmd, bool) { + return a.followHolder(row, false) +} + +func (a *app) followHolder(row chatlist.Row, retry bool) (tea.Cmd, bool) { + if !a.liveEligible(row) { + return nil, false + } + baseCtx := a.ctx + if baseCtx == nil { + baseCtx = context.Background() + } + if !retry { + a.followSeq++ + a.followRetry = &followRetry{seq: a.followSeq, file: a.file, cell: row.Cell, holder: followHolderKey(row)} + } + seq := a.followSeq + openLive, stale := a.openLive, a.file + return a.offLoop(func() func(bool) tea.Cmd { + conv, err := openLive(baseCtx, row) + return func(here bool) tea.Cmd { + if err != nil { + if here && !retry { + a.note(chatlist.Superseded(nonemptyDevice(row.Device))) + a.touch() + } + if !here || a.file != stale || a.liveFront() != nil { + return nil + } + return a.followLater(seq) + } + if st := a.followRetry; st != nil && st.seq == seq { + a.followRetry = nil + } + if !here || a.file != stale || a.liveFront() != nil { + if conv.Agent != nil { + leaveOffFrame(conv.Agent) + } + return nil + } + return a.swapForLive(conv) + } + }), true +} + +// followRetry is one displacement whose follow has been refused and is being +// asked again. It names the conversation that was displaced and who took it, so +// the retry does nothing once either has changed. +type followRetry struct { + seq uint64 + file string + cell, holder string + tried int +} + +// followRetryWaits are the pauses before each further try, with the last one +// generous: five tries spread over half a minute, which is far longer than a +// computer takes to open the chat it has just taken, and short enough that a +// holder that cannot be reached is given up on while the person still remembers +// what they did. +var followRetryWaits = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 15 * time.Second} + +// followRetryMsg wakes the window for one more try at following a holder. +type followRetryMsg struct{ seq uint64 } + +// followHolderKey is who took the chat, spelled by id when the directory gave +// one and by name when it did not, the same way [app.liveEligible] looks the +// holder up. +func followHolderKey(row chatlist.Row) string { + if row.DeviceID != "" { + return "id:" + row.DeviceID + } + return "name:" + row.Device +} + +// followLater schedules the next try of a displacement, and ends the retrying +// when the tries are spent. +func (a *app) followLater(seq uint64) tea.Cmd { + st := a.followRetry + if st == nil || st.seq != seq { + return nil + } + if st.tried >= len(followRetryWaits) { + a.followRetry = nil + return nil + } + wait := followRetryWaits[st.tried] + st.tried++ + return surfaceTick(wait, func(time.Time) tea.Msg { return followRetryMsg{seq: seq} }) +} + +// followRetried is one more try. It asks only while the window is still on the +// conversation that was displaced, with no live view in front, and the +// directory still says the same computer holds it; anything else ends it. +func (a *app) followRetried(msg followRetryMsg) tea.Cmd { + st := a.followRetry + if st == nil || st.seq != msg.seq { + return nil + } + if a.file != st.file || a.liveFront() != nil || a.hosted() { + a.followRetry = nil + return nil + } + row, held := a.heldElsewhere() + if !held || row.Cell != st.cell || followHolderKey(row) != st.holder { + a.followRetry = nil + return nil + } + cmd, tried := a.followHolder(row, true) + if !tried { + a.followRetry = nil + } + return cmd +} + +// swapForLive puts a live view in the place of the conversation in front: the +// old agent is retired, the words in the box stay in the box, and the new +// conversation is attached through the door every conversation comes through. +func (a *app) swapForLive(conv Conversation) tea.Cmd { + oldAgent := a.agent + oldKey := a.convKey(a.file) + draft := a.mainComposer() + a.detachConversation() + if oldKey != "" { + if held := a.behind[oldKey]; held != nil { + if held.watch != nil { + held.watch.stop() + } + delete(a.behind, oldKey) + } + if oldKey != a.convKey(conv.SessionFile) { + a.forget(oldKey) + } + } + if oldAgent != nil && oldAgent != conv.Agent { + leaveAgent(oldAgent) + } + cmd := a.attachConversation(conv, nil) + if key := a.convKey(conv.SessionFile); key != "" { + a.rememberOpen(key) + } + if !draft.empty() { + a.putComposer(draft) + } + a.touch() + return cmd +} + +const ( + homePermitKind session.QuestionKind = "surface-permit" + permitAskHead = "Let your other computers type into chats here?" + permitAskOptionType = "let them type" + permitAskOptionKeep = "keep them watching" + permitAskOptionPick = "choose in /devices" +) + +func permitAskReason(names []string) string { + var clean []string + for _, name := range names { + if name = strings.TrimSpace(name); name != "" { + clean = append(clean, name) + } + } + who := strings.Join(clean, " and ") + if who == "" { + who = "Your other computers" + } + return who + " can watch your chats here but cannot type yet." +} + +// considerPermitAsk raises the one-time question on Home when a local window has +// older paired computers that can watch chats here but cannot type yet, at most +// once per Home visit and never over another open card. +func (a *app) considerPermitAsk() { + if !a.at(pageHome) || a.hosted() || a.permitAsk == nil || a.home.permitAsked || a.machineRead.computerRemoved { + return + } + if _, asking := a.homeAsking(); asking || a.pair.open { + return + } + names, ask := a.permitAsk.AskOnce() + if !ask { + return + } + a.home.permitAsked = true + a.home.armed = "" + a.raiseHomeAsk(a.permitAskShown(names)) + a.sayHomeAsk() +} + +func (a *app) permitAskShown(names []string) questionShown { + return questionShown{ + question: session.Question{ + ID: a.nextContinueAskID(), + Kind: homePermitKind, + Ask: session.AskConfirmation, + Form: session.FormCard, + Asker: session.Asker{Kind: session.AskerSurface}, + Head: permitAskHead, + Reason: permitAskReason(names), + Options: []session.AnswerOption{ + {Key: "1", Label: permitAskOptionType}, + {Key: "2", Label: permitAskOptionKeep, Safe: true}, + {Key: "3", Label: permitAskOptionPick}, + }, + Stakes: session.StakesReversible, + Asked: a.now(), + }, + pick: 0, + local: func(answer session.Answer) tea.Cmd { + a.dropHomeAsk() + a.home.armed = "" + if a.permitAsk == nil { + return nil + } + key := answer.FirstKey() + var allow bool + switch key { + case "1": + allow = true + case "2", "3": + allow = false + default: + return nil + } + if err := a.permitAsk.Answer(allow); err != nil { + a.home.say(err.Error(), "") + return nil + } + if key == "3" { + return a.openDevices() + } + return nil + }, + } +} diff --git a/internal/tui3/live_follow_test.go b/internal/tui3/live_follow_test.go new file mode 100644 index 0000000000..64afd12b6c --- /dev/null +++ b/internal/tui3/live_follow_test.go @@ -0,0 +1,178 @@ +package tui3 + +import ( + "context" + "path/filepath" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/chatlist" +) + +// The reliability contract of the live view (R1 to R4 of the e2efix lane), as a +// person meets it: +// +// R1 Move here on a live view opens the moved chat on this computer, and the +// words typed next go to that chat. +// R2 The computer that gave the chat up shows a live view of the new holder, +// even when the new holder opens the chat a moment after it is taken. +// R3 When the host goes away and comes back the viewer stays on the live view. +// R4 A road swap is invisible: nothing the viewer already sees disappears, +// repeats or changes place. + +var retryRow = chatlist.Row{ + Cell: "0000000000000042", + Title: "Parser work", + Device: "tower", + DeviceID: "dev_tower", + Status: chatlist.Running, +} + +// retryingDoor is a live door that is shut for the first `shut` asks, the way +// a computer that has just taken a chat is shut until it has opened it. +func retryingDoor(t *testing.T, a *app, shut int) (asked *int, agents *[]*fakeAgent) { + t.Helper() + calls, built := new(int), new([]*fakeAgent) + root := t.TempDir() + a.openLive = func(_ context.Context, row chatlist.Row) (Conversation, error) { + *calls++ + if *calls <= shut { + return Conversation{}, ErrNoLiveView + } + agent := &fakeAgent{model: "m"} + *built = append(*built, agent) + return Conversation{ + Agent: agent, + SessionFile: filepath.Join(root, row.Cell, "session.jsonl"), + Live: &LiveSeam{ + Host: row.Device, Device: row.DeviceID, Cell: row.Cell, Row: row, + Read: func() LiveRead { return LiveRead{Kind: LiveOn} }, + }, + Link: &LinkSeam{}, + }, nil + } + return calls, built +} + +func supersededNotes(a *app) int { + n := 0 + for _, e := range a.entries { + if e.kind == entryNote && strings.Contains(e.text, chatlist.Superseded("tower")) { + n++ + } + } + return n +} + +// R2: a window whose chat was taken asks the new holder for a live view as soon +// as the directory says so. That computer may not have the chat open yet, and +// the window used to give up on the first refusal and stay read-only for good. +// It must try again, quietly, and end up on a live view. +func TestR2AWindowWhoseNewHolderOpensTheChatLateStillFollowsIt(t *testing.T) { + oldAgent := &fakeAgent{model: "m"} + a := newTestApp(oldAgent) + t.Cleanup(a.doorLine.close) + a.dismissWelcome() + a.devRow.devices = rosterOf + a.takeUp(Conversation{ + Agent: oldAgent, + SessionFile: filepath.Join(t.TempDir(), retryRow.Cell, "session.jsonl"), + }, true) + a.input.setText("words already in the box") + calls, agents := retryingDoor(t, a, 2) + + drain(t, a, a.recordMachines(homeMachinesMsg{rows: []chatlist.Row{retryRow}})) + if *calls != 1 || a.liveFront() != nil { + t.Fatalf("first try: %d asks, live view %v; want one refused ask and no view", *calls, a.liveFront()) + } + if supersededNotes(a) != 1 { + t.Fatalf("the refused first try said the superseded sentence %d times, want once", supersededNotes(a)) + } + if a.followRetry == nil { + t.Fatal("a refused first try left nothing to try again with") + } + + // The second try is refused as well, and says nothing more. + drain(t, a, a.followRetried(followRetryMsg{seq: a.followRetry.seq})) + if *calls != 2 || a.liveFront() != nil { + t.Fatalf("second try: %d asks, live view %v; want two asks and no view", *calls, a.liveFront()) + } + if supersededNotes(a) != 1 { + t.Fatalf("a refused retry repeated the superseded sentence (%d times)", supersededNotes(a)) + } + + // The third finds the door open: the window becomes a live view of the new + // holder with the old agent retired and the typed words kept. + drain(t, a, a.followRetried(followRetryMsg{seq: a.followRetry.seq})) + if a.liveFront() == nil || a.liveFront().Host != "tower" || len(*agents) != 1 || a.agent != (*agents)[0] { + t.Fatalf("third try did not end on a live view of the new holder: live=%+v", a.liveFront()) + } + if oldAgent.closes != 1 { + t.Fatalf("old local agent closes = %d, want 1", oldAgent.closes) + } + if got := a.input.String(); got != "words already in the box" { + t.Fatalf("composer words after the follow = %q", got) + } + if a.followRetry != nil { + t.Fatal("a finished follow left its retry behind") + } +} + +// R2, the bound: a holder that never opens the chat is asked a few times and +// then left alone, and a retry that outlived its displacement does nothing. +func TestR2TheRetriesStopWhenTheyAreSpentOrNoLongerWanted(t *testing.T) { + oldAgent := &fakeAgent{model: "m"} + a := newTestApp(oldAgent) + t.Cleanup(a.doorLine.close) + a.dismissWelcome() + a.devRow.devices = rosterOf + a.takeUp(Conversation{ + Agent: oldAgent, + SessionFile: filepath.Join(t.TempDir(), retryRow.Cell, "session.jsonl"), + }, true) + calls, _ := retryingDoor(t, a, 1000) + + drain(t, a, a.recordMachines(homeMachinesMsg{rows: []chatlist.Row{retryRow}})) + seq := a.followRetry.seq + for i := 0; i < len(followRetryWaits)+3 && a.followRetry != nil; i++ { + drain(t, a, a.followRetried(followRetryMsg{seq: seq})) + } + if a.followRetry != nil { + t.Fatal("the retries never ended") + } + if want := 1 + len(followRetryWaits); *calls != want { + t.Fatalf("asked the door %d times, want %d (the first try and %d retries)", *calls, want, len(followRetryWaits)) + } + if supersededNotes(a) != 1 { + t.Fatalf("the superseded sentence was said %d times, want once", supersededNotes(a)) + } + // A late timer of the finished displacement is ignored. + before := *calls + drain(t, a, a.followRetried(followRetryMsg{seq: seq})) + if *calls != before { + t.Fatal("a stale retry timer asked the door") + } +} + +// R2: the person moved on, so the retry must not swap the window under them. +func TestR2ARetryDoesNothingOnceThePersonLeftTheDisplacedChat(t *testing.T) { + oldAgent := &fakeAgent{model: "m"} + a := newTestApp(oldAgent) + t.Cleanup(a.doorLine.close) + a.dismissWelcome() + a.devRow.devices = rosterOf + a.takeUp(Conversation{ + Agent: oldAgent, + SessionFile: filepath.Join(t.TempDir(), retryRow.Cell, "session.jsonl"), + }, true) + calls, _ := retryingDoor(t, a, 1) + drain(t, a, a.recordMachines(homeMachinesMsg{rows: []chatlist.Row{retryRow}})) + a.file = filepath.Join(t.TempDir(), "0000000000000099", "session.jsonl") + drain(t, a, a.followRetried(followRetryMsg{seq: a.followRetry.seq})) + if *calls != 1 || a.liveFront() != nil { + t.Fatalf("a retry after the person left asked the door again (%d asks) or opened a view (%v)", *calls, a.liveFront()) + } + if a.followRetry != nil { + t.Fatal("a retry for a conversation no longer in front was kept") + } +} diff --git a/internal/tui3/live_keyboard_test.go b/internal/tui3/live_keyboard_test.go new file mode 100644 index 0000000000..3aa36c80f2 --- /dev/null +++ b/internal/tui3/live_keyboard_test.go @@ -0,0 +1,174 @@ +package tui3 + +import ( + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/chatlist" +) + +// keyboardOf builds a live view whose keyboard fact the test moves, with a Take +// that behaves as the engine does (it hands the keyboard to this view) and counts +// how many times it was asked. +func keyboardOf(t *testing.T, holder Driving) (*app, *fakeAgent, *Driving, *int) { + t.Helper() + agent := &fakeAgent{model: "m"} + a := newTestApp(agent) + a.width = 100 + a.title = "chat" + a.dismissWelcome() + driving := holder + taken := 0 + a.takeUp(Conversation{ + Agent: agent, + Link: &LinkSeam{ + Driving: func() Driving { return driving }, + Take: func() error { + taken++ + driving = Driving{Yours: true} + return nil + }, + }, + Live: &LiveSeam{ + Host: "Desktop", + Read: func() LiveRead { return LiveRead{Kind: LiveOn} }, + }, + }, true) + return a, agent, &driving, &taken +} + +// R6: a live view that does not hold the keyboard says so on its frame, whether +// the box is empty or holds a draft, and whether or not the engine has told it +// the holder's name. When it holds the keyboard that line is not shown. +func TestR6ALiveViewWithoutTheKeyboardSaysSoWhateverTheBoxHolds(t *testing.T) { + const draft = "words kept in the box" + for _, tc := range []struct { + name string + driving Driving + text string + }{ + {"named holder, empty box", Driving{Yours: false, Holder: "Desktop"}, ""}, + {"named holder, a draft", Driving{Yours: false, Holder: "Desktop"}, draft}, + {"unnamed holder, empty box", Driving{Yours: false}, ""}, + {"unnamed holder, a draft", Driving{Yours: false}, draft}, + } { + t.Run(tc.name, func(t *testing.T) { + a, _, _, _ := keyboardOf(t, tc.driving) + if tc.text != "" { + a.input.setText(tc.text) + } + want := chatlist.LiveTypingFrom(tc.driving.Holder) + if !a.watching() { + t.Fatalf("a live view without the keyboard did not report watching") + } + screen := plain(frame(a)) + if !strings.Contains(screen, want) { + t.Fatalf("the frame never says %q:\n%s", want, screen) + } + if tc.text != "" && strings.Contains(screen, tc.text) { + t.Fatalf("the draft was drawn beside the line that says the keyboard is elsewhere:\n%s", screen) + } + if tc.text != "" && a.input.String() != tc.text { + t.Fatalf("the draft is %q, want it kept as %q", a.input.String(), tc.text) + } + }) + } + + for _, text := range []string{"", draft} { + a, _, _, _ := keyboardOf(t, Driving{Yours: true}) + if text != "" { + a.input.setText(text) + } + if a.watching() { + t.Fatalf("a live view that holds the keyboard reported watching (box %q)", text) + } + if screen := plain(frame(a)); strings.Contains(screen, "typing from") { + t.Fatalf("a live view that holds the keyboard still says it does not (box %q):\n%s", text, screen) + } + } +} + +// R7: enter on a live view that does not hold the keyboard takes it and sends +// nothing, a draft in the box stays put, and the next enter sends it once. +func TestR7EnterOnAWatchingViewTakesTheKeyboardAndTheNextEnterSendsOnce(t *testing.T) { + const draft = "send me after the take" + for _, tc := range []struct { + name string + driving Driving + }{ + {"named holder", Driving{Yours: false, Holder: "Desktop"}}, + {"unnamed holder", Driving{Yours: false}}, + } { + t.Run(tc.name, func(t *testing.T) { + a, agent, driving, taken := keyboardOf(t, tc.driving) + a.input.setText(draft) + + drive(t, a, key("enter")) + if *taken != 1 { + t.Fatalf("enter on a watching view asked for the keyboard %d times, want once", *taken) + } + if len(agent.sent) != 0 { + t.Fatalf("the enter that took the keyboard also sent %v, want nothing", agent.sent) + } + if got := a.input.String(); got != draft { + t.Fatalf("taking the keyboard changed the draft to %q, want %q", got, draft) + } + if !driving.Yours || a.watching() { + t.Fatalf("the view still reports another window typing after the take: %+v", *driving) + } + + drive(t, a, key("enter")) + if len(agent.sent) != 1 || agent.sent[0] != draft { + t.Fatalf("the enter after the take sent %v, want [%s] once", agent.sent, draft) + } + if *taken != 1 { + t.Fatalf("the sending enter asked for the keyboard again (%d asks in all)", *taken) + } + }) + } +} + +// R8: with remote control off, which is every conversation that is not a live +// view, nothing changes: the first enter sends, no line says the keyboard is +// elsewhere, and a window that watches a local conversation another window is +// typing into keeps its own wording. +func TestR8WithRemoteControlOffAConversationKeepsItsKeyboardRoad(t *testing.T) { + agent := &fakeAgent{model: "m"} + a := newTestApp(agent) + a.width = 100 + a.dismissWelcome() + a.takeUp(Conversation{Agent: agent}, true) + a.input.setText("an ordinary line") + if a.watching() { + t.Fatal("a conversation with no live view and no link reported watching") + } + drive(t, a, key("enter")) + if len(agent.sent) != 1 || agent.sent[0] != "an ordinary line" { + t.Fatalf("the first enter on an ordinary conversation sent %v, want [an ordinary line]", agent.sent) + } + + // A local conversation another window is typing into has no live view, and it + // keeps the bar and the keys it always had, with no machine named. + local := &fakeAgent{model: "m"} + w := newTestApp(local) + w.width = 100 + w.dismissWelcome() + taken := 0 + w.takeUp(Conversation{ + Agent: local, + Link: &LinkSeam{ + Driving: func() Driving { return Driving{Yours: false} }, + Take: func() error { taken++; return nil }, + }, + }, true) + if !w.watching() { + t.Fatal("a local watcher stopped reporting watching") + } + screen := plain(frame(w)) + if !strings.Contains(screen, "typing from another window now") || !strings.Contains(screen, watchKeysWord) { + t.Fatalf("a local watcher lost its own words:\n%s", screen) + } + if strings.Contains(screen, chatlist.LiveTypingFrom("")) { + t.Fatalf("a local watcher was given the live view's sentence:\n%s", screen) + } +} diff --git a/internal/tui3/live_move_test.go b/internal/tui3/live_move_test.go new file mode 100644 index 0000000000..d8fc29443a --- /dev/null +++ b/internal/tui3/live_move_test.go @@ -0,0 +1,44 @@ +package tui3 + +import ( + "path/filepath" + "testing" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/session" +) + +// R1: a live view mirrors the host's own words, and when another computer +// takes the chat the host says that it did. If this window is the computer that +// took it, the sentence arrives in the moment between the move landing and the +// moved chat taking the screen, and it is about the chat as it was, not about +// the chat now. It must not stop the words the person types next. +func TestR1ASentenceTheHostSaysAboutTheMoveDoesNotStopTheWordsTypedNext(t *testing.T) { + a, _ := liveWithRecord(t, session.DisplayEntry{Role: "user", Text: "host question"}) + cell := filepath.Base(session.DirOf(a.file)) + // What a finished move leaves behind: the new hold, at the fence the move + // took, still waiting for its writer to say it holds. + a.machineRead.sendHolds = map[string]sendHold{cell: {fence: 2, awaitingWriter: true}} + + a.note(chatlist.Superseded("laptop")) + + if held := a.machineRead.sendHolds[cell]; held.blocked { + t.Fatalf("a sentence a live view mirrored blocked the hold the move just made: %+v", held) + } +} + +// R5: outside a live view, a displacement sentence still stops the window's own +// sends, which is what it is for. +func TestR5ASentenceAboutADisplacementStillStopsAWindowThatIsNotALiveView(t *testing.T) { + a := newTestApp(&fakeAgent{model: "m"}) + a.dismissWelcome() + a.file = filepath.Join(t.TempDir(), retryRow.Cell, "session.jsonl") + cell := filepath.Base(session.DirOf(a.file)) + a.machineRead.sendHolds = map[string]sendHold{cell: {fence: 2}} + + a.note(chatlist.Superseded("laptop")) + + if held := a.machineRead.sendHolds[cell]; !held.blocked { + t.Fatalf("a displaced window's own hold was not blocked by the sentence: %+v", held) + } +} diff --git a/internal/tui3/live_notes_test.go b/internal/tui3/live_notes_test.go new file mode 100644 index 0000000000..ba909d51a9 --- /dev/null +++ b/internal/tui3/live_notes_test.go @@ -0,0 +1,131 @@ +package tui3 + +import ( + "path/filepath" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/session" +) + +// liveRefreshAgent is a live view's agent whose snapshot is whatever the test +// says the host's record holds now. +type liveRefreshAgent struct { + *fakeAgent + record []session.DisplayEntry +} + +func (l *liveRefreshAgent) AttachReplay() ([]session.DisplayEntry, <-chan session.Event, func()) { + return append([]session.DisplayEntry(nil), l.record...), nil, nil +} + +func liveWithRecord(t *testing.T, record ...session.DisplayEntry) (*app, *liveRefreshAgent) { + t.Helper() + agent := &liveRefreshAgent{fakeAgent: &fakeAgent{model: "m"}, record: record} + a := newTestApp(agent) + t.Cleanup(a.doorLine.close) + a.dismissWelcome() + a.takeUp(Conversation{ + Agent: agent, + SessionFile: filepath.Join(t.TempDir(), retryRow.Cell, "session.jsonl"), + Live: &LiveSeam{ + Host: "tower", Device: "dev_tower", Cell: retryRow.Cell, Row: retryRow, + Read: func() LiveRead { return LiveRead{Kind: LiveOn} }, + }, + Link: &LinkSeam{}, + }, true) + a.replayList(record) + return a, agent +} + +func noteIndexes(a *app, text string) []int { + var at []int + for i, e := range a.entries { + if e.kind == entryNote && e.text == text { + at = append(at, i) + } + } + return at +} + +// R4: the snapshot a live view takes again after a reconnect (a road swap is +// one) rebuilds the transcript from the host's record. A sentence this window +// said about itself is in nobody's record, and it must still be there once, in +// the place the person read it. +func TestR4ASnapshotRefreshKeepsWhatTheViewerWasToldLocally(t *testing.T) { + const failed = "could not move this chat here" + a, agent := liveWithRecord(t, + session.DisplayEntry{Role: "user", Text: "host question"}, + session.DisplayEntry{Role: "assistant", Text: "host answer"}) + a.note(failed) + if len(noteIndexes(a, failed)) != 1 { + t.Fatalf("setup: the sentence was not written once:\n%+v", a.entries) + } + last := len(a.entries) + + // The host answered a second question while the road swapped: the refreshed + // record is longer than what the viewer drew. + agent.record = append(agent.record, + session.DisplayEntry{Role: "user", Text: "later question"}, + session.DisplayEntry{Role: "assistant", Text: "later answer"}) + drain(t, a, a.refreshHostedReplay()) + + at := noteIndexes(a, failed) + if len(at) != 1 { + t.Fatalf("the sentence is on screen %d times after a refresh, want once:\n%+v", len(at), a.entries) + } + if at[0] >= len(a.entries)-1 || at[0] > last { + t.Fatalf("the sentence moved to the end (%d of %d) instead of staying where it was read (%d)", at[0], len(a.entries), last-1) + } + for i, want := range []string{"host question", "host answer"} { + if a.entries[i].text != want { + t.Fatalf("entry %d = %q, want %q: the record was reordered", i, a.entries[i].text, want) + } + } + if !strings.Contains(plain(frame(a)), failed) { + t.Fatalf("the frame lost the sentence:\n%s", plain(frame(a))) + } +} + +// R4: a second refresh in a row neither repeats nor drops it, and two notes +// keep their order. +func TestR4TwoRefreshesKeepTwoNotesOnceAndInOrder(t *testing.T) { + a, _ := liveWithRecord(t, + session.DisplayEntry{Role: "user", Text: "host question"}, + session.DisplayEntry{Role: "assistant", Text: "host answer"}) + a.note("first sentence") + a.note("second sentence") + for i := 0; i < 2; i++ { + drain(t, a, a.refreshHostedReplay()) + } + first, second := noteIndexes(a, "first sentence"), noteIndexes(a, "second sentence") + if len(first) != 1 || len(second) != 1 || first[0] >= second[0] { + t.Fatalf("notes after two refreshes: first at %v, second at %v; want one each, in order:\n%+v", first, second, a.entries) + } +} + +// R4: a sentence the host's record already says is not drawn twice. +func TestR4ARecordedSentenceIsNotRepeatedByTheLocalCopy(t *testing.T) { + a, agent := liveWithRecord(t, session.DisplayEntry{Role: "user", Text: "host question"}) + a.note("said both places") + agent.record = append(agent.record, session.DisplayEntry{Role: "aside", Text: "said both places"}) + drain(t, a, a.refreshHostedReplay()) + if n := len(noteIndexes(a, "said both places")); n > 1 { + t.Fatalf("the sentence is drawn %d times, want at most once", n) + } +} + +// R5: a conversation held over ssh (no live seam) keeps the refresh it always +// had, which rebuilds from the host's record alone. +func TestR5ASnapshotRefreshWithoutALiveViewIsUnchanged(t *testing.T) { + agent := &liveRefreshAgent{fakeAgent: &fakeAgent{model: "m"}, record: []session.DisplayEntry{{Role: "user", Text: "host question"}}} + a := newTestApp(agent) + t.Cleanup(a.doorLine.close) + a.dismissWelcome() + a.replayList(agent.record) + a.note("a local sentence") + drain(t, a, a.refreshHostedReplay()) + if n := len(noteIndexes(a, "a local sentence")); n != 0 { + t.Fatalf("a window that is not a live view kept a local note across the refresh (%d)", n) + } +} diff --git a/internal/tui3/live_remote_control_off_test.go b/internal/tui3/live_remote_control_off_test.go new file mode 100644 index 0000000000..ce8562e27a --- /dev/null +++ b/internal/tui3/live_remote_control_off_test.go @@ -0,0 +1,48 @@ +package tui3 + +import ( + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/chatlist" +) + +// Written from the contract for the person turning remote control off on the +// computer being watched: the view that was open on it says that, in the one +// sentence the host's reason has, in the place a view's state is said. It never +// says the computer went offline, and it never carries the words of a link that +// is being repaired, because the computer is up and said no. +func TestAViewTheHostSwitchedOffSaysSoAndNeverSaysWentOffline(t *testing.T) { + a := newTestApp(&fakeAgent{model: "m"}) + a.dismissWelcome() + a.takeUp(Conversation{ + Agent: &fakeAgent{model: "m"}, + Live: &LiveSeam{ + Host: "Desktop", + Read: func() LiveRead { + return LiveRead{Kind: LiveRevoked, Reason: "remote-control-off"} + }, + }, + }, true) + + bar, ok := a.liveBar() + if !ok { + t.Fatal("a view the host switched off drew no sentence in the box's place") + } + const want = "Desktop turned remote control off." + if bar != want { + t.Fatalf("the bar reads %q, want exactly %q", bar, want) + } + if strings.Contains(bar, chatlist.LiveWentOffline("Desktop")) { + t.Fatalf("the bar says the computer went offline: %q", bar) + } + screen := plain(frame(a)) + if !strings.Contains(screen, want) { + t.Fatalf("the frame does not say %q:\n%s", want, screen) + } + for _, never := range []string{"went offline", "reconnecting"} { + if strings.Contains(screen, never) { + t.Fatalf("the frame says %q although the computer is up and said no:\n%s", never, screen) + } + } +} diff --git a/internal/tui3/live_roster_test.go b/internal/tui3/live_roster_test.go new file mode 100644 index 0000000000..d9a685fab1 --- /dev/null +++ b/internal/tui3/live_roster_test.go @@ -0,0 +1,122 @@ +package tui3 + +import ( + "context" + "testing" + + "github.com/Agent-Field/codeaf/internal/chatlist" +) + +// rosterFleet is a fleet that lists its devices when asked, the way a directory +// read does, and counts the asks. +type rosterFleet struct { + devices []chatlist.Device + asks int +} + +func (f *rosterFleet) FleetSize(context.Context) (int, error) { return len(f.devices), nil } + +func (f *rosterFleet) Roster(context.Context) ([]chatlist.Device, error) { + f.asks++ + return f.devices, nil +} + +func moveCardRaised(a *app) bool { + ask, ok := a.homeAsking() + return ok && ask.question.Head == moveAsk +} + +// R3 (the open the rest stands on): Enter on a chat another computer holds opens +// a live view, never the Move card, when that computer is one of the person's +// own. The listing of chats and the list of computers are two reads begun +// together, so a chat can be on screen, and entered, before the computers have +// answered; that Enter used to be refused with a Move card nobody asked for. +func TestR3EnterOnAHeldChatBeforeTheRosterAnswersStillOpensItLive(t *testing.T) { + a, taker := liveHomeRig(t, "dev_tower") + calls, _ := wireFakeOpenLive(t, a, nil) + fleet := &rosterFleet{devices: rosterOf} + a.fleet = fleet + a.devRow.devices = nil // the listing has landed; the roster has not + + standOn(t, a, "c1") + + if moveCardRaised(a) { + t.Fatal("Enter on a chat held by one of the person's own computers raised the Move card before the roster could say so") + } + if len(*calls) != 1 || (*calls)[0].Cell != "c1" || a.liveFront() == nil || a.at(pageHome) { + t.Fatalf("the Enter did not end on a live view: opens=%d live=%v home=%v", len(*calls), a.liveFront(), a.at(pageHome)) + } + if len(taker.cells) != 0 { + t.Fatalf("a live open moved the chat: %v", taker.cells) + } + if fleet.asks != 1 { + t.Fatalf("the roster was asked %d times, want once", fleet.asks) + } +} + +// R3: a roster read that was already out when Enter came may predate the +// computer it is looking for, so it does not decide the Enter: a read begun +// after it does. +func TestR3AnAnswerThatPredatesTheEnterDoesNotDecideIt(t *testing.T) { + a, _ := liveHomeRig(t, "dev_tower") + calls, _ := wireFakeOpenLive(t, a, nil) + fleet := &rosterFleet{devices: rosterOf} + a.fleet = fleet + a.devRow.devices = nil + a.devRow.asking, a.devRow.asked = true, 3 + + standOn(t, a, "c1") + if moveCardRaised(a) || len(*calls) != 0 { + t.Fatalf("the Enter was decided before any roster answered: card=%v opens=%d", moveCardRaised(a), len(*calls)) + } + + again := a.tookRoster(rosterMsg{seq: 3}) + if again == nil { + t.Fatal("an answer from before the Enter ended the wait without a fresh read") + } + if moveCardRaised(a) { + t.Fatal("the old answer, which lacks the computer, raised the Move card") + } + drain(t, a, again) + if len(*calls) != 1 || a.liveFront() == nil { + t.Fatalf("the fresh read did not open the chat live: opens=%d live=%v", len(*calls), a.liveFront()) + } + if fleet.asks != 1 { + t.Fatalf("fresh reads = %d, want one", fleet.asks) + } +} + +// R3, the other half: a computer the fresh roster does not list is not one of +// the person's own, and the Enter ends in the Move card as it always did. +func TestR3AComputerTheRosterDoesNotListStillGetsTheMoveCard(t *testing.T) { + a, _ := liveHomeRig(t, "dev_tower") + calls, _ := wireFakeOpenLive(t, a, nil) + fleet := &rosterFleet{devices: rosterOf[:1]} + a.fleet = fleet + a.devRow.devices = nil + + standOn(t, a, "c1") + + if !moveCardRaised(a) || len(*calls) != 0 { + t.Fatalf("an unlisted computer did not end in the Move card: card=%v opens=%d", moveCardRaised(a), len(*calls)) + } +} + +// R3: a second Enter while the first waits for the roster asks for nothing more. +func TestR3AnEnterThatIsAlreadyWaitingForTheRosterIsNotQueuedTwice(t *testing.T) { + a, _ := liveHomeRig(t, "dev_tower") + calls, _ := wireFakeOpenLive(t, a, nil) + fleet := &rosterFleet{devices: rosterOf} + a.fleet = fleet + a.devRow.devices = nil + a.devRow.asking, a.devRow.asked = true, 1 + + standOn(t, a, "c1") + standOn(t, a, "c1") + drain(t, a, a.tookRoster(rosterMsg{seq: 1})) + drain(t, a, a.tookRoster(rosterMsg{devices: rosterOf, seq: 2})) + + if len(*calls) != 1 { + t.Fatalf("two Enters opened the chat %d times, want once", len(*calls)) + } +} diff --git a/internal/tui3/live_setting_test.go b/internal/tui3/live_setting_test.go new file mode 100644 index 0000000000..ef646416af --- /dev/null +++ b/internal/tui3/live_setting_test.go @@ -0,0 +1,173 @@ +package tui3 + +import ( + "context" + "testing" + + "github.com/Agent-Field/codeaf/internal/chatlist" +) + +// THE SETTING IS READ LIVE. Remote control is turned on and off in /settings +// while a window is open, so whether Enter on a chat another computer holds opens +// it live or asks to move it must follow the setting at the moment of the Enter, +// not the setting at the moment the window started. These tests state that from +// the person's side: the setting is a function the test flips, the rest is the +// Home screen as the other live-view tests drive it. + +// liveSetting is the setting as a test switches it. +type liveSetting struct{ on bool } + +func (s *liveSetting) read() bool { return s.on } + +// settingRig is a Home with one chat held by an online computer of the +// person's own, the live opener wired, and the setting read through a function +// the returned value flips. +func settingRig(t *testing.T, on bool) (*app, *fakeTaker, *liveSetting, *[]chatlist.Row) { + t.Helper() + a, taker := liveHomeRig(t, "dev_tower") + calls, _ := wireFakeOpenLive(t, a, nil) + setting := &liveSetting{on: on} + a.remoteControl = setting.read + return a, taker, setting, calls +} + +// C1: a window that began with remote control off, then had it switched on, +// opens a held chat live on the next Enter, and never raised the Move card for it. +func TestAWindowSwitchedOnAfterItStartedOpensAHeldChatLive(t *testing.T) { + a, taker, setting, calls := settingRig(t, false) + + standOn(t, a, "c1") + if !moveCardRaised(a) || len(*calls) != 0 || !a.at(pageHome) { + t.Fatalf("with remote control off the Enter did not end in the Move card: card=%v opens=%d home=%v", moveCardRaised(a), len(*calls), a.at(pageHome)) + } + + setting.on = true + standOn(t, a, "c1") + if len(*calls) != 1 || (*calls)[0].Cell != "c1" { + t.Fatalf("after switching remote control on the Enter made %d live opens, want one for c1", len(*calls)) + } + if a.liveFront() == nil || a.liveFront().Cell != "c1" || a.at(pageHome) { + t.Fatalf("after switching remote control on the Enter did not end on a live view: live=%v home=%v", a.liveFront(), a.at(pageHome)) + } + if len(taker.cells) != 0 { + t.Fatalf("the live open moved the chat: %v", taker.cells) + } +} + +// C1, the other direction: switching it off in a window that has the opener +// brings the Move card back at once. +func TestAWindowSwitchedOffAfterItStartedAsksToMoveAHeldChat(t *testing.T) { + a, _, setting, calls := settingRig(t, true) + setting.on = false + + standOn(t, a, "c1") + if !moveCardRaised(a) || len(*calls) != 0 || !a.at(pageHome) { + t.Fatalf("with remote control switched off the Enter did not end in the Move card: card=%v opens=%d home=%v", moveCardRaised(a), len(*calls), a.at(pageHome)) + } +} + +// C2: with remote control off, a window that has the opener wired behaves BYTE +// FOR BYTE as a window that has none: the same frame, the same foot, no live +// attempt, and no wait for the roster that a held chat on a computer the roster +// has not yet listed would otherwise cause. +func TestWithRemoteControlOffAWiredOpenerChangesNothingOnHome(t *testing.T) { + // The listing has landed and the roster has not, which is the case where an + // opener that was offered would hold the Enter and ask the roster first. + build := func(wired bool) (*app, *rosterFleet, *[]chatlist.Row) { + a, _ := liveHomeRig(t, "dev_tower") + fleet := &rosterFleet{devices: rosterOf} + a.fleet = fleet + a.devRow.devices = nil + var calls *[]chatlist.Row + if wired { + calls, _ = wireFakeOpenLive(t, a, nil) + a.remoteControl = (&liveSetting{on: false}).read + } + return a, fleet, calls + } + bare, bareFleet, _ := build(false) + wired, wiredFleet, calls := build(true) + + standOn(t, bare, "c1") + standOn(t, wired, "c1") + + if got, want := homeText(wired), homeText(bare); got != want { + t.Fatalf("the Home frame differs once the opener is wired with remote control off:\n--- wired\n%s\n--- bare\n%s", got, want) + } + if wired.home.msg != bare.home.msg { + t.Fatalf("the foot differs: wired %q, bare %q", wired.home.msg, bare.home.msg) + } + if !moveCardRaised(wired) { + t.Fatal("the Enter did not end in the Move card") + } + if len(*calls) != 0 { + t.Fatalf("remote control off still attempted %d live opens", len(*calls)) + } + if wiredFleet.asks != bareFleet.asks || wiredFleet.asks != 0 { + t.Fatalf("the roster was asked %d times (bare %d), want none: an Enter with remote control off waits for nothing", wiredFleet.asks, bareFleet.asks) + } +} + +// C2: the displacement follow, which opens the new holder's view when another +// computer takes this window's chat, is also a live view and is also absent +// while remote control is off. +func TestAHolderIsNotFollowedLiveWhileRemoteControlIsOff(t *testing.T) { + a, _, setting, _ := settingRig(t, false) + row := a.machineRead.rows[0] + + if cmd, followed := a.followHolderLive(row); followed || cmd != nil { + t.Fatal("the window followed a holder live with remote control off") + } + setting.on = true + if _, followed := a.followHolderLive(row); !followed { + t.Fatal("the window did not follow a holder live with remote control on") + } +} + +// C4: a hosted window never offers live views, whatever the setting says. +func TestAHostedWindowNeverOffersLiveViewsWhateverTheSettingSays(t *testing.T) { + a, _, _, calls := settingRig(t, true) + a.host = "devbox" + + if a.liveEligible(a.machineRead.rows[0]) { + t.Fatal("a hosted window offered a live view with remote control on") + } + standOn(t, a, "c1") + if len(*calls) != 0 || a.liveFront() != nil { + t.Fatalf("a hosted window opened a live view: opens=%d live=%v", len(*calls), a.liveFront()) + } +} + +// A window with an opener and no setting seam offers live views, as every window +// did before the setting was handed in, and a window with a setting seam and no +// opener offers none however the setting reads. +func TestTheOpenerAloneDecidesWhenNoSettingIsHandedIn(t *testing.T) { + a, _, _, _ := settingRig(t, false) + a.remoteControl = nil + if !a.liveOffered() { + t.Fatal("an opener with no setting seam was not offered") + } + a.openLive = nil + a.remoteControl = (&liveSetting{on: true}).read + if a.liveOffered() { + t.Fatal("a window with no opener offered live views because the setting reads on") + } +} + +// Options.RemoteControl is what a window reads: the function handed in at +// construction is the one asked at each Enter. +func TestTheSettingHandedInAtConstructionIsTheOneAsked(t *testing.T) { + setting := &liveSetting{} + a := newApp(context.Background(), Options{ + Agent: &fakeAgent{model: "m"}, Workspace: "/tmp/lab", ProfileDir: mintProfileDir(), + OpenLive: func(context.Context, chatlist.Row) (Conversation, error) { return Conversation{}, ErrNoLiveView }, + RemoteControl: setting.read, + }) + if a.liveOffered() { + t.Fatal("a window built with the setting off offers live views") + } + setting.on = true + if !a.liveOffered() { + t.Fatal("a window built with the setting off did not follow it switching on") + } +} diff --git a/internal/tui3/live_test.go b/internal/tui3/live_test.go new file mode 100644 index 0000000000..7571e41315 --- /dev/null +++ b/internal/tui3/live_test.go @@ -0,0 +1,726 @@ +package tui3 + +import ( + "path/filepath" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/session" +) + +// V1/T6 (contract 2): an empty composer on a live view invites a message to the +// computer the chat runs on, while a conversation with no live seam keeps its +// team hint or its empty placeholder. +func TestALiveConversationInvitesAMessageToTheComputerItRunsOn(t *testing.T) { + a, harbor, _, _ := trafficApp(t) + a.wall.activeID = harbor + managerFile := a.file + teamHint := "to " + a.teamManagerMark() + " manager of harbor" + if got := a.trafficHint(); got != teamHint { + t.Fatalf("managed team conversation without a live seam lost its team hint: got %q, want %q", got, teamHint) + } + + plainApp := newTestApp(&fakeAgent{model: "m"}) + if got := plainApp.trafficHint(); got != "" { + t.Fatalf("plain conversation without a live seam drew a hint: %q", got) + } + + a.takeUp(Conversation{ + Agent: &fakeAgent{model: "m"}, + SessionFile: managerFile, + Live: &LiveSeam{ + Host: "Desktop", + Read: func() LiveRead { return LiveRead{Kind: LiveOn} }, + }, + }, true) + if got := a.trafficHint(); got != "Message Desktop" { + t.Fatalf("live conversation hint = %q, want %q", got, "Message Desktop") + } + if screen := plain(frame(a)); !strings.Contains(screen, "Message Desktop") { + t.Fatalf("empty composer on a live view did not draw Message Desktop:\n%s", screen) + } + + // Clearing the live seam via takeUp restores the team hint on the same window. + a.takeUp(Conversation{ + Agent: &fakeAgent{model: "m"}, + SessionFile: managerFile, + }, true) + if got := a.trafficHint(); got != teamHint { + t.Fatalf("clearing the live seam did not restore the team hint: got %q, want %q", got, teamHint) + } +} + +// V1/T6 (contract 3): the legend's host piece reads "on · live" while +// the live view is healthy (LiveOn) and "on " in every other state, while +// a conversation with no live seam keeps today's legend. +func TestTheLegendSaysTheChatIsLiveOnTheOtherComputer(t *testing.T) { + a := newTestApp(&fakeAgent{model: "m"}) + a.dismissWelcome() + if got := a.seamPieces(a.width).host; got != "" { + t.Fatalf("local conversation without a live seam had legend host %q", got) + } + + kind := LiveOn + a.takeUp(Conversation{ + Agent: &fakeAgent{model: "m"}, + Live: &LiveSeam{ + Host: "Desktop", + Read: func() LiveRead { return LiveRead{Kind: kind} }, + }, + }, true) + + if got := a.seamPieces(a.width).host; got != "on Desktop · live" { + t.Fatalf("healthy live view legend host = %q, want %q", got, "on Desktop · live") + } + if screen := plain(frame(a)); !strings.Contains(screen, "on Desktop · live") { + t.Fatalf("frame legend did not draw 'on Desktop · live':\n%s", screen) + } + + for _, other := range []LiveKind{LiveReconnecting, LiveWentOffline, LiveIdle, LiveRevoked, LiveBudget, LiveCopy} { + kind = other + if got := a.seamPieces(a.width).host; got != "on Desktop" { + t.Fatalf("live kind %v legend host = %q, want %q", other, got, "on Desktop") + } + screen := plain(frame(a)) + if !strings.Contains(screen, "on Desktop") || strings.Contains(screen, "on Desktop · live") { + t.Fatalf("live kind %v frame legend should say 'on Desktop' without '· live':\n%s", other, screen) + } + } +} + +// V1/T5 (contract 1): a live view keeps a.hosted() false and neutralizes the +// local-ownership machinery so recordMachines never prints a Superseded note +// and pressing Enter sends to the live agent instead of raising the Move card, +// while the identical setup with no live seam raises the Superseded note. +func TestTypingIntoALiveViewNeverRaisesTheMoveCardOrASupersededNote(t *testing.T) { + cellID := "0000000000000042" + sessionFile := filepath.Join(t.TempDir(), cellID, "session.jsonl") + remoteRow := chatlist.Row{ + Cell: cellID, + Title: "Parser work", + Device: "Desktop", + DeviceID: "dev-desktop", + Status: chatlist.Running, + } + + agent := &fakeAgent{model: "m"} + a := newTestApp(agent) + a.dismissWelcome() + a.machines = &flipping{status: chatlist.Running} + a.taker = &fakeTaker{} + a.takeUp(Conversation{ + Agent: agent, + SessionFile: sessionFile, + Live: &LiveSeam{ + Host: "Desktop", + Device: "dev-desktop", + Cell: cellID, + Row: remoteRow, + Read: func() LiveRead { return LiveRead{Kind: LiveOn} }, + }, + }, true) + + if a.hosted() { + t.Fatal("a live view inside a local window flipped a.hosted() true") + } + if a.watchesConversation() { + t.Fatal("a live view should not poll local conversation ownership") + } + + a.recordMachines(homeMachinesMsg{rows: []chatlist.Row{remoteRow}}) + if _, elsewhere := a.heldElsewhere(); elsewhere { + t.Fatal("heldElsewhere() reported true for a live view") + } + for _, e := range a.entries { + if e.kind == entryNote && strings.Contains(e.text, chatlist.Superseded("Desktop")) { + t.Fatalf("recordMachines printed a Superseded note on a live view: %q", e.text) + } + } + + typeText(t, a, "ship the fix") + drive(t, a, key("enter")) + if a.at(pageHome) { + t.Fatal("pressing Enter in a live view opened Home instead of sending") + } + if len(agent.sent) != 1 || agent.sent[0] != "ship the fix" { + t.Fatalf("pressing Enter in a live view sent %v, want [ship the fix]", agent.sent) + } + + // Absent path: the identical setup with no live seam raises the Superseded note. + localAgent := &fakeAgent{model: "m"} + local := newTestApp(localAgent) + local.dismissWelcome() + local.machines = &flipping{status: chatlist.Running} + local.taker = &fakeTaker{} + local.takeUp(Conversation{ + Agent: localAgent, + SessionFile: sessionFile, + }, true) + local.recordMachines(homeMachinesMsg{rows: []chatlist.Row{remoteRow}}) + if _, elsewhere := local.heldElsewhere(); !elsewhere { + t.Fatal("absent path: heldElsewhere() was false when Live was nil") + } + foundSuperseded := false + for _, e := range local.entries { + if e.kind == entryNote && strings.Contains(e.text, chatlist.Superseded("Desktop")) { + foundSuperseded = true + } + } + if !foundSuperseded { + t.Fatal("absent path: recordMachines with Live == nil did not print the Superseded note") + } +} + +// V6/T8 (contract 4 last clause and contract 5): when another computer holds +// the keyboard on a live view, the composer-position bar names who is typing +// without the word "take", and pressing Enter calls link.Take once. +func TestALiveWatcherNamesWhoTypesAndCanTakeTheKeyboard(t *testing.T) { + a := newTestApp(&fakeAgent{model: "m"}) + a.dismissWelcome() + taken := 0 + driving := Driving{Yours: false, Holder: "Desktop"} + a.takeUp(Conversation{ + Agent: &fakeAgent{model: "m"}, + Link: &LinkSeam{ + Driving: func() Driving { return driving }, + Take: func() error { + taken++ + driving = Driving{Yours: true} + return nil + }, + }, + Live: &LiveSeam{ + Host: "Desktop", + Read: func() LiveRead { return LiveRead{Kind: LiveOn} }, + }, + }, true) + + if !a.watching() { + t.Fatal("live view without the keyboard did not report a.watching() == true") + } + wantBar := chatlist.LiveTypingFrom("Desktop") + if strings.Contains(strings.ToLower(wantBar), "take") { + t.Fatalf("live watcher sentence %q contains the banned word 'take'", wantBar) + } + screen := plain(frame(a)) + if !strings.Contains(screen, wantBar) { + t.Fatalf("live watcher frame is missing %q:\n%s", wantBar, screen) + } + if strings.Contains(screen, watchKeysWord) { + t.Fatalf("live watcher bar drew the non-live right key hint %q:\n%s", watchKeysWord, screen) + } + + drive(t, a, key("enter")) + if taken != 1 { + t.Fatalf("pressing Enter on a live watcher called link.Take %d times, want 1", taken) + } + if a.watching() { + t.Fatal("live view still reported watching after taking the keyboard") + } +} + +// V11/T8 (contract 4 and contract 5): a watch-only live view shows its +// ReadOnly sentence in the composer's place, swallows typed characters without +// altering the draft, and pressing Enter calls neither Submit nor Take. +func TestAWatchOnlyLiveViewSaysWhyItCannotType(t *testing.T) { + agent := &fakeAgent{model: "m"} + a := newTestApp(agent) + a.width = 100 + a.title = "chat" + a.dismissWelcome() + taken := 0 + reason := chatlist.LiveWatchOnly("Desktop") + a.takeUp(Conversation{ + Agent: agent, + Link: &LinkSeam{ + Driving: func() Driving { + return Driving{Yours: false, Holder: "Desktop", ReadOnly: reason} + }, + Take: func() error { + taken++ + return nil + }, + }, + Live: &LiveSeam{ + Host: "Desktop", + Read: func() LiveRead { return LiveRead{Kind: LiveOn} }, + }, + }, true) + a.input.setText("kept draft") + + if !a.watching() { + t.Fatal("watch-only live view did not report a.watching() == true") + } + screen := plain(frame(a)) + if !strings.Contains(screen, reason) { + t.Fatalf("watch-only live view did not draw %q:\n%s", reason, screen) + } + if strings.Contains(screen, "kept draft") { + t.Fatalf("watch-only live view drew the hidden draft while the bar stood:\n%s", screen) + } + + drive(t, a, key("x"), key("y"), key("enter")) + if got := a.input.String(); got != "kept draft" { + t.Fatalf("typing while watch-only changed the draft to %q, want %q", got, "kept draft") + } + if len(agent.sent) != 0 { + t.Fatalf("pressing Enter while watch-only submitted %v", agent.sent) + } + if taken != 0 { + t.Fatalf("pressing Enter while watch-only called link.Take %d times, want 0", taken) + } +} + +// V7/T7 (contract 4, contract 5, contract 6): when a live link drops to +// LiveWentOffline, the bar says " went offline", the transcript entries +// stay on screen, and the half-typed draft is hidden and preserved until the +// link returns to LiveOn. +func TestADroppedLiveLinkSaysWentOfflineAndKeepsTheLastViewAndTheDraft(t *testing.T) { + agent := &fakeAgent{model: "m"} + a := newTestApp(agent) + a.dismissWelcome() + kind := LiveOn + a.takeUp(Conversation{ + Agent: agent, + Live: &LiveSeam{ + Host: "Desktop", + Read: func() LiveRead { return LiveRead{Kind: kind} }, + }, + }, true) + + a.entries = []entry{ + {kind: entryUser, text: "first line", turn: 1}, + {kind: entryAssistant, text: "second line", turn: 1}, + {kind: entryUser, text: "third line", turn: 2}, + } + a.input.setText("half-typed words") + a.touch() + + kind = LiveWentOffline + a.touch() + if !a.watching() { + t.Fatal("offline live view did not report a.watching() == true") + } + screen := plain(frame(a)) + if !strings.Contains(screen, "Desktop went offline") { + t.Fatalf("offline live view did not draw 'Desktop went offline':\n%s", screen) + } + for _, want := range []string{"first line", "second line", "third line"} { + if !strings.Contains(screen, want) { + t.Fatalf("offline live view lost transcript entry %q:\n%s", want, screen) + } + } + if strings.Contains(screen, "half-typed words") { + t.Fatalf("offline live view drew the composer draft while the offline bar stood:\n%s", screen) + } + + drive(t, a, key("z"), key("enter")) + if len(agent.sent) != 0 { + t.Fatalf("Enter while offline sent %v", agent.sent) + } + if len(a.entries) != 3 { + t.Fatalf("offline live view entries count changed to %d, want 3", len(a.entries)) + } + + kind = LiveOn + a.touch() + if a.watching() { + t.Fatal("restored live view still reported a.watching() == true") + } + restored := plain(frame(a)) + if strings.Contains(restored, "Desktop went offline") { + t.Fatalf("restored live view kept the offline bar:\n%s", restored) + } + if !strings.Contains(restored, "half-typed words") { + t.Fatalf("restored live view did not bring back the half-typed draft:\n%s", restored) + } + if got := a.input.String(); got != "half-typed words" { + t.Fatalf("draft text = %q, want %q", got, "half-typed words") + } +} + +// V24/T7 (contract 4 and contract 5): an idle-detached live view shows +// chatlist.LiveIdle in the composer position, swallows character keys without +// reconnecting, and calls Reconnect once when Enter is pressed. +func TestAnIdleLiveViewSaysSoAndEnterReconnects(t *testing.T) { + agent := &fakeAgent{model: "m"} + a := newTestApp(agent) + a.dismissWelcome() + reconnected := 0 + a.takeUp(Conversation{ + Agent: agent, + Live: &LiveSeam{ + Host: "Desktop", + Read: func() LiveRead { return LiveRead{Kind: LiveIdle} }, + Reconnect: func() { + reconnected++ + }, + }, + }, true) + a.input.setText("unsent draft") + + if !a.watching() { + t.Fatal("idle live view did not report a.watching() == true") + } + screen := plain(frame(a)) + if !strings.Contains(screen, chatlist.LiveIdle) { + t.Fatalf("idle live view did not draw %q:\n%s", chatlist.LiveIdle, screen) + } + + drive(t, a, key("a")) + if reconnected != 0 { + t.Fatalf("character key on an idle live view called Reconnect %d times, want 0", reconnected) + } + if got := a.input.String(); got != "unsent draft" { + t.Fatalf("character key on an idle live view altered the draft to %q", got) + } + + drive(t, a, key("enter")) + if reconnected != 1 { + t.Fatalf("pressing Enter on an idle live view called Reconnect %d times, want 1", reconnected) + } + if len(agent.sent) != 0 { + t.Fatalf("pressing Enter on an idle live view submitted %v", agent.sent) + } +} + +// V24/T12 (contract 8): a keypress, a scroll (mouse wheel and page key) and a +// send each call LiveSeam.Touch on a live front, an active turn touches at most +// once per second on the app's clock, and an idle view generates no calls. +func TestAKeypressAScrollAndASendTouchTheLiveLinkAndAnIdleViewDoesNot(t *testing.T) { + agent := &fakeAgent{model: "m"} + a := newTestApp(agent) + a.dismissWelcome() + now := time.Date(2026, time.November, 23, 14, 0, 0, 0, time.Local) + a.clock = func() time.Time { return now } + + touches := 0 + a.takeUp(Conversation{ + Agent: agent, + Live: &LiveSeam{ + Host: "Desktop", + Read: func() LiveRead { return LiveRead{Kind: LiveOn} }, + Touch: func() { touches++ }, + }, + }, true) + + // An idle view generates no Touch calls across frames or elapsed time. + _ = frame(a) + now = now.Add(5 * time.Minute) + _ = frame(a) + if touches != 0 { + t.Fatalf("idle live view called Touch %d times, want 0", touches) + } + + // A keypress calls Touch. + drive(t, a, key("h")) + if touches != 1 { + t.Fatalf("after a keypress Touch count = %d, want 1", touches) + } + + // A mouse wheel scroll calls Touch. + drive(t, a, tea.MouseWheelMsg{Button: tea.MouseWheelUp}) + if touches != 2 { + t.Fatalf("after a mouse wheel scroll Touch count = %d, want 2", touches) + } + + // A page-key scroll calls Touch. + drive(t, a, key("pgdown")) + if touches != 3 { + t.Fatalf("after a page-key scroll Touch count = %d, want 3", touches) + } + + // A send calls Touch. + drive(t, a, key("enter")) + if len(agent.sent) != 1 || agent.sent[0] != "h" { + t.Fatalf("send did not reach the agent: %v", agent.sent) + } + if touches != 4 { + t.Fatalf("after a send Touch count = %d, want 4", touches) + } + + // While a turn is running, events within the same second do not call Touch + // again, and advancing the clock by a full second allows one more call. + stream := make(chan session.Event, 4) + a.stream = stream + a.state = stateWorking + now = now.Add(200 * time.Millisecond) + a.apply(session.Event{Kind: session.EventTextDelta, Text: "part one"}) + now = now.Add(400 * time.Millisecond) + a.apply(session.Event{Kind: session.EventTextDelta, Text: " part two"}) + if touches != 4 { + t.Fatalf("running turn within 1s called Touch %d times, want 4", touches) + } + now = now.Add(500 * time.Millisecond) + a.apply(session.Event{Kind: session.EventTextDelta, Text: " part three"}) + if touches != 5 { + t.Fatalf("running turn after 1.1s called Touch %d times, want 5", touches) + } + + // Once the turn ends and the view is idle again, advancing the clock produces no calls. + a.stream = nil + a.state = stateIdle + now = now.Add(10 * time.Second) + a.paint() + if touches != 5 { + t.Fatalf("idle view after turn completion called Touch %d times, want 5", touches) + } +} + +// T3/T7 (contract 9): closing LiveSeam.Changed wakes the update loop to repaint +// at once and re-arms the wait for the next change, while a message from a +// stale conversation generation is dropped without re-arming. +func TestALiveStateChangeRepaintsAtOnce(t *testing.T) { + a := newTestApp(&fakeAgent{model: "m"}) + a.dismissWelcome() + + asked := 0 + first := make(chan struct{}) + close(first) + second := make(chan struct{}) + kind := LiveOn + a.takeUp(Conversation{ + Agent: &fakeAgent{model: "m"}, + Live: &LiveSeam{ + Host: "Desktop", + Read: func() LiveRead { return LiveRead{Kind: kind} }, + Changed: func() <-chan struct{} { + asked++ + if asked == 1 { + return first + } + return second + }, + }, + }, true) + + armed := a.armLive() + if armed == nil { + t.Fatal("armLive returned nil when LiveSeam.Changed was non-nil") + } + kind = LiveWentOffline + a.dirty = false + drive(t, a, runCmd(armed)...) + if asked < 2 { + t.Fatalf("live state wait did not re-arm after Changed closed: asked %d times, want at least 2", asked) + } + if !a.dirty { + t.Fatal("closing Changed did not mark the surface dirty for repaint") + } + if screen := plain(frame(a)); !strings.Contains(screen, "Desktop went offline") { + t.Fatalf("repaint after Changed did not draw the new state:\n%s", screen) + } + + // A stale generation is dropped and does not call Changed again. + before := asked + a.dirty = false + if cmd := a.liveMoved(liveChangedMsg{gen: a.convGen - 1}); cmd != nil { + t.Fatal("stale liveChangedMsg returned a non-nil command") + } + if asked != before || a.dirty { + t.Fatalf("stale liveChangedMsg was not dropped: asked=%d (was %d) dirty=%v", asked, before, a.dirty) + } +} + +// T9 (contract 7): /status and /status --json include the road row only for a +// live front whose Kind is not LiveCopy and whose Road is non-empty. +func TestStatusShowsTheRoadOfALiveConversationOnly(t *testing.T) { + a := newTestApp(&fakeAgent{model: "m"}) + if strings.Contains(a.statusText(), "road") || strings.Contains(a.statusJSON(), `"road"`) { + t.Fatalf("non-live conversation included a road row in /status:\n%s\n%s", a.statusText(), a.statusJSON()) + } + + kind := LiveOn + road := "relay" + a.takeUp(Conversation{ + Agent: &fakeAgent{model: "m"}, + Live: &LiveSeam{ + Host: "Desktop", + Road: road, + Read: func() LiveRead { return LiveRead{Kind: kind} }, + }, + }, true) + + if got := a.statusText(); !strings.Contains(got, "road") || !strings.Contains(got, "live · relay") { + t.Fatalf("/status text on a live view is missing 'road' / 'live · relay':\n%s", got) + } + if got := a.statusJSON(); !strings.Contains(got, `"road":"live · relay"`) { + t.Fatalf("/status JSON on a live view is missing \"road\":\"live · relay\":\n%s", got) + } + + // LiveCopy omits the road row because no live connection is carrying traffic. + kind = LiveCopy + if strings.Contains(a.statusText(), "live · relay") || strings.Contains(a.statusJSON(), `"road"`) { + t.Fatalf("LiveCopy conversation still showed a road row:\n%s\n%s", a.statusText(), a.statusJSON()) + } + + // An empty Road omits the road row under the emptiness law. + kind = LiveOn + a.liveFront().Road = "" + if strings.Contains(a.statusText(), "road") || strings.Contains(a.statusJSON(), `"road"`) { + t.Fatalf("live view with empty Road showed a road row:\n%s\n%s", a.statusText(), a.statusJSON()) + } +} + +// V30, V41: /status says which road the bytes travel from what the door reads +// on every draw, so the same live view says `live · relay` and then `live · +// direct` and back as the road changes, and the seam's own Road is only what the +// first paint knows. +func TestStatusShowsLiveDirectAndLiveRelayFromTheRoadTheLinkReports(t *testing.T) { + a := newTestApp(&fakeAgent{model: "m"}) + road := "" + a.takeUp(Conversation{ + Agent: &fakeAgent{model: "m"}, + Live: &LiveSeam{ + Host: "Desktop", + Road: "relay", + Read: func() LiveRead { return LiveRead{Kind: LiveOn, Road: road} }, + }, + }, true) + + for _, step := range []struct{ said, want string }{ + {"", "live · relay"}, // the door has not said yet: the first paint's word + {"direct", "live · direct"}, + {"relay", "live · relay"}, + {"direct", "live · direct"}, + } { + road = step.said + text, json := a.statusText(), a.statusJSON() + if !strings.Contains(text, step.want) || !strings.Contains(json, `"road":"`+step.want+`"`) { + t.Fatalf("with the door saying %q, /status should say %q:\n%s\n%s", step.said, step.want, text, json) + } + other := "live · relay" + if step.want == other { + other = "live · direct" + } + if strings.Contains(text, other) || strings.Contains(json, other) { + t.Fatalf("with the door saying %q, /status also says %q:\n%s\n%s", step.said, other, text, json) + } + } +} + +// V30: a road swap redraws the view and says nothing about it: the door's change +// signal is what asks for the redraw, and no banner, notice or note is added. +func TestARoadFlipRedrawsWithoutABanner(t *testing.T) { + a := newTestApp(&fakeAgent{model: "m"}) + road := "relay" + changed := make(chan struct{}) + a.takeUp(Conversation{ + Agent: &fakeAgent{model: "m"}, + Live: &LiveSeam{ + Host: "Desktop", + Road: "relay", + Read: func() LiveRead { return LiveRead{Kind: LiveOn, Road: road} }, + Changed: func() <-chan struct{} { return changed }, + }, + }, true) + before := a.statusText() + barBefore, onBefore := a.liveBar() + + road = "direct" + close(changed) + if cmd := a.liveMoved(liveChangedMsg{gen: a.convGen}); cmd == nil { + t.Fatalf("a road flip did not ask to be watched again") + } + after := a.statusText() + if after == before || !strings.Contains(after, "live · direct") { + t.Fatalf("/status did not follow the road flip:\nbefore:\n%s\nafter:\n%s", before, after) + } + if barAfter, onAfter := a.liveBar(); barAfter != barBefore || onAfter != onBefore { + t.Fatalf("a road flip changed the bar above the composer: %q -> %q", barBefore, barAfter) + } +} + +// V27 (contract 4 and contract 5): an offline copy (LiveCopy) shows the last +// seen bar formatted by chatlist.LiveSeenAt, swallows typed keys, and sends +// nothing when Enter is pressed while keeping existing words in the box. +func TestAnOfflineCopyShowsTheLastSeenBarAndSendsNothing(t *testing.T) { + agent := &fakeAgent{model: "m"} + a := newTestApp(agent) + a.dismissWelcome() + now := time.Date(2026, time.November, 23, 16, 30, 0, 0, time.Local) + seen := time.Date(2026, time.November, 23, 14, 2, 0, 0, time.Local) + a.clock = func() time.Time { return now } + + taken := 0 + a.takeUp(Conversation{ + Agent: agent, + Link: &LinkSeam{ + Take: func() error { + taken++ + return nil + }, + }, + Live: &LiveSeam{ + Host: "Desktop", + Road: "relay", + Read: func() LiveRead { return LiveRead{Kind: LiveCopy, SeenAt: seen} }, + }, + }, true) + a.input.setText("words already here") + + if !a.watching() { + t.Fatal("offline copy did not report a.watching() == true") + } + wantBar := "Desktop offline · last seen 14:02" + screen := plain(frame(a)) + if !strings.Contains(screen, wantBar) { + t.Fatalf("offline copy did not draw %q:\n%s", wantBar, screen) + } + + drive(t, a, key("q"), key("enter")) + if len(agent.sent) != 0 { + t.Fatalf("pressing Enter on an offline copy submitted %v", agent.sent) + } + if taken != 0 { + t.Fatalf("pressing Enter on an offline copy called link.Take %d times, want 0", taken) + } + if got := a.input.String(); got != "words already here" { + t.Fatalf("offline copy draft changed to %q, want %q", got, "words already here") + } + + // Verify LiveSeenAt across calendar days and zero time, and LiveNotSentOffline. + older := time.Date(2026, time.January, 2, 14, 2, 0, 0, time.Local) + if got := chatlist.LiveSeenAt(older, now); got != "2 Jan 14:02" { + t.Fatalf("LiveSeenAt across days = %q, want %q", got, "2 Jan 14:02") + } + if got := chatlist.LiveSeenAt(time.Time{}, now); got != "" { + t.Fatalf("LiveSeenAt on zero time = %q, want empty", got) + } + if got := chatlist.LiveNotSentOffline("Desktop"); got != "not sent. Desktop is offline; your words are still in the box" { + t.Fatalf("LiveNotSentOffline = %q", got) + } +} + +// V14 (contract 10): with Options.OpenLive == nil and Conversation.Live == nil, +// every live-view behaviour is absent and the surface draws and acts as before. +func TestWithNoLiveSeamTheSurfaceDrawsAndActsAsBefore(t *testing.T) { + a := newTestApp(&fakeAgent{model: "m"}) + a.dismissWelcome() + + if a.openLive != nil { + t.Fatal("default Options left a.openLive non-nil") + } + if a.liveFront() != nil { + t.Fatalf("liveFront() = %+v, want nil", a.liveFront()) + } + if got := a.trafficHint(); got != "" { + t.Fatalf("trafficHint() with no live seam = %q, want empty", got) + } + if got := a.seamPieces(a.width).host; got != "" { + t.Fatalf("seamPieces.host with no live seam = %q, want empty", got) + } + if a.watching() { + t.Fatal("watching() was true with no live seam and no driving seam") + } + if a.armLive() != nil { + t.Fatal("armLive() armed a command with no live seam") + } + if strings.Contains(a.statusText(), "road") || strings.Contains(a.statusJSON(), `"road"`) { + t.Fatalf("/status with no live seam contained a road row:\n%s", a.statusText()) + } +} diff --git a/internal/tui3/live_workspace_test.go b/internal/tui3/live_workspace_test.go new file mode 100644 index 0000000000..a7d4cefe9b --- /dev/null +++ b/internal/tui3/live_workspace_test.go @@ -0,0 +1,152 @@ +package tui3 + +import ( + "context" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/chatlist" +) + +// A LIVE VIEW'S FOLDER BELONGS TO THE OTHER COMPUTER. The folder a chat runs in +// is a path on the computer that runs it, and Home's project (the default folder +// for the next conversation, the project the box names, the row the projects panel +// draws first) is a fact about THIS computer. The 2026-11-24 hand test opened chats +// that ran in /tmp/h4pc-ws on a PC from a Mac that has no such folder, and Home then +// said `project: /tmp/h4pc-ws`. These tests state what Home's project must be, from +// the person's side, around a live view and around a local conversation. + +const otherComputersFolder = "/tmp/h4pc-ws" + +// homeProjectRead is everything Home says about this computer's project, read +// with the cursor on no row so that the reading is the window's own and not the +// row the cursor happens to rest on. +type homeProjectRead struct { + own, scope, launch string + destinations []string +} + +func readHomeProject(a *app) homeProjectRead { + cursor := a.home.cursor + a.home.cursor = -1 + read := homeProjectRead{ + own: a.ownWorkspace(), + scope: a.scopeWorkspace(), + launch: a.home.launch, + destinations: a.targetDestinations(), + } + a.home.cursor = cursor + return read +} + +func (r homeProjectRead) equal(o homeProjectRead) bool { + return r.own == o.own && r.scope == o.scope && r.launch == o.launch && slices.Equal(r.destinations, o.destinations) +} + +// projectRig is a window on this computer's own folder with one chat held by an +// online computer of the person's own, whose live view reports that other +// computer's folder as its workspace, and a conversation of this computer's own +// behind it that closing the live view returns to. +func projectRig(t *testing.T) (a *app, own string) { + t.Helper() + a, _ = liveHomeRig(t, "dev_tower") + own = filepath.Join(t.TempDir(), "parser") + a.workspace = own + a.file = filepath.Join(t.TempDir(), "cellA", "session.jsonl") + wireFakeOpenLive(t, a, nil) + inner := a.openLive + a.openLive = func(ctx context.Context, row chatlist.Row) (Conversation, error) { + conv, err := inner(ctx, row) + conv.Workspace = otherComputersFolder + return conv, err + } + drain(t, a, a.openHome()) + return a, own +} + +// C-a: after opening a live view of another computer's chat, going back to Home +// and closing the live view, Home's project is what it was before. The live +// view itself is about the other computer's folder, and that does not leak. +func TestAnOpenLiveViewLeavesHomesProjectAlone(t *testing.T) { + a, own := projectRig(t) + before := readHomeProject(a) + if before.own != own || before.launch != own { + t.Fatalf("the rig does not start in its own folder: %+v, want %s", before, own) + } + + standOn(t, a, "c1") + if a.liveFront() == nil || a.at(pageHome) { + t.Fatalf("the Enter did not end on a live view: live=%v home=%v", a.liveFront(), a.at(pageHome)) + } + if a.workspace != otherComputersFolder { + t.Fatalf("the live conversation does not carry the other computer's folder (%q), so this test proves nothing", a.workspace) + } + + drain(t, a, a.openHome()) + during := readHomeProject(a) + if !during.equal(before) { + t.Fatalf("Home's project moved while a live view is in front:\nbefore %+v\nduring %+v", before, during) + } + if frame := homeText(a); strings.Contains(frame, "h4pc-ws") { + t.Fatalf("Home draws the other computer's folder:\n%s", frame) + } + if where := a.targetProject(); strings.Contains(where, "h4pc-ws") { + t.Fatalf("the project the box names is the other computer's folder: %q", where) + } + + // Closing the live view returns to the conversation behind it. + a.closeHome() + cmd, closed := a.closeFront() + if !closed { + t.Fatal("the live view did not close: nothing was behind it, so the rig does not test the close") + } + drain(t, a, cmd) + if a.liveFront() != nil { + t.Fatal("a live view is still in front after it was closed") + } + drain(t, a, a.openHome()) + if after := readHomeProject(a); !after.equal(before) { + t.Fatalf("Home's project is not what it was before the live view:\nbefore %+v\nafter %+v", before, after) + } +} + +// C-a, the pin: a folder the person chose with alt+p stays chosen across a live +// view, as a pin always does. +func TestAnOpenLiveViewDoesNotMoveAPinnedProject(t *testing.T) { + a, _ := projectRig(t) + pinned := filepath.Join(t.TempDir(), "elsewhere") + a.target.where = pinned + + standOn(t, a, "c1") + drain(t, a, a.openHome()) + if got := a.targetWhere(); got != pinned { + t.Fatalf("targetWhere = %q after a live view, want the pin %q", got, pinned) + } +} + +// C-b: a local conversation in another folder moves Home's project exactly as it +// always did. The window's folder is the last conversation's, and Home follows it. +func TestALocalConversationInAnotherFolderStillMovesHomesProject(t *testing.T) { + a, own := projectRig(t) + other := filepath.Join(t.TempDir(), "other") + + a.takeUp(Conversation{ + Agent: &fakeAgent{model: "m"}, + SessionFile: filepath.Join(t.TempDir(), "cellB", "session.jsonl"), + Workspace: other, + }, true) + drain(t, a, a.openHome()) + + read := readHomeProject(a) + if read.own != other || read.scope != other || read.launch != other || a.workspace != other { + t.Fatalf("Home did not follow a local conversation to %s: workspace=%q %+v", other, a.workspace, read) + } + if read.own == own { + t.Fatal("Home's project did not move") + } + if !slices.Contains(read.destinations, other) { + t.Fatalf("the projects the draft can walk to do not include the new folder: %v", read.destinations) + } +} diff --git a/internal/tui3/machinepoll.go b/internal/tui3/machinepoll.go index 33c6bd3765..5582cfeb48 100644 --- a/internal/tui3/machinepoll.go +++ b/internal/tui3/machinepoll.go @@ -1,6 +1,7 @@ package tui3 import ( + "slices" "time" tea "charm.land/bubbletea/v2" @@ -110,7 +111,7 @@ func (a *app) pollMachines(now time.Time) tea.Cmd { // takes its chat, even while home is closed. A window without a sync source // or without a conversation has no directory work to do. func (a *app) watchesConversation() bool { - return a.machines != nil && a.file != "" && !a.hosted() + return a.machines != nil && a.file != "" && !a.hosted() && a.liveFront() == nil } // hurryMachines asks now, for a person who has just arrived. @@ -126,6 +127,32 @@ func (a *app) fileMachines(msg homeMachinesMsg) { changed := msg.err == nil && !chatlist.Same(a.machineRead.rows, msg.rows) a.machinePoll.landed(now, changed, a.socketUp() && msg.err == nil) if msg.err == nil { - a.machineRead = machineReading{rows: msg.rows, at: now, version: msg.version, sendHolds: a.machineRead.sendHolds, computerRemoved: a.machineRead.computerRemoved, host: a.machineRead.host, checking: a.machineRead.checking} + rows := a.withHolderSeen(msg.rows) + a.machineRead = machineReading{rows: rows, at: now, version: msg.version, sendHolds: a.machineRead.sendHolds, computerRemoved: a.machineRead.computerRemoved, host: a.machineRead.host, checking: a.machineRead.checking} } } + +func (a *app) holderSeenFor(deviceID string) time.Time { + if deviceID == "" { + return time.Time{} + } + for _, d := range a.devRow.devices { + if d.ID == deviceID && !d.LastSeen.IsZero() { + return d.LastSeen + } + } + return time.Time{} +} + +func (a *app) withHolderSeen(rows []chatlist.Row) []chatlist.Row { + if len(rows) == 0 || len(a.devRow.devices) == 0 { + return rows + } + out := slices.Clone(rows) + for i := range out { + if out[i].HolderSeen.IsZero() { + out[i].HolderSeen = a.holderSeenFor(out[i].DeviceID) + } + } + return out +} diff --git a/internal/tui3/manual_devices_test.go b/internal/tui3/manual_devices_test.go index de0494f1ae..efd4679a94 100644 --- a/internal/tui3/manual_devices_test.go +++ b/internal/tui3/manual_devices_test.go @@ -10,6 +10,7 @@ import ( "github.com/Agent-Field/codeaf/internal/chatlist" "github.com/Agent-Field/codeaf/internal/manual" + "github.com/Agent-Field/codeaf/internal/pair" ) // THE SENTENCES OF THE DEVICE SCREENS ARE IN THEIR PAGES, WORD FOR WORD. A @@ -22,15 +23,18 @@ func TestEverySentenceOfTheDeviceScreensIsOnItsPage(t *testing.T) { "add-or-remove-a-computer": { addMachineHeading, addMachinePitch, addMachineStepRun, addMachineStepPut, addMachineShow, approveAsk, fmt.Sprintf(approveCheckWord, "4821"), approveKeys, approveGone, - fmt.Sprintf(approveDenied, "laptop"), fmt.Sprintf(joinedFleetWord, "laptop"), + fmt.Sprintf(approveDenied, "laptop"), pair.ApprovedLine("laptop"), strings.Join([]string{devicesMoveKey, devicesNameKey, devicesGoneKey, devicesCloseKey}, " · "), fmt.Sprintf(devicesRemoveAsk, "desk"), fmt.Sprintf(devicesRevoked, "desk"), "seen 3h ago", "offline", approveWorking, approveDeclining, approveSlow, approveUnsure, ErrAlreadyPaired.Error(), deviceBring, deviceNothing, devicePickAsk, devicePickLeav, chatlist.Device{Name: "desk"}.Mark(false, tokens.Plain.Glyph(tokens.GQueued)), chatlist.RemovedChat, + devicesWatchKey, devicesTypeKey, devicesAccessBoth, devicesAccessWatch, devicesAccessNone, devicesTypeAskFor("desk"), + devicesWatchOnFor("desk"), devicesWatchOffFor("desk"), devicesTypeOnFor("desk"), devicesTypeOffFor("desk"), devicesPermitNoSetter, + strings.Join([]string{devicesMoveKey, devicesNameKey, devicesGoneKey, devicesWatchKey, devicesTypeKey, devicesCloseKey}, " · "), }, "naming-a-device": {devicesNameKeys, devicesNameAsk + "atlas▏", devicesNameOwn}, "continuing-a-chat-on-another-computer": { chatlist.SyncPaused, chatlist.SyncRestored, - continueAsk, continueStay, continueRetry, continueAlreadyRunning, continuing, continueFails, continueCheckFails, continueStoreBusy, continueUnreachable, lostRaceWord, chatlist.Unreachable, + moveAsk, moveStay, moveRetry, moveAlreadyRunning, movingHere, moveFails, moveCheckFails, moveStoreBusy, moveUnreachable, lostRaceWord, chatlist.Unreachable, fmt.Sprintf(resumeAskFormat, "tower"), resumeYes, resumeNo, chatlist.Moved("tower", 3200e6, true), chatlist.Moved("", 3200e6, false), chatlist.ArrivedHead("tower"), chatlist.OfferSetUp, chatlist.OfferNotNow, @@ -52,14 +56,26 @@ func TestEverySentenceOfTheDeviceScreensIsOnItsPage(t *testing.T) { } } -// The person-facing words keep the vocabulary law: the two pages never speak -// of the machinery behind the devices. -var banned = regexp.MustCompile(`\b(relay|node|lease|manifest|takeover|take over)\b`) +// The person-facing words keep the vocabulary law: the pages never speak of the +// machinery behind the devices. +// +// "relay" IS NOT ON THIS LIST ANY MORE. Until 2026-11-23 the pages called the +// server "the sync service" and kept the word relay out. The server is "the +// relay" in every sentence a person reads now, the refusals these pages quote +// verbatim (TestEverySentenceOfTheDeviceScreensIsOnItsPage) say it, and what the +// word may name is fenced by internal/wordlaw instead: the server and its +// storage switch, never a feature or an act. +var banned = regexp.MustCompile(`\b(node|lease|manifest|takeover|take over)\b`) + +// oldNamesHeading is the one heading that spells the old names of Move here, +// "take over" among them, so a person who asks in those words reaches the page. +// It is the only place the pages may say them. +const oldNamesHeading = `## Move here: also called "continue here", "take over" or "continue on this machine"` func TestTheDevicePagesKeepTheVocabularyLaw(t *testing.T) { for _, name := range []string{"add-or-remove-a-computer", "continuing-a-chat-on-another-computer", "naming-a-device"} { page, _ := manual.Chat().Page(name) - if word := banned.FindString(strings.ToLower(page)); word != "" { + if word := banned.FindString(strings.ReplaceAll(strings.ToLower(page), strings.ToLower(oldNamesHeading), "")); word != "" { t.Errorf("the page %s uses %q", name, word) } } diff --git a/internal/tui3/manual_live_test.go b/internal/tui3/manual_live_test.go new file mode 100644 index 0000000000..cbbdc437a0 --- /dev/null +++ b/internal/tui3/manual_live_test.go @@ -0,0 +1,45 @@ +package tui3 + +import ( + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/chatlist" + "github.com/Agent-Field/codeaf/internal/manual" +) + +// V12/V13 (Part 5): every person-facing sentence that the terminal surface +// spells for a live view, the device watch/type switches, and the one-time +// Home question appears verbatim on the remote-control manual page. +func TestEverySentenceOfALiveViewTheTerminalSpellsIsOnTheRemoteControlPage(t *testing.T) { + page, ok := manual.Chat().Page("remote-control") + if !ok { + t.Fatal("the page remote-control is not in the chat manual corpus") + } + sentences := []string{ + liveMessageHint("tower"), + liveLegendHost("tower", true), + devicesWatchKey, + devicesTypeKey, + devicesAccessBoth, + devicesAccessWatch, + devicesAccessNone, + devicesTypeAskFor("tower"), + devicesWatchOnFor("tower"), + devicesWatchOffFor("tower"), + devicesTypeOnFor("tower"), + devicesTypeOffFor("tower"), + permitAskHead, + permitAskReason([]string{"tower"}), + permitAskOptionType, + permitAskOptionKeep, + permitAskOptionPick, + chatlist.LiveRoad("direct"), + chatlist.LiveRoad("relay"), + } + for _, sentence := range sentences { + if !strings.Contains(page, sentence) { + t.Errorf("the page remote-control does not say %q - add it to internal/manual/chat/remote-control.md", sentence) + } + } +} diff --git a/internal/tui3/ownership_deadline_test.go b/internal/tui3/ownership_deadline_test.go index f6dca4d5d5..54e8ff9bf1 100644 --- a/internal/tui3/ownership_deadline_test.go +++ b/internal/tui3/ownership_deadline_test.go @@ -23,7 +23,7 @@ func (deadlineChatListing) Rows(context.Context) ([]chatlist.Row, error) { func TestHomeOwnershipDeadlineDoesNotClaimTheNetworkIsUnreachable(t *testing.T) { a := machinesHome(t, deadlineChatListing{}, 200) frame := homeText(a) - if !strings.Contains(frame, "sync.example did not answer in 25s; still trying") || strings.Contains(frame, "the sync service is not answering") { + if !strings.Contains(frame, "sync.example did not answer in 25s; still trying") || strings.Contains(frame, "the relay is not answering") { t.Fatalf("ownership read deadline was misreported:\n%s", frame) } } diff --git a/internal/tui3/pages.go b/internal/tui3/pages.go index 9718d32a54..79b1c41166 100644 --- a/internal/tui3/pages.go +++ b/internal/tui3/pages.go @@ -1472,6 +1472,20 @@ func (a *app) scopeWorkspace() string { } } } + return a.ownWorkspace() +} + +// ownWorkspace is the folder on THIS computer that Home starts things in when +// nothing points elsewhere: this window's workspace, and never the folder of a +// live view in front, which is a path on the computer that runs that chat and +// may not exist here. A new conversation started from Home in a folder this +// computer does not have is the failure this prevents, and so is a project row +// for a folder nobody here can open. For a local conversation in front it is +// exactly [app.workspace]. +func (a *app) ownWorkspace() string { + if a.liveView != nil { + return strings.TrimSpace(a.workspaceBeforeLive) + } return strings.TrimSpace(a.workspace) } diff --git a/internal/tui3/pair.go b/internal/tui3/pair.go index 567815b84a..2f8481e268 100644 --- a/internal/tui3/pair.go +++ b/internal/tui3/pair.go @@ -276,6 +276,7 @@ func (p *pairPanel) rows(width int, now time.Time, pal palette) []string { if p.ask.raw != "" { say(p.ask.raw, pal.ink) } else { + say(pair.PairedControlLine(p.ask.label), pal.ink) say(pair.AskChatsLine(p.ask.label, p.ask.words), pal.ink) } } diff --git a/internal/tui3/pair_test.go b/internal/tui3/pair_test.go index 256a8ba422..df0a450f16 100644 --- a/internal/tui3/pair_test.go +++ b/internal/tui3/pair_test.go @@ -149,6 +149,27 @@ func TestPairWithNoDoorSaysOneSentence(t *testing.T) { } } +func TestPairCardSaysThePairedDeviceCanControlChats(t *testing.T) { + door := &fakePairing{offer: func(ctx context.Context, ui pair.OfferUI) (string, error) { + showsCode(t, ui) + if !ui.Ask(ctx, "laptop", "amber cedar moon") { + return "", pair.ErrRefused + } + return "laptop", nil + }} + a := pairApp(t, door, 120) + r := newPairRig(t, a) + r.slash("/pair") + r.until("the question", func() bool { return a.pair.ask != nil }) + asked := plain(frame(a)) + want := pair.PairedControlLine("laptop") + if !strings.Contains(asked, want) { + t.Fatalf("pair card lacks %q:\n%s", want, asked) + } + r.press("n") + r.until("done", func() bool { return a.pair.done }) +} + func TestPairShareShowsTheCodeThenAsksThenPairs(t *testing.T) { release := make(chan struct{}) answered := make(chan bool, 1) @@ -175,7 +196,7 @@ func TestPairShareShowsTheCodeThenAsksThenPairs(t *testing.T) { close(release) r.until("the question", func() bool { return a.pair.ask != nil }) asked := plain(frame(a)) - for _, want := range []string{pair.AskChatsLine("laptop", "amber cedar moon")} { + for _, want := range []string{pair.PairedControlLine("laptop"), pair.AskChatsLine("laptop", "amber cedar moon")} { if !strings.Contains(asked, want) { t.Fatalf("the panel lacks %q:\n%s", want, asked) } @@ -192,7 +213,7 @@ func TestPairShareShowsTheCodeThenAsksThenPairs(t *testing.T) { if yes := <-answered; !yes { t.Fatal("y was heard as no") } - if got := plain(frame(a)); !strings.Contains(got, pair.PairedChatsLine("laptop")) { + if got := plain(frame(a)); !strings.Contains(strings.Join(strings.Fields(got), " "), pair.PairedChatsLine("laptop")) { t.Fatalf("no result line:\n%s", got) } } diff --git a/internal/tui3/question_reason_wrap_test.go b/internal/tui3/question_reason_wrap_test.go index 9624307998..e101a41af3 100644 --- a/internal/tui3/question_reason_wrap_test.go +++ b/internal/tui3/question_reason_wrap_test.go @@ -98,7 +98,7 @@ func TestARunawaySentenceIsStillBoundedAndSaysItWasCut(t *testing.T) { if !regexp.MustCompile(`(this|sentence|never|ends|and)` + glyphMore).MatchString(text) { t.Errorf("a sentence cut at the bound carries no sign of it on its last row:\n%s", text) } - if !strings.Contains(text, continueStay) { + if !strings.Contains(text, moveStay) { t.Errorf("the answers were pushed off the card by the sentence:\n%s", text) } } diff --git a/internal/tui3/relay_manual_test.go b/internal/tui3/relay_manual_test.go index 11d17d7b7b..9e1fbf9260 100644 --- a/internal/tui3/relay_manual_test.go +++ b/internal/tui3/relay_manual_test.go @@ -13,8 +13,8 @@ func TestRelayWaitAndChoiceWordsAreInTheChatManual(t *testing.T) { t.Fatal("missing continue manual") } for _, words := range []string{ - "continuing next; is still on its way here", - " picked this chat up again; press enter to continue it here", + "moving next; is still on its way here", + " picked this chat up again; press enter to move it here", "waiting for ; still checking", " did not answer in " + machinesAskTimeout.String() + "; still trying", " is unreachable; still trying", diff --git a/internal/tui3/relay_surface_test.go b/internal/tui3/relay_surface_test.go index cc015f14fe..b54cff1cda 100644 --- a/internal/tui3/relay_surface_test.go +++ b/internal/tui3/relay_surface_test.go @@ -128,7 +128,7 @@ func TestResumeNeverOffersThisComputersOwnDevice(t *testing.T) { keepSurfaceWorkersInTest(t, a) a.deviceID = "self" a.Update(homeMachinesMsg{rows: []chatlist.Row{{Cell: "chat", DeviceID: "self", Device: "laptop", Status: status}}}) - if got := leftOffFrame(a); strings.Contains(got, "Continue laptop's latest chat here?") { + if got := leftOffFrame(a); strings.Contains(got, "Move laptop's latest chat here?") { t.Fatalf("offered this computer for %s: %s", status, got) } } @@ -136,7 +136,7 @@ func TestResumeNeverOffersThisComputersOwnDevice(t *testing.T) { keepSurfaceWorkersInTest(t, a) a.Update(homeMachinesMsg{rows: []chatlist.Row{{Cell: "chat", DeviceID: "self", Device: "laptop", Status: chatlist.Off}}}) a.Update(rosterMsg{devices: []chatlist.Device{{ID: "self", Name: "laptop", Self: true}}}) - if got := leftOffFrame(a); strings.Contains(got, "Continue laptop's latest chat here?") { + if got := leftOffFrame(a); strings.Contains(got, "Move laptop's latest chat here?") { t.Fatalf("the self-device reading left its stale offer: %s", got) } } @@ -171,7 +171,7 @@ func TestFirstEnterWaitsForOwnershipReading(t *testing.T) { _, cmd := a.Update(key("enter")) close(src.ready) spend(t, a, cmd) - if got := plain(frame(a)); strings.Contains(got, chatlist.Unreachable) || !strings.Contains(got, "Continue this chat here?") { + if got := plain(frame(a)); strings.Contains(got, chatlist.Unreachable) || !strings.Contains(got, "Move this chat here?") { t.Fatalf("first send did not raise the card: %s", got) } if a.input.String() != "keep these words" { @@ -216,7 +216,7 @@ func TestHolderReportsRenewalOutageAndRecovery(t *testing.T) { for range 3 { a.Update(tea.WindowSizeMsg{Width: 160, Height: 40}) } - outage := "the sync service is not answering; this chat keeps working here and catches up when it is back" + outage := "the relay is not answering; this chat keeps working here and catches up when it is back" if got := plain(frame(a)); strings.Count(got, outage) != 1 { t.Fatalf("outage notice count is wrong: %s", got) } diff --git a/internal/tui3/removed_continuation_test.go b/internal/tui3/removed_continuation_test.go index 1e937828e4..ed8e6d303e 100644 --- a/internal/tui3/removed_continuation_test.go +++ b/internal/tui3/removed_continuation_test.go @@ -67,7 +67,7 @@ func TestRemovedComputerOffersNoContinuation(t *testing.T) { drain(t, a, a.recordMachines(homeMachinesMsg{err: directory.ErrRevoked})) } text := homeText(a) - if strings.Contains(text, "latest chat here?") || strings.Contains(text, "continue here") { + if strings.Contains(text, "latest chat here?") || strings.Contains(text, "move here") { t.Errorf("removed computer offered continuing: %s", text) } if !strings.Contains(text, removedPairNotice) { diff --git a/internal/tui3/replay.go b/internal/tui3/replay.go index 6d77c34b8d..fc738714ec 100644 --- a/internal/tui3/replay.go +++ b/internal/tui3/replay.go @@ -1,6 +1,7 @@ package tui3 import ( + "context" "path/filepath" "strings" @@ -57,7 +58,33 @@ import ( // the top of an hour-old conversation's last two screens and stopped, with the // rest of it sitting in the journal underneath. Now it is the size of ONE // helping — the opening one, and every one [app.backfill] hands up afterwards. -const replayTail = 40 +const ( + replayTail = 40 + olderPageLimit = 200 +) + +// liveOlderReader returns the front live conversation's OlderReader when the +// front conversation is a live view and its agent implements OlderReader. +func (a *app) liveOlderReader() OlderReader { + if a.liveFront() == nil || a.agent == nil { + return nil + } + older, _ := a.agent.(OlderReader) + return older +} + +// syncLiveOlder resets the live transcript base and older-page availability +// from the front live agent when it implements OlderReader. +func (a *app) syncLiveOlder() { + older := a.liveOlderReader() + if older == nil { + a.transcriptBase = 0 + a.olderMore = false + return + } + a.transcriptBase = max(0, older.TranscriptBase()) + a.olderMore = a.transcriptBase > 0 +} // replay folds the tail of the agent's transcript into entries. It runs once, // at construction, before the surface has drawn anything — and again whenever @@ -101,6 +128,7 @@ func (a *app) replayList(all []session.DisplayEntry) { // dropped and asked for again, so a rebuild after a rewind trusts nothing it // was holding before the cut. a.earlier, a.earlierFloor, a.earlierFrom, a.earlierSeam = nil, 0, 0, false + a.syncLiveOlder() if a.agent == nil { return } @@ -169,7 +197,7 @@ func (a *app) moreHistory() bool { if a.agent == nil { return false } - return a.replayFrom > a.earlierFloor || a.earlierFrom > 0 + return a.replayFrom > a.earlierFloor || a.earlierFrom > 0 || (a.liveOlderReader() != nil && a.olderMore) } // rebase hands the backfill's bookkeeping over to the region a pass has just @@ -325,6 +353,25 @@ func (a *app) prefetchHistory() tea.Cmd { return nil } source = a.earlier + case a.liveOlderReader() != nil && a.olderMore && a.transcriptBase > 0: + older := a.liveOlderReader() + before := a.transcriptBase + baseCtx := a.ctx + if baseCtx == nil { + baseCtx = context.Background() + } + a.historyLoading = true + return func() tea.Msg { + entries, more, err := older.Older(baseCtx, before, olderPageLimit) + return historyPageMsg{ + gen: msg.gen, + entries: append([]session.DisplayEntry(nil), entries...), + older: true, + before: before, + more: more, + err: err, + } + } default: return nil } @@ -344,6 +391,31 @@ func (a *app) historyPrefetched(msg historyPageMsg) tea.Cmd { return nil } a.historyLoading = false + if msg.older { + if a.liveOlderReader() == nil || a.transcriptBase != msg.before { + return nil + } + if msg.err != nil { + a.note(msg.err.Error()) + a.touch() + return nil + } + a.transcript = append(append([]session.DisplayEntry(nil), msg.entries...), a.transcript...) + a.transcriptBase = max(0, msg.before-len(msg.entries)) + a.olderMore = msg.more && len(msg.entries) > 0 && a.transcriptBase > 0 + if len(msg.entries) > 0 { + height := a.viewHeight() + beforeTotal := len(a.visible(a.bodyWidth())) + beforeOffset := a.offsetFor(beforeTotal, height) + a.prepend(msg.entries, false) + afterTotal := len(a.visible(a.bodyWidth())) + if !a.stick { + a.offset = beforeOffset + afterTotal - beforeTotal + } + } + a.touch() + return nil + } if msg.earlier { if a.earlierFrom != msg.to { return a.prefetchHistory() diff --git a/internal/tui3/replay_live_test.go b/internal/tui3/replay_live_test.go new file mode 100644 index 0000000000..424981b256 --- /dev/null +++ b/internal/tui3/replay_live_test.go @@ -0,0 +1,247 @@ +package tui3 + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/session" +) + +type olderAsk struct { + before int + limit int +} + +type fakeOlderAgent struct { + *fakeAgent + all []session.DisplayEntry + base int + calls []olderAsk + err error + forceEnd bool +} + +func newFakeOlderAgent(total, base int) *fakeOlderAgent { + all := make([]session.DisplayEntry, 0, total) + for i := 0; i < total; i++ { + role := "user" + prefix := "question " + if i%2 == 1 { + role = "assistant" + prefix = "answer " + } + all = append(all, session.DisplayEntry{ + Role: role, + Text: prefix + itoa(i), + }) + } + tail := append([]session.DisplayEntry(nil), all[base:]...) + return &fakeOlderAgent{ + fakeAgent: &fakeAgent{model: "m", past: tail}, + all: all, + base: base, + } +} + +func (f *fakeOlderAgent) TranscriptBase() int { + return f.base +} + +func (f *fakeOlderAgent) Older(_ context.Context, before, limit int) ([]session.DisplayEntry, bool, error) { + f.calls = append(f.calls, olderAsk{before: before, limit: limit}) + if f.err != nil { + return nil, false, f.err + } + if before <= 0 || before > len(f.all) { + return nil, false, nil + } + from := max(0, before-limit) + page := append([]session.DisplayEntry(nil), f.all[from:before]...) + more := from > 0 && !f.forceEnd + return page, more, nil +} + +func liveOlderApp(t *testing.T, agent Agent) *app { + t.Helper() + a := newTestApp(&fakeAgent{model: "m"}) + a.width, a.height = 80, 24 + a.dismissWelcome() + a.takeUp(Conversation{ + Agent: agent, + Live: &LiveSeam{ + Host: "Desktop", + Read: func() LiveRead { return LiveRead{Kind: LiveOn} }, + }, + }, true) + a.entries = nil + a.recordRows = 0 + a.turn = 0 + a.replay() + return a +} + +// V4/T11 (contract 1, 2, 3): scrolling up to the oldest entry held locally in a +// live view asks the agent's OlderReader for the page before it with limit<=200, +// draws the arrived page above what was there without moving the line under the +// reader's eye, keeps absolute index counting for the next ask, and removes the +// top marker once more is false. +func TestScrollingUpAtTheTopOfALiveChatAsksTheHostForAnOlderPage(t *testing.T) { + agent := newFakeOlderAgent(1000, 960) + a := liveOlderApp(t, agent) + + if !a.moreHistory() { + t.Fatal("live view at base 960 reported moreHistory() == false") + } + if got := plainRows(a)[0]; !strings.Contains(got, "earlier") { + t.Fatalf("top row did not draw the earlier marker: %q", got) + } + if len(agent.calls) != 0 { + t.Fatalf("Older called on open before scrolling: %+v", agent.calls) + } + + // Scroll to the top of the initial 40 entries (960..999). + for a.offsetFor(len(a.visible(a.bodyWidth())), a.viewHeight()) > a.viewHeight()+1 { + scrollBy(t, a, -1) + } + if len(agent.calls) != 0 { + t.Fatalf("Older called before entering the top prefetch margin: %+v", agent.calls) + } + + beforeWin, _ := a.window(a.bodyWidth(), a.viewHeight()) + if len(beforeWin) == 0 { + t.Fatal("viewport window is empty before older page prefetch") + } + readingLine := plain(beforeWin[0].text) + + // One step into the prefetch margin triggers the first Older request (before=960). + scrollBy(t, a, -1) + if len(agent.calls) != 1 { + t.Fatalf("Older call count = %d, want 1", len(agent.calls)) + } + if agent.calls[0].before != 960 || agent.calls[0].limit <= 0 || agent.calls[0].limit > 200 { + t.Fatalf("first Older call = %+v, want before=960 and 0 < limit <= 200", agent.calls[0]) + } + + // The 200-entry page (760..959) is drawn above what was there and the reading position holds. + drawn := drawnText(a) + for _, want := range []string{"question 760", "answer 959", "question 960", "answer 999"} { + if !strings.Contains(drawn, want) { + t.Fatalf("transcript after first older page is missing %q", want) + } + } + if strings.Contains(drawn, "answer 759") { + t.Fatal("transcript already contains entry 759 before the second Older ask") + } + for _, check := range []string{"question 760", "question 960", "answer 999"} { + if n := strings.Count(drawn, check); n != 1 { + t.Fatalf("entry %q appeared %d times, want 1", check, n) + } + } + + afterWin, _ := a.window(a.bodyWidth(), a.viewHeight()) + foundAt := -1 + for i, r := range afterWin { + if plain(r.text) == readingLine { + foundAt = i + break + } + } + if foundAt < 0 || foundAt > 2 { + t.Fatalf("the line under the reader moved to row %d across the older page arrival (was 0): %q", foundAt, readingLine) + } + if !a.moreHistory() { + t.Fatal("moreHistory() became false while Older returned more=true") + } + + // A second scroll to the top asks with before=760; more=false ends backfilling. + agent.forceEnd = true + for a.offsetFor(len(a.visible(a.bodyWidth())), a.viewHeight()) > 0 { + scrollBy(t, a, -a.scrollPage()) + } + if len(agent.calls) != 2 { + t.Fatalf("Older call count after second scroll to top = %d, want 2: %+v", len(agent.calls), agent.calls) + } + if agent.calls[1].before != 760 || agent.calls[1].limit <= 0 || agent.calls[1].limit > 200 { + t.Fatalf("second Older call = %+v, want before=760 and 0 < limit <= 200", agent.calls[1]) + } + if a.moreHistory() { + t.Fatal("moreHistory() stayed true after Older returned more=false") + } + if got := plainRows(a)[0]; strings.Contains(got, "earlier") { + t.Fatalf("earlier marker remained at the top after more=false: %q", got) + } + + // Scrolling up again at the top makes no further request. + scrollBy(t, a, -a.scrollPage()) + if len(agent.calls) != 2 { + t.Fatalf("Older called again after more=false: %+v", agent.calls) + } +} + +// V4/T11 (contract 4): when Older returns an error, the surface says it once as +// a note and does not retry in a loop; a later scroll to the top asks again. +func TestAnOlderPageThatFailsIsSaidOnceAndNotRetriedInALoop(t *testing.T) { + agent := newFakeOlderAgent(1000, 960) + wantErr := "Desktop did not answer in time" + agent.err = errors.New(wantErr) + a := liveOlderApp(t, agent) + + scrollBy(t, a, -1000) + + if len(agent.calls) != 1 { + t.Fatalf("Older called %d times on first scroll to top, want 1", len(agent.calls)) + } + if got := strings.Count(drawnText(a), wantErr); got != 1 { + t.Fatalf("error note appeared %d times, want 1:\n%s", got, drawnText(a)) + } + + // A later scroll to the top asks again, and succeeds once the error clears. + agent.err = nil + scrollBy(t, a, -a.scrollPage()) + if len(agent.calls) != 2 { + t.Fatalf("Older called %d times on later scroll to top, want 2", len(agent.calls)) + } + if !strings.Contains(drawnText(a), "question 760") { + t.Fatal("retry on later scroll to top did not prepend the older page") + } +} + +// V4/V14/T11 (contract 5): a conversation that is not a live view, or whose +// agent does not implement OlderReader, never calls Older and pages only its +// local transcript slice as before. +func TestAChatThatIsNotLiveNeverAsksForOlderPages(t *testing.T) { + // 1. Not a live view (Live == nil), even when the agent implements OlderReader. + agent := newFakeOlderAgent(1000, 960) + local := newTestApp(agent) + local.width, local.height = 80, 24 + local.dismissWelcome() + local.entries = nil + local.recordRows = 0 + local.turn = 0 + local.replay() + + if local.moreHistory() { + t.Fatal("non-live chat with 40 local entries reported moreHistory() == true") + } + scrollToTop(t, local) + if len(agent.calls) != 0 { + t.Fatalf("non-live chat called Older: %+v", agent.calls) + } + + // 2. A live view whose agent does not implement OlderReader pages locally only. + plainAgent := &fakeAgent{model: "m", past: longPast(80)} + livePlain := liveOlderApp(t, plainAgent) + reads := plainAgent.transcriptReads + scrollToTop(t, livePlain) + if !strings.Contains(drawnText(livePlain), "question 0") { + t.Fatal("live view without OlderReader did not backfill its local transcript") + } + if livePlain.moreHistory() { + t.Fatal("live view without OlderReader still reported moreHistory() at the top") + } + if plainAgent.transcriptReads != reads { + t.Fatalf("scrolling live view without OlderReader re-read Transcript() %d times", plainAgent.transcriptReads-reads) + } +} diff --git a/internal/tui3/settings.go b/internal/tui3/settings.go index b18b8deff9..7c56162dd7 100644 --- a/internal/tui3/settings.go +++ b/internal/tui3/settings.go @@ -521,6 +521,14 @@ var settingUI = map[string]settingMeta{ tab: tabWorkspace, label: "idle handoff", widget: widgetToggle, about: config.IdleHandoffHint, }, + // REMOTE CONTROL SITS ON THE DEVICES TAB, below the computers it is about + // (settings_devices.go). It is a registry row like the ones above, so the + // toggle, the write and the "set by CODEAF_REMOTE_CONTROL" note are the code + // every other switch already runs. + config.KeyRemoteControl: { + tab: tabDevices, label: "remote control", widget: widgetToggle, + about: config.RemoteControlHint, + }, // The three rows Google and Slack connections are signed with. They belong on this tab // and not under Providers because they are not about which model answers // what: they are about what codeaf may REACH on your behalf, which is the @@ -1602,6 +1610,11 @@ func (s *sheet) build() { if !ok || meta.tab != title || crewSeatKey(row.Key) { continue } + // THE SWITCH FOR REACHING OTHER COMPUTERS IS ABSENT WHEN THEY CANNOT BE + // REACHED, in a search as on the tab (settings_devices.go). + if row.Key == config.KeyRemoteControl && s.devicesUnavailable() != "" { + continue + } score, hit, at, n := s.settingMatch(row, meta, title, terms) if !hit { continue @@ -2328,7 +2341,7 @@ func (a *app) sheetKey(msg tea.KeyPressMsg) (cmd tea.Cmd, took bool) { } s := &a.sheet defer a.touch() - if s.dev != nil && s.dev.removing != nil { + if s.dev != nil && s.dev.confirming() { cmd, _ := s.dev.key(a, msg.String()) return cmd, true } @@ -2413,29 +2426,19 @@ func (a *app) sheetKey(msg tea.KeyPressMsg) (cmd tea.Cmd, took bool) { case "enter": return a.activate(), true - case "r": - if s.onDevices() && !s.searching() && s.devicesUnavailable() == "" { - if s.dev != nil && s.dev.loaded { - s.syncDeviceCursor() - if item, ok := s.current(); ok && item.dev != nil && !item.dev.add && !item.dev.storage && !item.dev.unavailable { - return a.revoke(s.dev), true - } - } - return nil, true - } - s.query.insert("r") - s.build() - case "n": + case "r", "n", "w", "t": + key := msg.String() if s.onDevices() && !s.searching() && s.devicesUnavailable() == "" { if s.dev != nil && s.dev.loaded { s.syncDeviceCursor() if item, ok := s.current(); ok && item.dev != nil && !item.dev.add && !item.dev.storage && !item.dev.unavailable { - s.dev.startNaming() + cmd, _ := s.dev.key(a, key) + return cmd, true } } return nil, true } - s.query.insert("n") + s.query.insert(key) s.build() case " ", "space": // A SPACE WHILE A SEARCH IS TYPED IS A WORD IN THE QUERY and not a diff --git a/internal/tui3/settings_devices.go b/internal/tui3/settings_devices.go index 3325569fbb..2c24726536 100644 --- a/internal/tui3/settings_devices.go +++ b/internal/tui3/settings_devices.go @@ -8,6 +8,7 @@ import ( tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" + "github.com/Agent-Field/codeaf/internal/config" "github.com/Agent-Field/codeaf/internal/fuzzy" "github.com/Agent-Field/codeaf/internal/syncsetup" ) @@ -29,7 +30,7 @@ const ( // tabDevices is the category title on the settings bar, placed between // Connections and Privacy. tabDevices = "Devices" - storageLabel = "sync storage" + storageLabel = "relay storage" // devicesAddKey is the key legend clause for the row that starts pairing // another computer. devicesAddKey = "enter add" @@ -110,10 +111,30 @@ func (s *sheet) buildDevices() { s.items = append(s.items, sheetItem{ dev: &deviceSheetRow{add: true}, }) + s.items = append(s.items, s.devicesSettingItems()...) s.cursor = s.clampCursor(s.cursor) s.syncDeviceCursor() } +// devicesSettingItems are the registry rows that belong to this tab, which is +// `remote control` today. They stand AFTER the computers and the add row, so a +// cursor that starts on the first computer starts there still, and they are +// ordinary [sheetItem] rows, so the cursor, the toggle and the hover are the +// code every other tab runs. THE TAB DRAWS THEM ONLY ONCE THE COMPUTERS ARE +// READ ([sheet.buildDevices] returns before this while they load, fail, or +// cannot work here): the loading and failure sentences are what a tab with +// nothing on it says, and a switch for reaching other computers is absent +// without a list of them. +func (s *sheet) devicesSettingItems() []sheetItem { + rows := s.tabRows() + out := make([]sheetItem, 0, len(rows)) + for _, row := range rows { + meta, _ := s.metaFor(row) + out = append(out, sheetItem{row: row, meta: meta}) + } + return out +} + // devEmptyWord is the single sentence drawn when the Devices tab has no rows to // offer: the unavailability reason, the loading line, or the card's own read // failure ([deviceCard.waiting]). @@ -235,10 +256,10 @@ func (s *sheet) appendDevicesSearch(terms []fuzzy.Term) int { if !ok { return 0 } - s.items = append(s.items, - sheetItem{head: tabDevices}, - sheetItem{dev: &deviceSheetRow{unavailable: true}}, - ) + if !s.devicesHeadStands() { + s.items = append(s.items, sheetItem{head: tabDevices}) + } + s.items = append(s.items, sheetItem{dev: &deviceSheetRow{unavailable: true}}) return score } type devHit struct { @@ -271,7 +292,7 @@ func (s *sheet) appendDevicesSearch(terms []fuzzy.Term) int { } } if s.storageCode != "" { - if score, ok, at, size := s.matchHits([]string{storageLabel, "request access", tabDevices}, terms); ok { + if score, ok, at, size := s.matchHits([]string{storageLabel, "request access", tabDevices, config.LegacySyncStorage}, terms); ok { best = max(best, score) matched = append(matched, devHit{item: sheetItem{dev: &deviceSheetRow{storage: true}, hitAt: at, hitLen: size}, score: score}) } @@ -287,13 +308,28 @@ func (s *sheet) appendDevicesSearch(terms []fuzzy.Term) int { return 0 } sort.SliceStable(matched, func(i, j int) bool { return matched[i].score > matched[j].score }) - s.items = append(s.items, sheetItem{head: tabDevices}) + if !s.devicesHeadStands() { + s.items = append(s.items, sheetItem{head: tabDevices}) + } for _, one := range matched { s.items = append(s.items, one.item) } return best } +// devicesHeadStands says whether the group being built already carries the +// Devices heading, which it does when a registry row of this tab (`remote +// control`) matched the search first. Two headings over one group would read as +// two tabs. +func (s *sheet) devicesHeadStands() bool { + for at := len(s.items) - 1; at >= 0; at-- { + if s.items[at].heading() { + return s.items[at].head == tabDevices + } + } + return false +} + // devRowLines renders one row of the Devices tab through the sheet's standard // [overlayLines] grammar while delegating every word and mark of a device row // to [deviceCard.rowText]. When this device is being renamed, the card's own @@ -393,7 +429,7 @@ func (s *sheet) devicesDetails(frameWidth, bodyWidth int) []string { // under the cursor: `r remove` only on a removable computer, `↑↓ choose` only // when more than one row can be walked, and `enter add` on the add row. func (s *sheet) devicesKeysLine() string { - if s.dev != nil && s.dev.removing != nil { + if s.dev != nil && s.dev.confirming() { return s.dev.hint() } if s.devTyping() { @@ -409,7 +445,8 @@ func (s *sheet) devicesKeysLine() string { if restful > 1 { out = append(out, devicesMoveKey) } - if item, ok := s.current(); ok && item.dev != nil && !item.dev.unavailable { + item, ok := s.current() + if ok && item.dev != nil && !item.dev.unavailable { if item.dev.storage { if s.storageState == "off" { out = append(out, "enter request access") @@ -419,11 +456,11 @@ func (s *sheet) devicesKeysLine() string { } else { out = append(out, devicesNameKey) if s.dev != nil && item.dev.index >= 0 && item.dev.index < len(s.dev.rowsOf) { - if row := s.dev.rowsOf[item.dev.index]; !row.Self && !row.Revoked { - out = append(out, devicesGoneKey) - } + out = append(out, s.dev.rowActionKeys(s.dev.rowsOf[item.dev.index])...) } } + } else if ok && item.dev == nil && item.row.Key != "" { + out = append(out, "enter change") } out = append(out, "←→ categories", devicesCloseKey) return strings.Join(out, " · ") diff --git a/internal/tui3/settings_devices_test.go b/internal/tui3/settings_devices_test.go index 18f16afcb1..d0a6c068ff 100644 --- a/internal/tui3/settings_devices_test.go +++ b/internal/tui3/settings_devices_test.go @@ -339,15 +339,17 @@ func TestSettingsDevicesNKeyRenamesThisDeviceAndEscCancelsTypingWithoutClosingSe func TestSettingsDevicesKeysLineShrinksToWhatWorksOnTheCurrentRow(t *testing.T) { now := time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC) - // Single selectable row (empty directory + Add another device): no ↑↓ choose, - // enter add present, no r remove. + // An empty directory leaves the add row and the `remote control` switch, two + // rows to walk, so the legend offers the arrows; the cursor starts on the add + // row, which says enter add and never r remove. (Before the switch stood on + // this tab the add row was alone and the arrows were not offered.) single, _ := openSettingsDevices(t, &fakeApprovals{}, now) keys := single.sheet.keysLine() - if strings.Contains(keys, devicesMoveKey) { - t.Fatalf("single-row Devices tab offered %q: %q", devicesMoveKey, keys) + if !strings.Contains(keys, devicesMoveKey) { + t.Fatalf("a Devices tab with two walkable rows lacked %q: %q", devicesMoveKey, keys) } if !strings.Contains(keys, devicesAddKey) || strings.Contains(keys, devicesGoneKey) { - t.Fatalf("single add row keys wrong: %q", keys) + t.Fatalf("add row keys wrong: %q", keys) } // Multi-row tab: self, removable, and already-removed rows (orderDevices diff --git a/internal/tui3/settings_remote_control_test.go b/internal/tui3/settings_remote_control_test.go new file mode 100644 index 0000000000..a80fc6aaf0 --- /dev/null +++ b/internal/tui3/settings_remote_control_test.go @@ -0,0 +1,133 @@ +package tui3 + +import ( + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/config" +) + +// remoteControlRowApp opens Settings on the Devices tab with the computers read +// and the environment pin out of the way, so the row reads what its file says. +func remoteControlRowApp(t *testing.T, door Approvals) (*app, *pairRig) { + t.Helper() + t.Setenv("CODEAF_HOME", t.TempDir()) + t.Setenv("CODEAF_REMOTE_CONTROL", "") + a, r := openSettingsDevices(t, door, timeNow()) + return a, r +} + +// T15 / D12: Settings, Devices, shows a row called `remote control` that reads +// off until the person turns it on, and one press of enter turns it on and +// writes it, so another computer can open this one's chats without a restart. +func TestTheDevicesTabOffersRemoteControlOffUntilItIsTurnedOn(t *testing.T) { + a, r := remoteControlRowApp(t, devicesFake()) + if config.RemoteControlAt(a.profileDir) { + t.Fatal("remote control read on in a fresh profile") + } + r.press("end") + item, ok := a.sheet.current() + if !ok || item.row.Key != config.KeyRemoteControl { + t.Fatalf("the cursor at the end of the Devices tab is on %+v, want the remote control row", item) + } + got := plain(frame(a)) + if !strings.Contains(got, "remote control") { + t.Fatalf("the Devices tab does not draw the row:\n%s", got) + } + if !strings.Contains(got, "off") { + t.Fatalf("the row does not say it is off:\n%s", got) + } + if keys := a.sheet.devicesKeysLine(); !strings.Contains(keys, "enter change") { + t.Fatalf("the legend on the row does not offer enter: %q", keys) + } + + r.press("enter") + if !config.RemoteControlAt(a.profileDir) { + t.Fatalf("enter on the row did not turn remote control on:\n%s", plain(frame(a))) + } + if got := plain(frame(a)); !strings.Contains(got, "on") { + t.Fatalf("the row does not say it is on after the press:\n%s", got) + } + + r.press("enter") + if config.RemoteControlAt(a.profileDir) { + t.Fatal("a second enter did not turn remote control back off") + } +} + +// T15: the computers keep the top of the tab. The row stands after the add row, +// so the cursor that starts on this computer starts there still. +func TestTheRemoteControlRowStandsAfterTheComputersAndTheAddRow(t *testing.T) { + a, _ := remoteControlRowApp(t, devicesFake()) + items := a.sheet.items + if len(items) < 5 { + t.Fatalf("the Devices tab has %d items, want three computers, the add row and the switch", len(items)) + } + if items[0].dev == nil || items[0].dev.index != 0 { + t.Fatalf("the first item is not the first computer: %+v", items[0]) + } + last := items[len(items)-1] + if last.row.Key != config.KeyRemoteControl { + t.Fatalf("the last item is %+v, want the remote control row", last) + } + before := items[len(items)-2] + if before.dev == nil || !before.dev.add { + t.Fatalf("the item before the switch is %+v, want the add row", before) + } +} + +// T15 / the capability law: when devices cannot work in this session the tab +// has no computers and no switch for reaching them, because a switch that +// cannot do anything is absent and not broken. +func TestTheRemoteControlRowIsAbsentWhenDevicesCannotWork(t *testing.T) { + a, _ := remoteControlRowApp(t, nil) + for _, item := range a.sheet.items { + if item.row.Key == config.KeyRemoteControl { + t.Fatalf("the Devices tab drew the remote control row with no way to reach another computer:\n%s", plain(frame(a))) + } + } +} + +// T15: the row is findable by the words a person would type, from any tab. +func TestSettingsSearchFindsTheRemoteControlRow(t *testing.T) { + t.Setenv("CODEAF_HOME", t.TempDir()) + t.Setenv("CODEAF_REMOTE_CONTROL", "") + a, r := approveApp(t, devicesFake()) + a.openSettings() + for _, ch := range "remote control" { + r.press(string(ch)) + } + got := plain(frame(a)) + if !strings.Contains(got, "remote control") { + t.Fatalf("searching for remote control found nothing:\n%s", got) + } + if !a.sheet.onDevices() { + t.Fatalf("searching for remote control landed on %s, want %s", settingTabs[a.sheet.tab], tabDevices) + } +} + +// T15: a search that matches both the switch and the computers draws the +// Devices heading once and keeps the computers in the same group. +func TestASearchThatFindsRemoteControlAndTheComputersHasOneDevicesHeading(t *testing.T) { + t.Setenv("CODEAF_HOME", t.TempDir()) + t.Setenv("CODEAF_REMOTE_CONTROL", "") + a, r := approveApp(t, devicesFake()) + a.openSettings() + r.press("ctrl+u") + r.typeText("devices") + heads, row := 0, false + for _, item := range a.sheet.items { + if item.heading() && item.head == tabDevices { + heads++ + } + if item.row.Key == config.KeyRemoteControl { + row = true + } + } + if heads != 1 { + t.Fatalf("the search drew the %s heading %d times, want once", tabDevices, heads) + } + if !row { + t.Fatal("the search for devices did not offer the remote control row") + } +} diff --git a/internal/tui3/statusnote.go b/internal/tui3/statusnote.go index c183524aba..21fa48cc6d 100644 --- a/internal/tui3/statusnote.go +++ b/internal/tui3/statusnote.go @@ -117,6 +117,9 @@ func (a *app) statusItems() []deckItem { } items = append(items, item) } + if road := a.liveRoadWord(); road != "" { + items = append(items, deckItem{label: "road", value: road}) + } if a.relayStorageOff() { items = append(items, deckItem{label: storageLabel, value: "off"}) } else if word := a.syncSpaceWord(); word != "" { diff --git a/internal/tui3/storage_off_settings_test.go b/internal/tui3/storage_off_settings_test.go index 9a08bbb6e8..b98a6f117a 100644 --- a/internal/tui3/storage_off_settings_test.go +++ b/internal/tui3/storage_off_settings_test.go @@ -143,7 +143,7 @@ func TestContinueCardSendsAndSavesWhileStorageOff(t *testing.T) { if a.machineRead.sendHolds[at.ID].awaitingWriter { t.Fatal("local continuation waits for an uploading writer") } - if strings.Contains(plain(frame(a)), "continue here") || strings.Contains(plain(frame(a)), "held on other-computer") { + if strings.Contains(plain(frame(a)), "move here") || strings.Contains(plain(frame(a)), "held on other-computer") { t.Fatal("continuation card remained") } typeLine(t, a, "! printf next-local-turn") @@ -226,7 +226,7 @@ func TestSettingsSamplesOnlyVisibleStorage(t *testing.T) { t.Fatalf("state=%s reads=%d", a.sheet.storageState, door.reads.Load()) } a.sheet.tab = 0 - a.sheet.query.insert("sync storage") + a.sheet.query.insert("relay storage") _, cmd = (placeSettings{}).tick(a, time.Now()) if cmd == nil { t.Fatal("Settings search did not refresh") @@ -287,7 +287,7 @@ func TestCloseOlderRemoteSavingReceipt(t *testing.T) { shown := strings.Join(strings.Fields(plain(frame(a))), " ") want := closeSaveFailedWord if receipt { - want = "saved here; it reaches your other devices when the sync service at 127.0.0.1:8901 answers" + want = "saved here; it reaches your other devices when the relay at 127.0.0.1:8901 answers" } if !strings.Contains(shown, want) { t.Fatalf("receipt=%v frame=%s", receipt, shown) diff --git a/internal/tui3/storage_off_window_test.go b/internal/tui3/storage_off_window_test.go index 2944afd3ea..1e7ba346ea 100644 --- a/internal/tui3/storage_off_window_test.go +++ b/internal/tui3/storage_off_window_test.go @@ -22,7 +22,7 @@ func TestFirstStatusAfterPairing(t *testing.T) { door.code = "id_account" cmd := a.runStatusCommand("") shown := plain(frame(a)) - if !strings.Contains(strings.Join(strings.Fields(shown), " "), "sync storage off") || requests != 0 || cmd == nil { + if !strings.Contains(strings.Join(strings.Fields(shown), " "), "relay storage off") || requests != 0 || cmd == nil { t.Fatalf("first status frame, requests=%d: %s", requests, shown) } } @@ -34,7 +34,7 @@ func TestStorageSearchActionMatchesPermission(t *testing.T) { door := &storageApprovals{fakeApprovals: devicesFake(), code: "id_account", state: state} a, r := openSettingsDevices(t, door, time.Now()) r.press("ctrl+u") - r.typeText("sync storage") + r.typeText("relay storage") found := false for i, item := range a.sheet.items { if item.dev != nil && item.dev.storage { @@ -77,7 +77,7 @@ func TestCloseStorageOffReceipt(t *testing.T) { err error want string }{ - {"storage off", syncwords.UploadFailure(wireauth.ErrStorageOff), "saved here; sync storage is off for this account, so it stays on this computer"}, + {"storage off", syncwords.UploadFailure(wireauth.ErrStorageOff), "saved here; relay storage is off for this account, so it stays on this computer"}, {"local failure", errors.New("disk full"), closeSaveFailedWord}, {"mixed failure", errors.Join(errors.New("disk full"), syncwords.UploadFailure(wireauth.ErrStorageOff)), closeSaveFailedWord}, } { @@ -107,7 +107,7 @@ func TestCloseStorageOffReceipt(t *testing.T) { func TestOpenSettingsNoticesPairingAnswer(t *testing.T) { door := &storageApprovals{fakeApprovals: devicesFake()} a, _ := openSettingsDevices(t, door, time.Now()) - if strings.Contains(plain(frame(a)), "sync storage") { + if strings.Contains(plain(frame(a)), "relay storage") { t.Fatal("unpaired row shown") } door.code, door.state = "id_account", "off" @@ -117,7 +117,7 @@ func TestOpenSettingsNoticesPairingAnswer(t *testing.T) { } a.Update(cmd()) shown := plain(frame(a)) - if !strings.Contains(shown, "sync storage") || a.sheet.storageState != "off" { + if !strings.Contains(shown, "relay storage") || a.sheet.storageState != "off" { t.Fatalf("paired row missing: %s", shown) } } @@ -151,7 +151,7 @@ func TestLateCloseStorageOffReceipt(t *testing.T) { <-finished a.Update(noticesMsg{}) shown := strings.Join(strings.Fields(plain(frame(a))), " ") - if !strings.Contains(shown, "saved here; sync storage is off for this account, so it stays on this computer") || strings.Contains(shown, closeSaveFailedWord) { + if !strings.Contains(shown, "saved here; relay storage is off for this account, so it stays on this computer") || strings.Contains(shown, closeSaveFailedWord) { t.Fatalf("late receipt: %s", shown) } } diff --git a/internal/tui3/storage_optin_test.go b/internal/tui3/storage_optin_test.go index de5935ad6a..c78e3035fb 100644 --- a/internal/tui3/storage_optin_test.go +++ b/internal/tui3/storage_optin_test.go @@ -42,7 +42,7 @@ func TestStorageOptInDevicesRequestAndStatus(t *testing.T) { r.press("enter") r.until("storage request opener", func() bool { return opened != "" }) parsed, err := url.Parse(opened) - if err != nil || !strings.HasPrefix(opened, syncsetup.StorageRequestURL+"?") || parsed.Query().Get("title") != "sync storage access: "+code || parsed.Query().Get("body") != "Please turn on sync storage for my account.\n\nRequest code: "+code { + if err != nil || !strings.HasPrefix(opened, syncsetup.StorageRequestURL+"?") || parsed.Query().Get("title") != "relay storage access: "+code || parsed.Query().Get("body") != "Please turn on relay storage for my account.\n\nRequest code: "+code { t.Fatalf("request link: %s %v", opened, err) } details := plain(frame(a)) @@ -51,7 +51,7 @@ func TestStorageOptInDevicesRequestAndStatus(t *testing.T) { } a.syncSpace = blobstore.Counts{Storage: "off"} text := a.statusText() - if !strings.Contains(text, "sync storage") || !strings.Contains(text, "off") || strings.Contains(text, "sync space") { + if !strings.Contains(text, "relay storage") || !strings.Contains(text, "off") || strings.Contains(text, "sync space") { t.Fatalf("off status: %s", text) } for _, fact := range a.statusFacts(text) { @@ -68,7 +68,7 @@ func TestStorageOptInDevicesRequestAndStatus(t *testing.T) { t.Fatal("enabled storage still asks for access") } a.syncSpace = blobstore.Counts{Storage: "on"} - if strings.Contains(a.statusText(), "sync storage") { + if strings.Contains(a.statusText(), "relay storage") { t.Fatal("enabled status has off line") } } @@ -123,7 +123,7 @@ func TestStorageOptInSearchRequestShowsFallbackFrame(t *testing.T) { processOpener = func(string) error { return errors.New("no browser") } t.Cleanup(func() { processOpener = old }) r.press("ctrl+u") - r.typeText("sync storage") + r.typeText("relay storage") for i, item := range a.sheet.items { if item.dev != nil && item.dev.storage { a.sheet.cursor = i @@ -138,6 +138,30 @@ func TestStorageOptInSearchRequestShowsFallbackFrame(t *testing.T) { } } +// The switch is called "relay storage" now. Contract: a person who remembers +// the old name, "sync storage", still finds the same row by typing it, and the +// row is drawn under the new name. +func TestStorageRowIsStillFoundByItsOldName(t *testing.T) { + code := "id_" + strings.Repeat("d", 32) + door := &storageApprovals{fakeApprovals: devicesFake(), code: code, state: "off"} + a, r := openSettingsDevices(t, door, time.Now()) + a.syncService = "http://127.0.0.1:18831" + r.press("ctrl+u") + r.typeText("sync storage") + found := false + for _, item := range a.sheet.items { + if item.dev != nil && item.dev.storage { + found = true + } + } + if !found { + t.Fatalf("searching the old name %q did not find the storage row: %s", "sync storage", plain(frame(a))) + } + if shown := plain(frame(a)); !strings.Contains(shown, "relay storage") { + t.Fatalf("the row must be drawn as relay storage: %s", shown) + } +} + func TestStorageOptInRequestFallbackNarrowPendingDevicesFrame(t *testing.T) { code := "id_" + strings.Repeat("c", 32) door := &storageApprovals{fakeApprovals: devicesFake(), code: code, state: "off"} @@ -169,12 +193,12 @@ func TestStorageOptInStatusPrefersCurrentPermission(t *testing.T) { a.approvals = door a.syncService = "http://127.0.0.1:18831" a.syncSpace = blobstore.Counts{Storage: "on"} - if !strings.Contains(a.statusText(), "sync storage") { + if !strings.Contains(a.statusText(), "relay storage") { t.Fatal("cached refusal hidden by earlier usage answer") } door.state = "on" a.syncSpace.Storage = "off" - if strings.Contains(a.statusText(), "sync storage") { + if strings.Contains(a.statusText(), "relay storage") { t.Fatal("cached approval hidden by earlier usage answer") } } diff --git a/internal/tui3/take_failure_draft_test.go b/internal/tui3/take_failure_draft_test.go index 3d8a73837d..af614d62ec 100644 --- a/internal/tui3/take_failure_draft_test.go +++ b/internal/tui3/take_failure_draft_test.go @@ -45,7 +45,7 @@ func TestEveryFailedTakeReturnsTheCapturedComposer(t *testing.T) { } if failure.err == directory.ErrUnreachable { notes := strings.Join(noteTexts(a), "\n") - if !strings.Contains(notes, continueUnreachable) { + if !strings.Contains(notes, moveUnreachable) { t.Errorf("an unreachable move did not say the chat stayed and the words were kept: %q", notes) } if !a.at(pageHome) || !strings.Contains(homeText(a), "your words are still in the box") { diff --git a/internal/tui3/teamrailpointer.go b/internal/tui3/teamrailpointer.go index 33b475e8ff..4e1b85188f 100644 --- a/internal/tui3/teamrailpointer.go +++ b/internal/tui3/teamrailpointer.go @@ -113,6 +113,9 @@ func (a *app) teamOfFront() (team, bool) { // and the box says which. "" elsewhere. Frame-safe, allocation free for every // conversation that is not in a managed team. func (a *app) trafficHint() string { + if live := a.liveFront(); live != nil && live.Host != "" { + return liveMessageHint(live.Host) + } if a.teamsOff() || !a.wall.loaded || len(a.wall.teams) == 0 { return "" } diff --git a/internal/tui3/teams_refresh_test.go b/internal/tui3/teams_refresh_test.go index abd68cbda7..136d627989 100644 --- a/internal/tui3/teams_refresh_test.go +++ b/internal/tui3/teams_refresh_test.go @@ -72,11 +72,11 @@ func TestSameChatGesturesCheckCachedRemoteOwnershipBeforeReturning(t *testing.T) t.Fatal("front-chat shortcut bypassed ownership") } ask, ok := a.homeAsking() - if !ok || ask.question.Head != continueAsk { + if !ok || ask.question.Head != moveAsk { t.Fatal("no continuation question", ask, ok) } frame, _, _ := a.frame() - if !strings.Contains(plain(frame), continueAsk) { + if !strings.Contains(plain(frame), moveAsk) { t.Fatal("the continuation question is not visible") } }) @@ -103,7 +103,7 @@ func TestRemoteMemberCompletionIsDeduplicatedAndItsLinkContinuesHere(t *testing. a.completeChat(chosen) a.mentionChatPress(chosen.key) ask, ok := a.homeAsking() - if !ok || ask.question.Head != continueAsk { + if !ok || ask.question.Head != moveAsk { t.Fatal("chosen remote link missed continuation") } } diff --git a/internal/tui3/teamsrelay_test.go b/internal/tui3/teamsrelay_test.go index bc05ae374f..aeffe849ba 100644 --- a/internal/tui3/teamsrelay_test.go +++ b/internal/tui3/teamsrelay_test.go @@ -28,7 +28,7 @@ func TestTeamMemberUsesExistingContinueHereQuestion(t *testing.T) { a.wall.teams = []team{{ID: "alpha", Name: "alpha", Members: []teamMember{member}}} a.trafficGo(member.Key) ask, ok := a.homeAsking() - if !ok || ask.question.Head != continueAsk || a.home.armed != machineArm(row.Cell) { + if !ok || ask.question.Head != moveAsk || a.home.armed != machineArm(row.Cell) { t.Fatalf("member did not use existing continuation: %+v %v", ask, ok) } } @@ -98,7 +98,7 @@ func TestRemoteTeamMemberFetchesItsContinueRowWhenHomeHasNotReadItYet(t *testing a.wall.teams = []team{{ID: "alpha", Name: "alpha", Members: []teamMember{member}}} spend(t, a, a.trafficGo(member.Key)) ask, ok := a.homeAsking() - if !ok || ask.question.Head != continueAsk { + if !ok || ask.question.Head != moveAsk { t.Fatal("uncached remote team member did not fetch its continuation row") } } @@ -153,7 +153,7 @@ func TestMemberGesturesShowContinuationAndBothAnswersFromTeamsAndTabs(t *testing drain(t, a, a.tabGo(chatTab{key: m.Key, file: m.File, where: m.Where, word: m.Word})) } frame, _, _ := a.frame() - if !a.at(pageHome) || !strings.Contains(plain(frame), continueAsk) { + if !a.at(pageHome) || !strings.Contains(plain(frame), moveAsk) { t.Fatalf("question not on screen:\n%s", plain(frame)) } if a.home.armed != machineArm(src.row.Cell) { diff --git a/internal/tui3/tui3.go b/internal/tui3/tui3.go index 99843e804d..a8e5aca11d 100644 --- a/internal/tui3/tui3.go +++ b/internal/tui3/tui3.go @@ -187,6 +187,30 @@ type Agent interface { EarlierHistory() session.EarlierHistory } +// OlderReader is an Agent that can fetch entries from before the ones it hands +// over in Transcript(), a page at a time. +type OlderReader interface { + // Older returns up to limit entries that come immediately before the absolute + // index before (counted from the start of the chat's transcript), oldest + // first, and whether there are still older ones. + Older(ctx context.Context, before, limit int) ([]session.DisplayEntry, bool, error) + // TranscriptBase is the absolute index of Transcript()[0]. + TranscriptBase() int +} + +// PermitAsker asks once on Home whether computers paired before remote control +// shipped should also be allowed to type into chats on this computer. +type PermitAsker interface { + // AskOnce says whether Home should ask now, and the names of the computers it + // is about. It is true at most until Answer is called once. IT IS ASKED ON THE + // UPDATE LOOP, every time Home is built, so it must answer from what the door + // already holds and never read a file or the wire. + AskOnce() (names []string, ask bool) + // Answer records the person's decision: true lets those computers type, and + // false keeps them watching. Either answer ends the question for good. + Answer(allow bool) error +} + // detachable is an agent whose conversation OUTLIVES THIS TERMINAL, and it is // how this surface tells the two apart without guessing. // @@ -305,6 +329,12 @@ type Conversation struct { // no link — and every door whose conversations share one connection. Link *LinkSeam + // Live is what the door says about a conversation running on another of this + // person's computers and viewed inside this local window ([LiveSeam]). Nil + // means the conversation is not a live view, and every live-view behaviour is + // absent. + Live *LiveSeam + // Seal is what THIS conversation's seat says about its seals ([SealSeam]). // It is per conversation because a window can switch between them: the // segment and the sentences are the shown session's own. The zero value is @@ -463,6 +493,21 @@ type Options struct { // that cannot, and the offer is then absent rather than failing // (homepanel_continue.go). Takeover Taker + // OpenLive opens a chat held on another of this person's computers as a live + // view inside this local window. Nil means this window has no road to open + // one on (no other computer, or a hosted session) and the surface behaves as + // it does without live views. + OpenLive func(ctx context.Context, row chatlist.Row) (Conversation, error) + // RemoteControl says, at the moment it is asked, whether remote control is + // switched on. It is read each time a live view could be opened and never + // kept, so turning the setting on or off in a running window takes effect + // on the next Enter without a restart. Nil means the opener's presence is + // the whole answer: a window given OpenLive and no RemoteControl offers live + // views. + RemoteControl func() bool + // PermitAsk asks once on Home whether older paired computers may type into + // chats on this computer. Nil means there is nothing to ask. + PermitAsk PermitAsker // Pairing shares this computer's chats with another, and receives another's // (pair.go). Nil is a connection that cannot, and /pair then says so in one // sentence while the first-run screen leaves its code field out. diff --git a/internal/tui3/view.go b/internal/tui3/view.go index 300ca43930..2a1357cb8b 100644 --- a/internal/tui3/view.go +++ b/internal/tui3/view.go @@ -1367,6 +1367,7 @@ func (a *app) offsetFor(total, height int) int { // an offset in already-rendered memory; the command that materializes history // lands later on the update loop. func (a *app) scroll(delta int) tea.Cmd { + a.touchLive() height := a.viewHeight() total := len(a.visible(a.bodyWidth())) at := a.offsetFor(total, height) + delta diff --git a/internal/tui3/watching.go b/internal/tui3/watching.go index d3ca4e02ca..2915af6489 100644 --- a/internal/tui3/watching.go +++ b/internal/tui3/watching.go @@ -62,16 +62,26 @@ type Driving struct { // which a person reads as one they forgot rather than as a machine they // walked away from. It is the case [homeHeldShort] already has a word for. Here bool + // ReadOnly is the sentence explaining why this computer may watch the chat + // but not type into it; empty means typing is permitted. + ReadOnly string + // Holder is the name of the other computer that currently holds the keyboard, + // and empty when this computer holds it. + Holder string } // watching reports that this window is attached to a conversation another window -// is typing into. +// is typing into, or that a live view's composer-position bar is standing. // // IT IS ASKED ON THE DRAW PATH, twice a frame, so it must answer from what is // already held and never from the wire — the same law [LinkSeam.Note] states, // and the client obeys it for the same reason: the answer is a field a frame // already delivered, under the mutex that guards it. func (a *app) watching() bool { + if a.liveFront() != nil { + _, bar := a.liveBar() + return bar + } if a.link.Driving == nil { return false } @@ -117,6 +127,9 @@ func (a *app) watchBar(width int) []string { if width < 1 { return []string{""} } + if word, ok := a.liveBar(); ok { + return []string{a.pal.dim(fit(word, width))} + } left := a.watchWord() gap := width - ansi.StringWidth(left) - ansi.StringWidth(watchKeysWord) if gap < 1 { @@ -150,7 +163,7 @@ func (a *app) watchKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { switch msg.String() { case "enter", "ctrl+enter": a.watchSpaces = 0 - return a.takeKeyboard(), true + return a.liveBarEnter(), true case "alt+enter", "ctrl+j": // A newline into a box nobody can see is nothing at all. a.watchSpaces = 0 @@ -330,6 +343,18 @@ type drivingMsg struct { // // A SEAM THAT IS NOT WIRED ARMS NOTHING, which is every local session. func (a *app) watchDriving() tea.Cmd { + if a.armingLive { + live := a.liveFront() + if live == nil || live.Changed == nil { + return nil + } + changed := live.Changed + gen := a.convGen + return func() tea.Msg { + <-changed() + return liveChangedMsg{gen: gen} + } + } changed := a.link.DrivingChanged if changed == nil { return nil diff --git a/internal/tui3/workspace_take_draft_test.go b/internal/tui3/workspace_take_draft_test.go index 4ee0dd77d6..fd83e4d183 100644 --- a/internal/tui3/workspace_take_draft_test.go +++ b/internal/tui3/workspace_take_draft_test.go @@ -60,7 +60,7 @@ func TestTakeRootPickerPreservesDraftAndSendsOnlyAfterSuccess(t *testing.T) { } a.putComposer(composerState{}) spend(t, a, a.tookTakeover(msg)) - if noted(a, continueFails) { + if noted(a, moveFails) { t.Fatal("a folder choice was reported as a failed take") } if outcome == "cancel first" { @@ -89,7 +89,7 @@ func TestTakeRootPickerPreservesDraftAndSendsOnlyAfterSuccess(t *testing.T) { if (outcome == "cancel first" || outcome == "cancel second" || outcome == "removed") && fake.calls != 1 { t.Fatal("cancelled or removed computer retried the take") } - if (outcome == "cancel first" || outcome == "cancel second") && noted(a, continueFails) { + if (outcome == "cancel first" || outcome == "cancel second") && noted(a, moveFails) { t.Fatal("cancellation reported a failed take") } if outcome == "failure" && !a.machineRead.sendHolds[heldCell].blocked { diff --git a/internal/tui3/wormhole_contract_test.go b/internal/tui3/wormhole_contract_test.go index 9837d3f40c..e4186adfec 100644 --- a/internal/tui3/wormhole_contract_test.go +++ b/internal/tui3/wormhole_contract_test.go @@ -54,7 +54,7 @@ func TestC5OnlineContinueOpensTheArrivedCopy(t *testing.T) { standOn(t, a, "c-run") drive(t, a, key("enter")) if a.at(pageHome) || a.file != transcript || a.workspace != work { - t.Fatalf("continue here stayed on home or opened %s; wanted %s\n%s", a.file, transcript, homeText(a)) + t.Fatalf("move here stayed on home or opened %s; wanted %s\n%s", a.file, transcript, homeText(a)) } if got := plain(lastNote(t, a)); !strings.Contains(got, "Moved from host-a in 3s") { t.Fatalf("no arrival banner: %s", got) diff --git a/internal/viewcache/cache.go b/internal/viewcache/cache.go new file mode 100644 index 0000000000..31da28e231 --- /dev/null +++ b/internal/viewcache/cache.go @@ -0,0 +1,388 @@ +// Package viewcache is the copy of another computer's chat that THIS computer +// keeps, so a chat that cannot be reached can still be read. +// +// A live view (another of the person's computers is running the chat and this +// one watches and types into it) leaves nothing behind on the relay: it carries +// bytes it cannot read and stores no chat text. That is the promise, and it is +// also the weakness, because when the other computer goes away there is nothing +// anywhere to show. So the viewer keeps, on its own disk and nowhere else, the +// last thing it drew: the final stretch of the transcript, the title and the +// moment it was last up to date. It is read-only by construction. Nothing here +// can send a word to the other computer, and the surface that draws it says so. +// +// THE TRUST BOUNDARY IS THE VIEWER'S OWN HOME. The copy is plain text, like the +// viewer's own transcripts under the same folder, readable by this person alone +// (directories 0700, files 0600). It holds what the host's transcript holds, +// which already leaves out whatever the seal guard keeps out of saved history, +// so it adds no new reach for a secret. +// +// IT IS BOUNDED, AND THE BOUNDS ARE ONE SET OF CONSTANTS. A copy that grew with +// every chat ever watched would be a second, unbounded transcript store on a +// laptop, so the last [MaxEntries] entries and at most [MaxBytes] of one chat +// are kept, for at most [MaxChats] chats, oldest out. PERF.md carries the same +// numbers and changes in the same commit as these. +package viewcache + +import ( + "encoding/json" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/fsreplace" + "github.com/Agent-Field/codeaf/internal/session" +) + +// The bounds. A number that appears in two places drifts, so PERF.md and the +// manual quote these and nothing else spells them. +const ( + // MaxEntries is how many of the newest transcript entries one chat keeps. + MaxEntries = 200 + // MaxBytes is the most one chat's file may weigh. Oldest entries go first + // until it fits. + MaxBytes = 1 << 20 + // MaxChats is how many chats the whole cache keeps, across every computer. + MaxChats = 40 + // WriteEvery is the shortest gap between two writes of one chat's copy by + // [Cache.Save]. A copy is written on a quiet beat, never per frame; this is + // the floor under a caller that gets the beat wrong. + WriteEvery = 2 * time.Second +) + +// version is the on-disk format. It is the first field of every file. +const version = 1 + +// Clock is the one thing the cache asks the time for, so a test moves time +// instead of sleeping through it. +type Clock interface{ Now() time.Time } + +type realClock struct{} + +func (realClock) Now() time.Time { return time.Now() } + +// Snapshot is one chat as this computer last saw it. +type Snapshot struct { + // Host is the directory device id of the computer that runs the chat and + // HostName the name a person knows it by. + Host string + HostName string + // Chat is the chat's cell id, the same id a Home row carries. + Chat string + Title string + Model string + Workspace string + // SeenAt is when this copy was last brought up to date from the live view. + SeenAt time.Time + // Base is the absolute index, counted from the start of the chat's + // transcript, of Entries[0], and Total is how many entries the transcript + // had. They keep "scroll up for older" honest after the copy has been cut to + // its newest stretch. + Base, Total int + Entries []session.DisplayEntry +} + +// Cache is the viewer's folder of last-seen copies. +type Cache struct { + root string + clk Clock + + mu sync.Mutex + wrote map[string]time.Time // key host/chat -> last write +} + +// Open returns the cache under a CODEAF_HOME. Nothing is created until the +// first Save. +func Open(home string) *Cache { return OpenWith(home, realClock{}) } + +// OpenWith is [Open] with a clock a test controls. +func OpenWith(home string, clk Clock) *Cache { + if clk == nil { + clk = realClock{} + } + return &Cache{ + root: filepath.Join(home, "v3", "viewed"), + clk: clk, + wrote: map[string]time.Time{}, + } +} + +// fileDoc is what a file holds. V is first so a reader can tell the format +// before it trusts anything else in the file. +type fileDoc struct { + V int `json:"V"` + Snapshot +} + +// folder turns a name a computer chose, or an id it was given, into one path +// element: letters, digits and three quiet punctuation marks, everything else a +// dash. It cannot name a parent folder, and two different names can only +// collide by being spelled almost identically. +func folder(name, empty string) string { + name = strings.TrimSpace(name) + var b strings.Builder + for _, r := range name { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', + r == '.', r == '_', r == '-': + b.WriteRune(r) + default: + b.WriteByte('-') + } + } + out := b.String() + if out == "" || strings.Trim(out, ".") == "" { + return empty + } + return out +} + +func (c *Cache) dir(host string) string { return filepath.Join(c.root, folder(host, "elsewhere")) } + +func (c *Cache) path(host, chat string) string { + return filepath.Join(c.dir(host), folder(chat, "chat")+".json") +} + +func key(host, chat string) string { return folder(host, "elsewhere") + "/" + folder(chat, "chat") } + +// Save writes the copy of one chat, unless it wrote that chat less than +// [WriteEvery] ago, in which case it does nothing and says nothing: the next +// quiet beat carries the newer one. Use [Cache.SaveNow] when the view is about +// to go away. +func (c *Cache) Save(host, chat string, s Snapshot) error { + c.mu.Lock() + last, ok := c.wrote[key(host, chat)] + c.mu.Unlock() + if ok && c.clk.Now().Sub(last) < WriteEvery { + return nil + } + return c.SaveNow(host, chat, s) +} + +// SaveNow writes the copy whatever was written a moment ago. It is for the +// beats that end a view (the person left it, the link closed), because those +// are the last chance to keep what was on screen. +func (c *Cache) SaveNow(host, chat string, s Snapshot) error { + s.Host, s.Chat = host, chat + if s.SeenAt.IsZero() { + s.SeenAt = c.clk.Now() + } + s = bound(s) + raw, err := marshalBounded(&s) + if err != nil { + return err + } + dir := c.dir(host) + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + // MkdirAll leaves an existing folder's mode alone; a folder somebody made + // wider is narrowed again, because this one is private. + _ = os.Chmod(c.root, 0o700) + _ = os.Chmod(dir, 0o700) + if err := writeAtomic(c.path(host, chat), raw); err != nil { + return err + } + c.mu.Lock() + c.wrote[key(host, chat)] = c.clk.Now() + c.mu.Unlock() + c.Prune() + return nil +} + +// bound cuts a snapshot to its newest [MaxEntries] and keeps Base and Total +// consistent with what it cut. +func bound(s Snapshot) Snapshot { + if len(s.Entries) > MaxEntries { + drop := len(s.Entries) - MaxEntries + s.Entries = append([]session.DisplayEntry(nil), s.Entries[drop:]...) + s.Base += drop + } + if s.Total < s.Base+len(s.Entries) { + s.Total = s.Base + len(s.Entries) + } + return s +} + +// marshalBounded renders the file and drops the oldest entries until it weighs +// no more than [MaxBytes]. A chat whose single newest entry is larger than that +// is kept with no entries at all, which still says when it was last seen and +// what it was called. +func marshalBounded(s *Snapshot) ([]byte, error) { + for { + raw, err := json.Marshal(fileDoc{V: version, Snapshot: *s}) + if err != nil { + return nil, err + } + if len(raw) <= MaxBytes || len(s.Entries) == 0 { + return raw, nil + } + // Drop the share of the entries that the excess is of the file, plus + // one, so a long chat of long entries is not marshalled once per entry. + over := len(raw) - MaxBytes + drop := min(len(s.Entries), len(s.Entries)*over/len(raw)+1) + s.Entries = append([]session.DisplayEntry(nil), s.Entries[drop:]...) + s.Base += drop + } +} + +// writeAtomic puts the bytes where the file belongs through a temporary file in +// the same folder, so a reader never meets half of one. +func writeAtomic(path string, raw []byte) error { + tmp, err := os.CreateTemp(filepath.Dir(path), ".viewed-*.tmp") + if err != nil { + return err + } + name := tmp.Name() + fail := func(err error) error { + _ = tmp.Close() + _ = os.Remove(name) + return err + } + if err := tmp.Chmod(0o600); err != nil { + return fail(err) + } + if _, err := tmp.Write(raw); err != nil { + return fail(err) + } + if err := tmp.Close(); err != nil { + _ = os.Remove(name) + return err + } + if err := fsreplace.Rename(name, path); err != nil { + _ = os.Remove(name) + return err + } + return nil +} + +// Load reads the copy of one chat. It answers false for a chat that was never +// kept, for a file it cannot read, and for one that says it is about another +// chat or another computer: a copy it cannot vouch for is not shown. +func (c *Cache) Load(host, chat string) (Snapshot, bool) { + raw, err := os.ReadFile(c.path(host, chat)) + if err != nil { + return Snapshot{}, false + } + var doc fileDoc + if err := json.Unmarshal(raw, &doc); err != nil || doc.V != version { + return Snapshot{}, false + } + if doc.Host != host || doc.Chat != chat { + return Snapshot{}, false + } + return doc.Snapshot, true +} + +// Forget removes every copy kept for one computer. It is what removing the +// computer from the person's devices does, and what moving a chat here does for +// that chat ([Cache.ForgetChat]). +func (c *Cache) Forget(host string) { + _ = os.RemoveAll(c.dir(host)) + prefix := folder(host, "elsewhere") + "/" + c.mu.Lock() + for k := range c.wrote { + if strings.HasPrefix(k, prefix) { + delete(c.wrote, k) + } + } + c.mu.Unlock() +} + +// ForgetChat removes the copy of one chat. +func (c *Cache) ForgetChat(host, chat string) { + _ = os.Remove(c.path(host, chat)) + c.mu.Lock() + delete(c.wrote, key(host, chat)) + c.mu.Unlock() +} + +// ForgetChatEverywhere removes the copy of one chat kept for every computer. +// Moving a chat here uses it, because the window that moved it does not know +// which computer the copy was last seen on, and a copy of a chat that now runs +// on this computer is only a stale picture of it. +func (c *Cache) ForgetChatEverywhere(chat string) { + hosts, err := os.ReadDir(c.root) + if err != nil { + return + } + for _, host := range hosts { + if !host.IsDir() { + continue + } + _ = os.Remove(filepath.Join(c.root, host.Name(), folder(chat, "chat")+".json")) + c.mu.Lock() + delete(c.wrote, host.Name()+"/"+folder(chat, "chat")) + c.mu.Unlock() + } +} + +type found struct { + path string + at time.Time +} + +// Prune keeps the newest [MaxChats] copies across every computer, removes the +// stray temporary files a crashed write left behind, and removes a computer's +// folder once nothing is left in it. +func (c *Cache) Prune() { + hosts, err := os.ReadDir(c.root) + if err != nil { + return + } + var all []found + for _, h := range hosts { + if !h.IsDir() { + continue + } + dir := filepath.Join(c.root, h.Name()) + entries, err := os.ReadDir(dir) + if err != nil { + continue + } + for _, e := range entries { + path := filepath.Join(dir, e.Name()) + if e.IsDir() { + continue + } + if strings.HasSuffix(e.Name(), ".tmp") { + if info, err := e.Info(); err == nil && c.clk.Now().Sub(info.ModTime()) > time.Minute { + _ = os.Remove(path) + } + continue + } + if !strings.HasSuffix(e.Name(), ".json") { + continue + } + at := seenAt(path) + if at.IsZero() { + _ = os.Remove(path) + continue + } + all = append(all, found{path: path, at: at}) + } + if len(entries) == 0 { + _ = os.Remove(dir) + } + } + if len(all) <= MaxChats { + return + } + sort.Slice(all, func(i, j int) bool { return all[i].at.After(all[j].at) }) + for _, old := range all[MaxChats:] { + _ = os.Remove(old.path) + } +} + +// seenAt is when a file was last written, which is when its copy was last +// brought up to date. It is read from the file's own time and not from its +// contents, so pruning forty chats does not read forty megabytes. +func seenAt(path string) time.Time { + info, err := os.Stat(path) + if err != nil { + return time.Time{} + } + return info.ModTime() +} diff --git a/internal/viewcache/cache_test.go b/internal/viewcache/cache_test.go new file mode 100644 index 0000000000..3202b09923 --- /dev/null +++ b/internal/viewcache/cache_test.go @@ -0,0 +1,333 @@ +package viewcache + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/session" +) + +// These tests are written from what a person is promised, not from the file +// layout: a chat they were watching can still be read when its computer is gone +// (V27), the copy lives on their own disk and stays small, and nothing here can +// leave it or grow without end. + +type fakeClock struct{ at time.Time } + +func (f *fakeClock) Now() time.Time { return f.at } +func (f *fakeClock) advance(d time.Duration) { f.at = f.at.Add(d) } + +func newCache(t *testing.T) (*Cache, string, *fakeClock) { + t.Helper() + home := t.TempDir() + clk := &fakeClock{at: time.Date(2026, 11, 23, 14, 2, 0, 0, time.UTC)} + return OpenWith(home, clk), home, clk +} + +func entries(n int, text string) []session.DisplayEntry { + out := make([]session.DisplayEntry, n) + for i := range out { + out[i] = session.DisplayEntry{Role: "assistant", Text: fmt.Sprintf("%s %d", text, i)} + } + return out +} + +// V27: a chat that was being watched can be read after its computer is gone. +func TestAWatchedChatComesBackAsItWasLastSeen(t *testing.T) { + c, _, clk := newCache(t) + seen := clk.Now() + in := Snapshot{ + HostName: "Desktop", Title: "port the parser", Model: "m", Workspace: "parser", + SeenAt: seen, Base: 0, Total: 3, Entries: entries(3, "line"), + } + if err := c.SaveNow("dev_desk", "cell1", in); err != nil { + t.Fatal(err) + } + got, ok := c.Load("dev_desk", "cell1") + if !ok { + t.Fatal("a chat that was kept cannot be read back") + } + if got.Title != "port the parser" || got.HostName != "Desktop" || got.Host != "dev_desk" || got.Chat != "cell1" { + t.Fatalf("what the person saw changed: %+v", got) + } + if !got.SeenAt.Equal(seen) { + t.Fatalf("last seen %v, want %v: the banner would say the wrong time", got.SeenAt, seen) + } + if len(got.Entries) != 3 || got.Entries[2].Text != "line 2" { + t.Fatalf("entries came back as %+v", got.Entries) + } + if _, ok := c.Load("dev_desk", "another-chat"); ok { + t.Fatal("a chat never watched has a copy") + } + if _, ok := c.Load("dev_other", "cell1"); ok { + t.Fatal("another computer's chat answered for this one") + } +} + +// V27: bounded. The copy holds the newest stretch, and scrolling up still counts +// from the start of the transcript. +func TestASnapshotIsBoundedAndPlainTextOnlyOnTheViewersDisk(t *testing.T) { + c, home, _ := newCache(t) + if err := c.SaveNow("dev_desk", "long", Snapshot{Total: 1000, Base: 700, Entries: entries(300, "e")}); err != nil { + t.Fatal(err) + } + got, _ := c.Load("dev_desk", "long") + if len(got.Entries) != MaxEntries { + t.Fatalf("kept %d entries, want the newest %d", len(got.Entries), MaxEntries) + } + if got.Entries[len(got.Entries)-1].Text != "e 299" { + t.Fatalf("kept the wrong end: last is %q", got.Entries[len(got.Entries)-1].Text) + } + if got.Base != 800 || got.Total != 1000 { + t.Fatalf("base %d total %d: the copy no longer says where in the chat it is", got.Base, got.Total) + } + + // A chat of very large entries is held to its byte bound, oldest out. + big := strings.Repeat("x", 100<<10) + huge := make([]session.DisplayEntry, 40) + for i := range huge { + huge[i] = session.DisplayEntry{Role: "tool", Text: fmt.Sprintf("%02d%s", i, big)} + } + if err := c.SaveNow("dev_desk", "huge", Snapshot{Total: 40, Entries: huge}); err != nil { + t.Fatal(err) + } + info, err := os.Stat(filepath.Join(home, "v3", "viewed", "dev_desk", "huge.json")) + if err != nil { + t.Fatal(err) + } + if info.Size() > MaxBytes { + t.Fatalf("one chat weighs %d bytes, over the %d bound", info.Size(), MaxBytes) + } + h, _ := c.Load("dev_desk", "huge") + if len(h.Entries) == 0 || !strings.HasPrefix(h.Entries[len(h.Entries)-1].Text, "39") { + t.Fatalf("the newest entry was not the one kept") + } + if h.Base+len(h.Entries) != 40 { + t.Fatalf("base %d plus %d entries is not the transcript's end", h.Base, len(h.Entries)) + } + + // One entry larger than the whole bound is dropped, and the chat is still + // remembered with its title and the time. + one := []session.DisplayEntry{{Role: "tool", Text: strings.Repeat("y", 2<<20)}} + if err := c.SaveNow("dev_desk", "one", Snapshot{Title: "kept", Total: 1, Entries: one}); err != nil { + t.Fatal(err) + } + o, ok := c.Load("dev_desk", "one") + if !ok || o.Title != "kept" || len(o.Entries) != 0 { + t.Fatalf("an oversize entry broke the copy: %+v ok=%v", o, ok) + } + + // Plain text, in the viewer's own folder, and nothing else written. + raw, err := os.ReadFile(filepath.Join(home, "v3", "viewed", "dev_desk", "long.json")) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(string(raw), `{"V":1,`) || !strings.Contains(string(raw), "e 299") { + t.Fatalf("the file is not plain versioned text: %.80s", raw) + } + var stray []string + _ = filepath.Walk(home, func(p string, i os.FileInfo, err error) error { + if err == nil && !i.IsDir() && !strings.Contains(p, filepath.Join("v3", "viewed")) { + stray = append(stray, p) + } + return nil + }) + if len(stray) > 0 { + t.Fatalf("wrote outside the viewed folder: %v", stray) + } +} + +// V27: the copy is for this person alone. +func TestTheCopyIsReadableByThisPersonOnly(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("file modes are not a thing on this platform") + } + c, home, _ := newCache(t) + if err := c.SaveNow("dev_desk", "cell1", Snapshot{Entries: entries(1, "a")}); err != nil { + t.Fatal(err) + } + for _, dir := range []string{ + filepath.Join(home, "v3", "viewed"), + filepath.Join(home, "v3", "viewed", "dev_desk"), + } { + info, err := os.Stat(dir) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o700 { + t.Errorf("%s is %o, want 700", dir, info.Mode().Perm()) + } + } + info, err := os.Stat(filepath.Join(home, "v3", "viewed", "dev_desk", "cell1.json")) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Errorf("the copy is %o, want 600", info.Mode().Perm()) + } +} + +// The cache keeps the newest forty chats across every computer and lets the +// oldest go. +func TestOnlyTheNewestFortyChatsAreKept(t *testing.T) { + c, _, clk := newCache(t) + for i := 0; i < MaxChats+5; i++ { + clk.advance(time.Minute) + host := fmt.Sprintf("dev_%d", i%3) + if err := c.SaveNow(host, fmt.Sprintf("chat%02d", i), Snapshot{Entries: entries(1, "a")}); err != nil { + t.Fatal(err) + } + // Files are aged by their own time, which a fake clock does not move. + old := time.Now().Add(time.Duration(i-MaxChats-10) * time.Hour) + _ = os.Chtimes(c.path(host, fmt.Sprintf("chat%02d", i)), old, old) + } + c.Prune() + kept := 0 + for i := 0; i < MaxChats+5; i++ { + _, ok := c.Load(fmt.Sprintf("dev_%d", i%3), fmt.Sprintf("chat%02d", i)) + if ok { + kept++ + if i < 5 { + t.Errorf("chat%02d, one of the oldest five, is still kept", i) + } + } else if i >= 5 { + t.Errorf("chat%02d is newer than the oldest five and was removed", i) + } + } + if kept != MaxChats { + t.Fatalf("kept %d chats, want %d", kept, MaxChats) + } +} + +// A copy is written on a quiet beat, never per frame. +func TestACopyIsNotRewrittenMoreThanOnceInTwoSeconds(t *testing.T) { + c, _, clk := newCache(t) + if err := c.Save("dev_desk", "c", Snapshot{Title: "first", Entries: entries(1, "a")}); err != nil { + t.Fatal(err) + } + clk.advance(WriteEvery - time.Millisecond) + if err := c.Save("dev_desk", "c", Snapshot{Title: "second", Entries: entries(1, "b")}); err != nil { + t.Fatal(err) + } + if got, _ := c.Load("dev_desk", "c"); got.Title != "first" { + t.Fatalf("wrote again inside the window: %q", got.Title) + } + // The beats that end a view are not held back. + if err := c.SaveNow("dev_desk", "c", Snapshot{Title: "closing", Entries: entries(1, "c")}); err != nil { + t.Fatal(err) + } + if got, _ := c.Load("dev_desk", "c"); got.Title != "closing" { + t.Fatalf("the view that was ending was not kept: %q", got.Title) + } + clk.advance(WriteEvery) + if err := c.Save("dev_desk", "c", Snapshot{Title: "later", Entries: entries(1, "d")}); err != nil { + t.Fatal(err) + } + if got, _ := c.Load("dev_desk", "c"); got.Title != "later" { + t.Fatalf("never wrote again after the window: %q", got.Title) + } +} + +// Removing a computer, or moving a chat here, takes its copy with it. +func TestForgettingAComputerOrAChatRemovesOnlyThat(t *testing.T) { + c, home, _ := newCache(t) + for _, k := range [][2]string{{"dev_a", "1"}, {"dev_a", "2"}, {"dev_b", "1"}} { + if err := c.SaveNow(k[0], k[1], Snapshot{Entries: entries(1, "a")}); err != nil { + t.Fatal(err) + } + } + c.ForgetChat("dev_a", "1") + if _, ok := c.Load("dev_a", "1"); ok { + t.Fatal("the chat that was forgotten is still kept") + } + if _, ok := c.Load("dev_a", "2"); !ok { + t.Fatal("forgetting one chat removed its neighbour") + } + c.Forget("dev_a") + if _, ok := c.Load("dev_a", "2"); ok { + t.Fatal("a removed computer's chat is still kept") + } + if _, ok := c.Load("dev_b", "1"); !ok { + t.Fatal("removing one computer removed another's copy") + } + if _, err := os.Stat(filepath.Join(home, "v3", "viewed", "dev_a")); err == nil { + t.Fatal("a removed computer's folder is still there") + } +} + +// Moving a chat here does not know which computer its copy was last seen on, +// so it takes that chat's copy from every computer and leaves the others alone. +func TestForgettingAChatEverywhereKeepsEveryOtherChat(t *testing.T) { + c, _, _ := newCache(t) + for _, k := range [][2]string{{"dev_a", "1"}, {"dev_b", "1"}, {"dev_b", "2"}} { + if err := c.SaveNow(k[0], k[1], Snapshot{Entries: entries(1, "a")}); err != nil { + t.Fatal(err) + } + } + c.ForgetChatEverywhere("1") + for _, host := range []string{"dev_a", "dev_b"} { + if _, ok := c.Load(host, "1"); ok { + t.Fatalf("the copy of chat 1 kept for %s survived", host) + } + } + if _, ok := c.Load("dev_b", "2"); !ok { + t.Fatal("forgetting chat 1 everywhere removed chat 2") + } + // A cache with nothing in it forgets nothing and says nothing. + empty, _, _ := newCache(t) + empty.ForgetChatEverywhere("1") +} + +// A name a computer chose can never name a place outside the cache. +func TestNamesThatLookLikePathsStayInsideTheCache(t *testing.T) { + c, home, _ := newCache(t) + if err := c.SaveNow("../../escape", "../../../etc/passwd", Snapshot{Entries: entries(1, "a")}); err != nil { + t.Fatal(err) + } + var outside []string + _ = filepath.Walk(home, func(p string, i os.FileInfo, err error) error { + if err == nil && !i.IsDir() && !strings.HasPrefix(p, filepath.Join(home, "v3", "viewed")+string(filepath.Separator)) { + outside = append(outside, p) + } + return nil + }) + if len(outside) > 0 { + t.Fatalf("left the cache: %v", outside) + } + if _, ok := c.Load("../../escape", "../../../etc/passwd"); !ok { + t.Fatal("a chat saved under an odd name cannot be read back under it") + } +} + +// A copy this build cannot vouch for is not shown. +func TestACopyThatIsDamagedOrAboutAnotherChatIsNotShown(t *testing.T) { + c, _, _ := newCache(t) + if err := c.SaveNow("dev_a", "one", Snapshot{Entries: entries(1, "a")}); err != nil { + t.Fatal(err) + } + // Somebody copied one chat's file over another's name. + raw, _ := os.ReadFile(c.path("dev_a", "one")) + if err := os.WriteFile(c.path("dev_a", "two"), raw, 0o600); err != nil { + t.Fatal(err) + } + if _, ok := c.Load("dev_a", "two"); ok { + t.Fatal("a file that says it is another chat answered for this one") + } + if err := os.WriteFile(c.path("dev_a", "one"), []byte("{not json"), 0o600); err != nil { + t.Fatal(err) + } + if _, ok := c.Load("dev_a", "one"); ok { + t.Fatal("a damaged file was shown") + } + if err := os.WriteFile(c.path("dev_a", "one"), []byte(`{"V":99,"Host":"dev_a","Chat":"one"}`), 0o600); err != nil { + t.Fatal(err) + } + if _, ok := c.Load("dev_a", "one"); ok { + t.Fatal("a format from the future was shown") + } +} diff --git a/internal/wireauth/wireauth.go b/internal/wireauth/wireauth.go index a4862ab3e6..8ab3265493 100644 --- a/internal/wireauth/wireauth.go +++ b/internal/wireauth/wireauth.go @@ -74,7 +74,7 @@ var ErrRateLimited = errors.New("wireauth: rate limited") var ErrTooManyIdentities = errors.New("wireauth: too many new identities") // ErrStorageOff means the relay has not enabled storage for this account. -var ErrStorageOff = errors.New("wireauth: sync storage off") +var ErrStorageOff = errors.New("wireauth: relay storage off") // ErrRelayFull identifies shared storage capacity on both wires. Each decoder // also retains its own general full error so existing callers keep matching it. diff --git a/internal/wordlaw/relay_manual.golden b/internal/wordlaw/relay_manual.golden new file mode 100644 index 0000000000..722f3c2920 --- /dev/null +++ b/internal/wordlaw/relay_manual.golden @@ -0,0 +1,109 @@ +# How many times each chat manual page says "relay" (any case, any form: relay, relays, relayed). +# A page's count may fall and may not rise. Regenerate with: go test ./internal/wordlaw -run Relay -update +# Format: pagecount +a-dev-box-on-your-own-railway.md 10 +accounts.md 0 +adaptive-runs.md 0 +add-or-remove-a-computer.md 36 +app-provider-connections.md 0 +asking-from-home.md 0 +attaching-files.md 0 +automations.md 0 +choosing-a-folder.md 0 +claude-code-provider.md 2 +claude.md 0 +client-tools.md 0 +closing-a-chat.md 0 +collections.md 0 +commands.md 8 +compacting-over-and-over.md 0 +continuing-a-chat-on-another-computer.md 78 +conversations-and-teams.md 22 +coordination-and-workers.md 72 +debug-record.md 0 +delegates.md 0 +desktop-sync.md 31 +empty-screen.md 0 +factory-agentfield.md 0 +factory-ai-search.md 0 +factory-jira.md 0 +factory-stage-conversations.md 0 +factory.md 0 +forking-and-syncing-a-workspace.md 0 +getting-started.md 5 +giving-a-password-or-token.md 0 +hints-and-tips.md 0 +home.md 26 +how-tasks-run.md 1 +inbox.md 0 +inviting-people.md 0 +kept-running.md 0 +keys.md 7 +lanes.md 0 +linux-workspace-limits.md 0 +lock-out-a-lost-computer.md 27 +losing-every-device.md 11 +making-pictures-audio-and-video.md 0 +models-and-cost.md 4 +my-space.md 0 +naming-a-device.md 1 +opening-files-from-that-machine.md 0 +openrouter-credits.md 0 +organization-agents.md 0 +organization-hosted-sessions.md 0 +organization-library.md 0 +organization-sharing.md 0 +organization-start.md 0 +organization-workstream-agent.md 0 +organization-workstream-tasks.md 0 +permissions.md 0 +places.md 0 +putting-a-skill-in-front.md 0 +questions.md 0 +quick-switch-models.md 0 +reaching-this-machine-without-ssh.md 69 +reading-a-task-page.md 0 +relay-hosted-or-your-own.md 69 +relay-limits-and-refusals.md 56 +relay-what-it-stores-and-sees.md 69 +remote-control.md 16 +review.md 0 +running-commands-on-windows.md 0 +running-from-the-terminal.md 38 +running-on-another-machine.md 3 +saved-programs.md 0 +saved-shapes-of-work.md 0 +screen.md 0 +sec.md 0 +senior-dev.md 0 +services.md 0 +sessions-and-rewind.md 4 +settings.md 9 +skills-a-turn-used.md 0 +skills-from-other-tools.md 0 +starting-codeaf.md 10 +staying-on-that-machine.md 0 +subharnesses.md 0 +task-controls.md 0 +task-rooms-after-restart.md 0 +tasks-on-another-computer.md 14 +tasks.md 1 +team-manager.md 7 +team-questions-and-caps.md 0 +teams-page.md 0 +telemetry.md 0 +unattended-run-limits.md 0 +use-skill.md 0 +use-this-on-another-computer.md 93 +what-i-can-do.md 0 +what-i-remember.md 6 +when-the-connection-drops.md 4 +work-home-and-overview.md 0 +worker-harness.md 2 +working-indicator.md 0 +workstream-asks-and-decisions.md 0 +workstream-chats-and-tools.md 0 +workstream-files.md 0 +workstream-new-setup.md 0 +workstream-overview.md 0 +workstream-people-and-rules.md 0 diff --git a/internal/wordlaw/relay_words.golden b/internal/wordlaw/relay_words.golden new file mode 100644 index 0000000000..5497db7d74 --- /dev/null +++ b/internal/wordlaw/relay_words.golden @@ -0,0 +1,207 @@ +# Every non-test Go string in cmd and internal that says "relay", with the class a person gave it. +# server = the server (its address, commands, refusals); storage = the switch that lets it keep sealed copies; +# other-feature = a different feature that says the word (only the model pool's own files). +# model-prompt = an instruction to the model using the plain verb ("relay it"), only in internal/session; to be reworded. +# Regenerate with: go test ./internal/wordlaw -run Relay -update Then read the diff. +# Format: classpathquoted text +model-prompt internal/session/assignment_tool.go "Fold a direction the PERSON just gave you into what this task is for. Only for a line that CHANGES THE JOB — a different output format, a different target, a requirement dropped or added — and only citing the direction id that carried it. A fact you were handed (\"the config lives under etc/\"), a question about your approach, and anything another agent relayed are NOT this: use them, answer them, and leave the assignment alone. What you set here is what the checker will judge the finished work against, so state it as an observable condition and keep everything the person did not change." +model-prompt internal/session/jobs.go "— this already happened: relay it if it matters, never re-run it and never poll for it." +model-prompt internal/session/tools_capabilities.go "A refusal is the person's own machine answering and not an error to work around: relay it exactly as " +model-prompt internal/session/tools_floor.go "tell (with item) passes the person's words to that job's main agent, gives it one turn of its own conversation, and answers what it said, for you to relay. Use it only when the person asks in this turn; the turn is charged to the job's budget and is stopped after " +other-feature cmd/codeaf/pool.go "CODEAF_MODEL_POOL_PUBLIC_KEY does not decode (set it to the base64 Ed25519 public key of your relay, or clear it)" +other-feature cmd/codeaf/pool.go "json:\"relay,omitempty\"" +other-feature cmd/codeaf/pool.go "json:\"relay_url\"" +other-feature cmd/codeaf/pool.go "models.pool.public_key does not decode (set it to the base64 Ed25519 public key of your relay, or clear it)" +other-feature cmd/codeaf/pool.go "relay %s · %s" +other-feature cmd/codeaf/pool.go "relay: not read (model_pool off)" +other-feature cmd/codeaf/pool.go "relay: reachable · index unchanged, version %d" +other-feature cmd/codeaf/pool.go "relay: reachable · index version %d" +other-feature cmd/codeaf/pool.go "relay: unreachable (%s) · mirror: reachable · index version %d" +other-feature cmd/codeaf/pool.go "relay: unreachable (%s) · mirror: unreachable (%s) · reading %s" +other-feature internal/config/settings.go "CODEAF_MODEL_POOL_RELAY_URL" +other-feature internal/pool/index/cmd/seedgen/main.go " (%d lines in the file, %d from the relay)\n" +other-feature internal/pool/index/cmd/seedgen/main.go "relay: %v; mirror: %v" +other-feature internal/pool/index/cmd/seedgen/main.go "seedgen: %s and %s are what the relay would write\n" +other-feature internal/pool/index/cmd/seedgen/main.go "seedgen: %s is not what the relay would write\n" +other-feature internal/pool/index/cmd/seedgen/main.go "seedgen: the file is not what the relay would write" +other-feature internal/pool/index/cmd/seedgen/main.go "the relay's index address" +other-feature internal/pool/poolcfg/poolcfg.go "CODEAF_MODEL_POOL_RELAY_URL" +other-feature internal/tui3/settings.go "trusts the key built into codeaf; set it to read a relay of your own." +server cmd/codeaf-relay-admin/main.go "CODEAF_RELAY_ADMIN_KEY" +server cmd/codeaf-relay-admin/main.go "codeaf-relay-admin" +server cmd/codeaf-relay-admin/main.go "codeaf/relay-admin/v1\n" +server cmd/codeaf-relay-admin/main.go "relay answer does not match the request" +server cmd/codeaf-relay-admin/main.go "relay answer is too large" +server cmd/codeaf-relay-admin/main.go "relay answered HTTP %d with an unreadable answer" +server cmd/codeaf-relay-admin/main.go "relay must be prod, staging, dev or an HTTP URL" +server cmd/codeaf-relay-admin/main.go "relay name or URL" +server cmd/codeaf-relay-admin/main.go "relay refused: %s (HTTP %d)" +server cmd/codeaf-relay-admin/main.go "relay request failed: " +server cmd/codeaf-relay-admin/main.go "relay" +server cmd/codeaf-relay-admin/main.go "usage: codeaf-relay-admin approve|revoke [--relay prod|staging|dev|] [--key ], or public-key [--key ]" +server cmd/codeaf-release/main.go "codeaf-release — resolve release tags and channel retention\n\n next --channel stable|rc [--component patch|minor|major]\n Read existing tags from stdin and print the next semver tag.\n next --channel dev|staging --sha --date YYYYMMDD\n Print the tag for one channel build.\n kind \n Print stable, rc, dev, staging, or other.\n prune --channel dev|staging\n Read lines and print expired tags.\n service [--url ] | relay-url --channel stable|rc|staging|dev\n Check a live relay's capabilities, or print a channel's hosted URL.\n promotion-plan|promotion-decision|promotion-recheck|promotion-release|promotion-published|promotion-jobs|promotion-push-error|promotion-message\n Plan, check, and report the staging promotion. See docs/rules/promotion.md.\n" +server cmd/codeaf-release/main.go "relay-url" +server cmd/codeaf-release/service.go "could not check the relay at %s: %w" +server cmd/codeaf-release/service.go "relay-url takes --channel " +server cmd/codeaf-release/service.go "service takes only --url " +server cmd/codeaf-release/service.go "the relay at %s must be updated before this build ships; it does not promise %s" +server cmd/codeaf-release/service.go "the relay at %s promises everything this build needs\n" +server cmd/codeaf/app_chatread.go "The relay can't be reached, so this chat can't be read right now." +server cmd/codeaf/app_notes.go "This computer can't reach your relay right now, so the message didn't go. Send it again once it's back." +server cmd/codeaf/app_notes.go "This relay can't carry a message to another computer yet. Move the chat here to write to it." +server cmd/codeaf/chatv3.go "--host reaches a machine over ssh and --at reaches one through the relay: name one or the other, not both" +server cmd/codeaf/chatv3_at.go " to your relay" +server cmd/codeaf/chatv3_at.go ", ~/.codeaf/v3/remote/relay, then the address this machine syncs through" +server cmd/codeaf/chatv3_at.go "no relay is set up on this machine, so there is nowhere to be reachable from — set " +server cmd/codeaf/chatv3_at.go "relay" +server cmd/codeaf/chatv3_at.go "the relay to be reachable through; empty reads " +server cmd/codeaf/main.go "relay" +server cmd/codeaf/pair.go "relay" +server cmd/codeaf/pair.go "the relay to pair through; empty is the one this device already uses" +server cmd/codeaf/pairroute.go "could not keep the pairing relay address, so nothing was sent: %w" +server cmd/relay/main.go "relay:" +server internal/appwire/chats.go "sync.relay" +server internal/appwire/sync.go "json:\"relay,omitempty\"" +server internal/atlas/frame.go "relay / hosted" +server internal/atlas/pairing.go "Add machine B with a link and a 4-digit check. No account is needed. The relay only sees sealed boxes." +server internal/atlas/pairing.go "Frames are XChaCha20-Poly1305 ciphertext; the relay never sees plaintext." +server internal/atlas/pairing.go "HostedRelayURL" +server internal/atlas/pairing.go "Opens the connection to the relay, signs requests, seals the vault with chacha20poly1305, follows the directory (\"running on A\"), and runs Continuer.Take for 'move here'." +server internal/atlas/pairing.go "POST /v1/dir/requests/{code}/approve (signed); relay writes the Device record" +server internal/atlas/pairing.go "Plaintext files only ever exist on the machines, never on the relay" +server internal/atlas/pairing.go "The default hosted relay selected per release channel in internal/syncsetup/relayurl.go: a Cloudflare Worker with Durable Objects and R2. It holds the directory, the encrypted blobs and pairing requests, and it cannot decrypt any of them." +server internal/atlas/pairing.go "The grant is sealed to B's x25519 key, so the relay only sees an opaque box" +server internal/atlas/pairing.go "The same service, self-hosted: `codeaf relay` or cmd/relay. It keeps one SQLite directory and one blob folder per identity, logs only ids and byte counts, and forwards remote-engine bytes without reading them." +server internal/atlas/pairing.go "`codeaf devices` and /devices list devices and show which are online. You can revoke or rename one. The relay refuses a revoked device, and the other devices hear about it through the directory watch." +server internal/atlas/pairing.go "cmd/relay/main.go" +server internal/atlas/pairing.go "codeaf relay" +server internal/atlas/pairing.go "docs/relay.md" +server internal/atlas/pairing.go "hosted relay" +server internal/atlas/pairing.go "internal/relay/relay.go" +server internal/atlas/pairing.go "internal/relayserve/main.go" +server internal/atlas/pairing.go "internal/relayserve/namespaces.go" +server internal/atlas/pairing.go "internal/relayserve/service.go" +server internal/atlas/pairing.go "internal/syncsetup/relayurl.go" +server internal/atlas/pairing.go "relay/hosted/src/limits.js" +server internal/atlas/pairing.go "relay/hosted/src/routes.js" +server internal/atlas/pairing.go "selfrelay" +server internal/blobstore/wire.go "relay_admission_full" +server internal/chatlist/copy.go "sync is off: set CODEAF_SYNC_URL to your relay's address" +server internal/chatlist/copy.go "the relay did not answer in time" +server internal/chatlist/copy.go "the relay is not answering" +server internal/chatlist/liveview.go "live · relay" +server internal/clusterctl/control.go "this relay does not offer cluster leadership yet; your saved chats are still here" +server internal/clusterstate/membership.go "this cluster has reached its enrollment limit; remove a joined computer or ask the relay operator for capacity" +server internal/config/settings.go "CODEAF_RELAY" +server internal/config/settings.go "CODEAF_RELAY_ADMIN_KEY" +server internal/config/settings.go "relay" +server internal/devbox/devbox.go "the pairing relay changed while setting up the box" +server internal/directory/client.go " waits for a relay update; all else works, so close it there and move it here" +server internal/directory/client.go "directory: this relay is too old for that" +server internal/directory/directorytest/pairing.go "PutDeviceIgnoresRelayFields" +server internal/directory/directorytest/presencecases.go "the legacy window is 75 s of the relay's own clock; the in-process relay proves it on a fake clock" +server internal/directory/directorytest/watchcases.go "the relay keeps the default cap; CapIsOneThousand covers it" +server internal/directory/directorytest/watchcases.go "the relay was built with a lowered cap; CapRefusesBeyond covers it" +server internal/directory/export.go "codeaf: directory upgraded; use a current relay build" +server internal/directory/rotation.go "directory: grace period outside what this relay accepts" +server internal/directory/wire.go "relay_admission_full" +server internal/dirwatch/stream.go "dirwatch: the relay stopped hearing this socket" +server internal/dirwatch/stream.go "dirwatch: this relay has no watch route" +server internal/executor/gated.go "couldn't confirm taking this chat back from the relay; try again" +server internal/factory/agentfield/client.go "/relay" +server internal/factory/agentfield/client.go "/relay/ack" +server internal/filesdoor/serve.go "filesdoor: a door needs a relay address that looks like https://relay.example.com" +server internal/filesdoor/serve.go "relay" +server internal/livedoor/direct.go "relay" +server internal/livedoor/direct.go "relay-only" +server internal/livedoor/link.go "%w: no relay tunnel to signal on" +server internal/pair/errors.go "%s is not connected to the relay right now — run `codeaf serve` on that machine" +server internal/pair/errors.go "no relay is set up on this machine, so --at has nowhere to look for %s — set %s to a relay, or reach that machine with --host over ssh" +server internal/pair/errors.go "no relay is set, so there is nowhere to pair through: set CODEAF_SYNC_URL to its address, or pass --via
" +server internal/pair/errors.go "pair: no relay is configured" +server internal/pair/errors.go "sync is off (CODEAF_SYNC_URL=off); pairing needs the relay" +server internal/pair/errors.go "that relay is too old for pairing" +server internal/pair/errors.go "the relay at %s syncs chats but does not connect machines — run your own with `codeaf relay` and set %s to it" +server internal/pair/errors.go "the relay is turning connections away right now — try again in a minute" +server internal/pair/merge.go "relay" +server internal/pair/serve.go " to your relay" +server internal/pair/serve.go "no relay is set up on this machine, so there is nowhere to be reachable from — set " +server internal/pair/serve.go "the relay is turning registrations away right now — waiting before trying again" +server internal/pair/service.go "CODEAF_RELAY" +server internal/pair/service.go "relay" +server internal/pairbox/box.go "pairbox: the relay is full" +server internal/pairbox/http.go "pairbox: that relay is too old for pairing" +server internal/pairbox/http.go "pairbox: the relay answered %d" +server internal/pairbox/pairboxtest/run.go "RelayFull" +server internal/relay/client.go "%q is not a relay URL — it looks like https://relay.example.com" +server internal/relay/client.go "connections open, which is as many as the relay carries at once" +server internal/relay/client.go "not a relay door" +server internal/relay/client.go "relay: %q is not a dial class — the classes are %q and %q" +server internal/relay/client.go "relay: cannot be reached" +server internal/relay/client.go "relay: no machine connected under that name" +server internal/relay/client.go "relay: service unavailable" +server internal/relay/client.go "relay: that name is already connected" +server internal/relay/client.go "relay: that service does not offer machine connections" +server internal/relay/client.go "relay: too many connections from here" +server internal/relay/client.go "the relay at %s refused this connection (%d) — check the address it was given" +server internal/relay/handshake.go "aforge relay registration v1" +server internal/relay/handshake.go "the relay refused this machine's registration" +server internal/relay/handshake.go "the relay sent a challenge this build cannot answer" +server internal/relay/mux.go "relay: a machine opened a stream, which only the relay may do" +server internal/relay/mux.go "relay: frame claims %d bytes, over the %d-byte limit" +server internal/relay/mux.go "relay: frame of %d bytes is over the %d-byte limit" +server internal/relay/mux.go "that machine already has %d connections open, which is as many as the relay carries at once" +server internal/relay/mux.go "the connection to the relay ended" +server internal/relay/name.go "aforge relay name\x00" +server internal/relay/relay.go "aforge-relay/1" +server internal/relay/server.go "not a relay door" +server internal/relay/server.go "relay: that client wrote before the upgrade was answered" +server internal/relay/server.go "relay: this server does not hand out connections" +server internal/relay/server.go "that machine is already connected to the relay under this name" +server internal/relay/transport.go "relay: that relay only speaks the raw upgrade" +server internal/relayserve/main.go "codeaf relay is listening on " +server internal/relayserve/main.go "relay" +server internal/relayserve/main.go "relay: %w" +server internal/relayserve/main.go "usage: codeaf relay [--listen host:port] [--store path]\n\nRun your own relay.\n\n --listen host:port address to listen on (default :8787)\n --store path keep your devices and saved chats here; empty connects machines only\n --quiet do not log arrivals, departures or requests\n --status=false turn off the service status endpoint\n --trust-proxy use the caller address supplied by a trusted proxy" +server internal/relayserve/namespaces.go "relayserve: %q is not an identity id" +server internal/relayserve/unavailable.go "relay unavailable phase=%s cause=%q" +server internal/rotate/journal.go "json:\"handoff_relay,omitempty\"" +server internal/rotate/rotate.go "this relay cannot replace an identity: it is too old for that" +server internal/rotate/steps.go "rotate: the new relay does not hold the vault" +server internal/rotate/steps.go "rotate: the new relay has chat %s at %q, not %q" +server internal/rotate/steps.go "rotate: the new relay lacks the newest turn of chat %s" +server internal/syncsetup/cluster.go "the relay" +server internal/syncsetup/firstrun.go "), a relay that only ever sees ciphertext; turn that off with CODEAF_SYNC_URL=off, or use your own with CODEAF_SYNC_URL=." +server internal/syncsetup/livetransfer.go "blind pass-through: sending shared chats to the relay: %v" +server internal/syncsetup/notes.go "this computer is not listed by the relay yet" +server internal/syncsetup/notes.go "this relay cannot carry a message to another computer yet" +server internal/syncsetup/storage.go "json:\"relay\"" +server internal/syncwords/errors.go "the relay at " +server internal/syncwords/words.go " — if that is your own relay, start it there with codeaf relay" +server internal/syncwords/words.go "asking the relay at " +server internal/syncwords/words.go "relay: %s (%s)" +server internal/syncwords/words.go "saved here; it reaches your other devices when the relay at %s answers" +server internal/syncwords/words.go "the relay at " +server internal/syncwords/words.go "the relay is not answering; this chat keeps working here and catches up when it is back" +server internal/taskcopy/cold_prototype.go "cold task %s has no matching prepared relay artifact" +server internal/taskdoor/serve.go "taskdoor: a door needs a relay, roster and executor" +server internal/tui3/pair_firstrun.go "use your own relay: codeaf pair --relay " +storage cmd/codeaf/app_notes.go "Relay storage is off for this account, so a message can't wait for another computer. Move the chat here to write to it." +storage cmd/codeaf/identity_rotate.go ".\nrelay storage is off; your chats stay on this computer.\n" +storage cmd/codeaf/main.go " minutes\n after. --max-hours wins.\n CODEAF_MAX_COST the same ceiling in dollars. --max-cost wins. Either one\n alone is a budget; without one, --yolo is only the\n approval posture it has always been.\n CODEAF_PREAUTHORIZE_SPEND\n 1 spends past the day's limit without stopping a\n headless run to ask\n CODEAF_SYNC_URL relay for your chats; off disables syncing\n CODEAF_MOVE_FILES_FIRST=1\n wait for all workspace files before opening a moved chat\n CODEAF_PASSTHROUGH\n off (also 0, false, no) turns blind pass-through off:\n while hosted relay storage is off, a chat then stays on\n the computer that has it instead of passing straight\n through the relay to a paired computer that is\n also running codeaf (default on)\n CODEAF_RELAY relay override for pairing and remote connections\n CODEAF_HOME the whole state root — journal, workspace, CAS, craft,\n profiles, catalog, skills (default ~/.codeaf). Move it\n to run a disposable store that touches nothing of yours.\n CODEAF_NO_UPDATE_CHECK\n 1 skips the launch check and the update a released\n codeaf installs as it opens; /update and codeaf\n update still work.\n CODEAF_PROFILE_DIR where measured behaviour is kept (default CODEAF_HOME)\n CODEAF_CALL_LOG the model-call log (default /logs/calls.jsonl).\n \"off\" writes nothing; any other value is the file to\n write.\n CODEAF_CALL_LOG_BODIES=1\n also record each call's whole request and response —\n your prompts included. Off by default, and for one run\n at a time.\n CODEAF_GITHUB_LOG a file: one line per GitHub request, by endpoint and\n status, with the rate limit GitHub reported. Names,\n paths and tokens are not written. Off by default.\n CODEAF_TELEMETRY on (default). off turns the anonymous usage counts off;\n docs/TELEMETRY.md in the repository says what they are,\n DO_NOT_TRACK=1 does the same, and so does the telemetry\n switch in the chat's /settings\n CODEAF_TELEMETRY_ENDPOINT\n where the usage counts go\n (default https://agentfield.ai/api/oss/codeaf/telemetry);\n set to empty to turn them off entirely\n DO_NOT_TRACK=1 the ecosystem's own opt-out word, honoured as if it were\n CODEAF_TELEMETRY=off\n\nThe user-facing knobs above — budgets, rhythm, the document reader, the vision\nand media slots — are also the " +storage internal/blobstore/store.go "blobstore: relay storage: %w: %w" +storage internal/blobstore/wire.go "relay_storage_full" +storage internal/chatlist/copy.go "chats move between your computers by blind pass-through while both run codeaf; keys, memories, teams and preferences wait for relay storage (request access in Settings under Devices)" +storage internal/chatlist/copy.go "relay storage is off for this account, so chats stay on this computer; request access in Settings under Devices" +storage internal/directory/wire.go "relay_storage_full" +storage internal/rotate/steps.go "relay storage is off; chats stay on your computers" +storage internal/syncsetup/storage.go "Please turn on relay storage for my account.\n\nRequest code: " +storage internal/syncsetup/storage.go "relay storage access: " +storage internal/syncwords/words.go "a message to a chat on another computer waits for relay storage, which is off for this account; move the chat here to write to it" +storage internal/syncwords/words.go "cannot move this chat here while relay storage is off because this computer is missing saved turns; your local turns stay here" +storage internal/syncwords/words.go "saved here; relay storage is off for this account, so it stays on this computer" +storage internal/syncwords/words.go "this chat is only on the computer that shares it, and blind pass-through is switched off here; switch it back on (CODEAF_PASSTHROUGH) or turn on relay storage to move it here" +storage internal/taskdoor/copy.go "task copies need private storage and a relay blob store" +storage internal/tui3/settings_devices.go "relay storage" +storage internal/wireauth/wireauth.go "wireauth: relay storage full" +storage internal/wireauth/wireauth.go "wireauth: relay storage off" diff --git a/internal/wordlaw/wordlaw_test.go b/internal/wordlaw/wordlaw_test.go new file mode 100644 index 0000000000..37038ea29d --- /dev/null +++ b/internal/wordlaw/wordlaw_test.go @@ -0,0 +1,583 @@ +// Package wordlaw is THE WORDS LAW, and it is a package of nothing but the law. +// +// Three spellings were retired on 2026-11-23, and a string a person reads may +// not bring any of them back: +// +// - "Continue here" was the label for carrying a chat from another computer to +// this one. The act has one verb, "Move here", wherever a person meets it. +// - "sync service" was the TUI's name for the server. People call it the relay. +// - "sync storage" was the name of the switch that lets the relay keep sealed +// copies. It is "relay storage". +// +// And one word is fenced: "relay" names the server and its storage switch, and +// NOTHING ELSE. It is never the name of a feature or something a person does (a +// person does not "relay a chat"; they move it, or open it live). Because a +// count of strings cannot tell a server from a feature, the second half of the +// law is a ledger: every string in the program that says "relay" is listed in +// relay_words.golden with a class a person gave it, and a new one fails until a +// person classifies it. The chat manual's own count of the word is a ratchet +// that may only fall. +// +// The law reads every string literal in the program's own sources, because a +// person reads the string and not the constant it hangs from, and it fails +// naming the file, the line and the spelling. Comments are not strings and are +// not read here. Test files are not read either: a test that asserts a person- +// facing string asserts the NEW spelling. The two manual corpora are read as +// text, wrapped lines and all, because a sentence the manual breaks across two +// lines is still one sentence. +// +// IT LIVES IN ITS OWN PACKAGE FOR THE SAME REASON iconlaw DOES: a word is not one +// surface's law, and a list of roots here is how a new surface joins it. It +// imports go/ast, so `make test-laws` finds it and runs it on every pull request. +// +// To classify a new string, or to lower the manual's baseline after a page lost +// some mentions: +// +// go test ./internal/wordlaw -run Relay -update +// +// and read the diff of the two .golden files before committing it. +package wordlaw + +import ( + "bufio" + "flag" + "fmt" + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "regexp" + "sort" + "strconv" + "strings" + "testing" +) + +var update = flag.Bool("update", false, "rewrite relay_words.golden and relay_manual.golden from the tree") + +// goRoots are the trees whose string literals a person can read: the commands +// and every package under internal. third_party is vendored code and never ours. +var goRoots = []string{"../../cmd", ".."} + +// corpora are the two Markdown manuals a person (or the model, on a person's +// behalf) reads. The resident's pages are a separate corpus and say none of this, +// and they are held to the same law so that stays true. +var corpora = []string{"../manual/chat", "../manual/pages"} + +// workerRoot is the hosted relay's own source, which is JavaScript. +const workerRoot = "../../relay/hosted/src" + +// legacyHeading is THE ONE PLACE "continue here" may be written in the manual. +// Everything a person might ask in the old words reaches the Move page through +// this heading, and nowhere else spells the label: a section that offered it +// would send people looking for a button that is gone. +const ( + legacyHeadingPage = "continuing-a-chat-on-another-computer.md" + legacyHeading = `## Move here: also called "continue here", "take over" or "continue on this machine"` +) + +// kept are the few Go literals that may still carry a retired spelling, each +// with the words it may carry. A search alias is typed by a person and never +// drawn, so it is how somebody who remembers the old label still finds the row +// it named; config.LegacyWords is the one slice that holds them. +var kept = map[string][]string{ + "internal/config/settings_presentation.go": {"continue here", "sync storage"}, +} + +// continueHere matches the retired label and the sentences that wrapped it: +// `Continue here`, `continue it here`, `Continue this chat here?`, `continue the +// chat here`, `continuing here…` and `Continue %s's latest chat here?`. It does +// not match "a task that cannot be continued here", which is the task verb and a +// different feature. +var continueHere = spaced(`\bcontinu(?:e|ing) (?:(?:this|the) chat |it )?here\b|\bcontinue \S{1,30}'s latest chat here\b`) + +// syncWords matches the two retired names for the server and its storage. +var syncWords = spaced(`\bsync service\b|\bsync storage\b`) + +// relayAsAFeature matches "relay" used as a verb or as the name of a feature. A +// server plural ("both relays") and the server's own nouns are fine; a person +// never "relays a chat", and there is no "relay mode". +var relayAsAFeature = spaced(`\b(?:relayed|relaying|relay mode|relay feature|relays? (?:a|the|your) (?:chat|chats|message|messages|answer|conversation)|relay (?:a|your) (?:chat|chats|message|messages))\b`) + +// spaced compiles a case-insensitive pattern whose spaces match any run of +// whitespace, so a phrase the manual wraps across two lines is still found. +func spaced(pattern string) *regexp.Regexp { + return regexp.MustCompile(`(?i)` + strings.ReplaceAll(pattern, " ", `\s+`)) +} + +// goString is one string literal in the program and where it stands. +type goString struct { + path string // repository-relative, forward slashes + line int + text string +} + +// programStrings reads every non-test Go file under goRoots and returns each +// string literal except an import path, which is a name for the compiler and not +// a sentence for a person. +func programStrings(t *testing.T) []goString { + t.Helper() + var out []goString + files := 0 + for _, root := range goRoots { + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + switch d.Name() { + case "testdata", "third_party", "wordlaw": + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { + return nil + } + files++ + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, path, nil, 0) + if err != nil { + t.Errorf("%s: %v", path, err) + return nil + } + rel := repoRelative(path) + ast.Inspect(file, func(n ast.Node) bool { + switch lit := n.(type) { + case *ast.ImportSpec: + return false + case *ast.BasicLit: + if lit.Kind != token.STRING { + return true + } + text, err := strconv.Unquote(lit.Value) + if err != nil { + return true + } + out = append(out, goString{path: rel, line: fset.Position(lit.Pos()).Line, text: text}) + } + return true + }) + return nil + }) + if err != nil { + t.Fatal(err) + } + } + if files < 500 { + t.Fatalf("the law read only %d Go files; its roots no longer reach the program", files) + } + return out +} + +// page is one Markdown file of a manual corpus. +type page struct { + corpus string // "chat" or "pages" + name string // file name, e.g. "home.md" + text string +} + +func manualPages(t *testing.T) []page { + t.Helper() + var out []page + for _, root := range corpora { + entries, err := os.ReadDir(root) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".md") { + continue + } + raw, err := os.ReadFile(filepath.Join(root, entry.Name())) + if err != nil { + t.Fatal(err) + } + out = append(out, page{corpus: filepath.Base(root), name: entry.Name(), text: string(raw)}) + } + } + if len(out) < 90 { + t.Fatalf("the law read only %d manual pages; its roots no longer reach the corpora", len(out)) + } + return out +} + +// lineOf is the 1-based line of a byte offset. +func lineOf(text string, offset int) int { return strings.Count(text[:offset], "\n") + 1 } + +// lineAt is the text of the line holding a byte offset. +func lineAt(text string, offset int) string { + start := strings.LastIndex(text[:offset], "\n") + 1 + end := strings.Index(text[offset:], "\n") + if end < 0 { + return text[start:] + } + return text[start : offset+end] +} + +func allowed(rel, word string) bool { + for _, w := range kept[rel] { + if w == word { + return true + } + } + return false +} + +// TestSyncServiceIsGone is the law for the two names of the server and its +// storage that are retired: Go strings, both manuals and the hosted relay's own +// JavaScript. The manual's three old-name headings are the one exception, and +// they are an exception because a question in the old words reaches a page by its +// heading: a heading naming both "relay storage" and "sync storage" is how +// somebody who remembers the old switch still finds the page that answers. +func TestSyncServiceIsGone(t *testing.T) { + for _, s := range programStrings(t) { + lower := strings.ToLower(s.text) + for _, word := range []string{"sync service", "sync storage"} { + if strings.Contains(lower, word) && !allowed(s.path, word) { + t.Errorf("%s:%d spells %q in a string a person can read; the server is the relay and its switch is relay storage", s.path, s.line, word) + } + } + } + for _, p := range manualPages(t) { + for _, at := range syncWords.FindAllStringIndex(p.text, -1) { + line := lineAt(p.text, at[0]) + word := strings.ToLower(strings.Join(strings.Fields(p.text[at[0]:at[1]]), " ")) + if word == "sync storage" && strings.HasPrefix(line, "## ") && strings.Contains(strings.ToLower(line), "relay storage") { + continue + } + t.Errorf("manual/%s/%s:%d says %q; the server is the relay and its switch is relay storage", p.corpus, p.name, lineOf(p.text, at[0]), word) + } + } + err := filepath.WalkDir(workerRoot, func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(path, ".js") { + return err + } + raw, err := os.ReadFile(path) + if err != nil { + return err + } + for _, at := range syncWords.FindAllStringIndex(string(raw), -1) { + t.Errorf("%s:%d says %q; the server is the relay", repoRelative(path), lineOf(string(raw), at[0]), strings.ToLower(string(raw[at[0]:at[1]]))) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +// TestContinueHereSurvivesOnlyInOneManualHeading is the law for the old label. +// Go strings may carry it only in the Settings search alias list; the manual may +// carry it only in the one heading that answers a question asked in the old +// words, and that heading must still stand. +func TestContinueHereSurvivesOnlyInOneManualHeading(t *testing.T) { + for _, s := range programStrings(t) { + if found := continueHere.FindString(s.text); found != "" && !allowed(s.path, strings.ToLower(found)) { + t.Errorf("%s:%d spells %q in a string a person can read; say \"Move here\" instead", s.path, s.line, found) + } + } + headings := 0 + for _, p := range manualPages(t) { + text := p.text + if p.corpus == "chat" && p.name == legacyHeadingPage { + headings += strings.Count(text, "\n"+legacyHeading+"\n") + // BLANK THE HEADING RATHER THAN CUT IT, so every later line number is + // still the line number in the file. + text = strings.ReplaceAll(text, "\n"+legacyHeading+"\n", "\n"+strings.Repeat(" ", len(legacyHeading))+"\n") + } + for _, at := range continueHere.FindAllStringIndex(text, -1) { + t.Errorf("manual/%s/%s:%d offers %q; the act is \"Move here\", and the old words live only in the heading %q", + p.corpus, p.name, lineOf(text, at[0]), strings.Join(strings.Fields(text[at[0]:at[1]]), " "), legacyHeading) + } + } + if headings != 1 { + t.Errorf("%s must hold the heading %s exactly once, and holds it %d times: a question in the old words reaches the Move page through it", legacyHeadingPage, legacyHeading, headings) + } +} + +// The relay classes. A string that says "relay" is one of these. +const ( + classServer = "server" // the server a person runs or reaches: its address, its refusals, its commands + classStorage = "storage" // the switch that lets it keep sealed copies + classFeature = "other-feature" // a different feature that happens to say the word: today, only the model pool + classPrompt = "model-prompt" // an instruction to the model that uses the plain verb ("relay it"); not a name for anything + relayGolden = "relay_words.golden" + manualGolden = "relay_manual.golden" + goldenComment = "#" +) + +// modelPoolPaths are the only places "relay" may name something other than the +// server: the model pool has a relay of its own (a different feature, with its +// own address and its own key), and it is out of this rename's scope. +var modelPoolPaths = []string{ + "cmd/codeaf/pool.go", + "internal/pool/", + "internal/config/settings.go", + "internal/tui3/settings.go", +} + +// modelPromptPaths are the only places the plain verb may stand in an +// instruction to the model. These sentences are read by the model, not by a +// person, and the session package pins their text in its law registry, so they +// are reworded in a prompt wave of their own rather than inside a words pass; +// they sit in the ledger so that a fourth one fails the build. +var modelPromptPaths = []string{"internal/session/"} + +func isModelPromptPath(path string) bool { + for _, p := range modelPromptPaths { + if strings.HasPrefix(path, p) { + return true + } + } + return false +} + +func isModelPoolPath(path string) bool { + for _, p := range modelPoolPaths { + if path == p || (strings.HasSuffix(p, "/") && strings.HasPrefix(path, p)) { + return true + } + } + return false +} + +// relayKey is the identity of one ledger line: the file and the text, never the +// line number, so an edit above a string does not move it. +func relayKey(path, text string) string { return path + "\t" + strconv.Quote(text) } + +// readGolden parses a .golden file into its lines, skipping comments. +func readGolden(t *testing.T, name string) []string { + t.Helper() + f, err := os.Open(name) + if err != nil { + if os.IsNotExist(err) { + return nil + } + t.Fatal(err) + } + defer f.Close() + var lines []string + scanner := bufio.NewScanner(f) + scanner.Buffer(make([]byte, 1<<20), 1<<20) + for scanner.Scan() { + if line := scanner.Text(); line != "" && !strings.HasPrefix(line, goldenComment) { + lines = append(lines, line) + } + } + if err := scanner.Err(); err != nil { + t.Fatal(err) + } + return lines +} + +func writeGolden(t *testing.T, name, header string, lines []string) { + t.Helper() + sort.Strings(lines) + body := header + "\n" + strings.Join(lines, "\n") + "\n" + if err := os.WriteFile(name, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +// TestNoPersonFacingStringNamesRelayAsAFeature holds the fence round the word +// "relay". Contract: "relay" names the server and its storage switch. +// +// - Every Go string that says it is in relay_words.golden with a class. A new one +// fails until a person has said which: server, storage, or (only in the model +// pool's own files) other-feature, or (only in the session package's prompts) +// model-prompt, the plain verb in an instruction the model reads. +// - A line in the ledger whose string is gone fails too, so the ledger is a +// picture of the program and not a pile. +// - No chat manual page uses "relay" as a verb or the name of a feature. +func TestNoPersonFacingStringNamesRelayAsAFeature(t *testing.T) { + type found struct { + path string + line int + text string + } + current := map[string]found{} + for _, s := range programStrings(t) { + if strings.Contains(strings.ToLower(s.text), "relay") { + key := relayKey(s.path, s.text) + if _, seen := current[key]; !seen { + current[key] = found{s.path, s.line, s.text} + } + } + } + classes := map[string]string{} // key -> class + for _, line := range readGolden(t, relayGolden) { + parts := strings.SplitN(line, "\t", 2) + if len(parts) != 2 { + t.Fatalf("%s: a ledger line is `classpathquoted text`, not %q", relayGolden, line) + } + classes[parts[1]] = parts[0] + } + + if *update { + var lines []string + for key, f := range current { + class := classes[key] + if class == "" { + class = classServer + if strings.Contains(strings.ToLower(f.text), "storage") { + class = classStorage + } + } + lines = append(lines, class+"\t"+key) + } + writeGolden(t, relayGolden, `# Every non-test Go string in cmd and internal that says "relay", with the class a person gave it. +# server = the server (its address, commands, refusals); storage = the switch that lets it keep sealed copies; +# other-feature = a different feature that says the word (only the model pool's own files). +# model-prompt = an instruction to the model using the plain verb ("relay it"), only in internal/session; to be reworded. +# Regenerate with: go test ./internal/wordlaw -run Relay -update Then read the diff. +# Format: classpathquoted text`, lines) + return + } + + var problems []string + for key, f := range current { + class, ok := classes[key] + switch { + case !ok: + problems = append(problems, fmt.Sprintf("%s:%d says \"relay\" and nobody has classified it: %s\n\t\tRun `go test ./internal/wordlaw -run Relay -update`, then read the diff and set its class (server, storage or other-feature).", f.path, f.line, strconv.Quote(f.text))) + case class != classServer && class != classStorage && class != classFeature && class != classPrompt: + problems = append(problems, fmt.Sprintf("%s:%d is classed %q; the classes are %s, %s, %s and %s", f.path, f.line, class, classServer, classStorage, classFeature, classPrompt)) + case class == classFeature && !isModelPoolPath(f.path): + problems = append(problems, fmt.Sprintf("%s:%d is classed %s, but \"relay\" names a feature only in the model pool's files (%s); it names the server and its storage switch", f.path, f.line, classFeature, strings.Join(modelPoolPaths, ", "))) + case class == classPrompt && !isModelPromptPath(f.path): + problems = append(problems, fmt.Sprintf("%s:%d is classed %s, but only the session package's prompts (%s) may use \"relay\" as a plain verb; say \"pass it on\" or \"tell the person\"", f.path, f.line, classPrompt, strings.Join(modelPromptPaths, ", "))) + } + } + for key := range classes { + if _, ok := current[key]; !ok { + problems = append(problems, fmt.Sprintf("%s lists a string that is gone: %s\n\t\tRun `go test ./internal/wordlaw -run Relay -update` to drop it.", relayGolden, key)) + } + } + sort.Strings(problems) + for _, p := range problems { + t.Error(p) + } + + for _, p := range manualPages(t) { + for _, at := range relayAsAFeature.FindAllStringIndex(p.text, -1) { + t.Errorf("manual/%s/%s:%d uses %q; relay names only the server and its storage switch, never a feature or something a person does", + p.corpus, p.name, lineOf(p.text, at[0]), strings.Join(strings.Fields(p.text[at[0]:at[1]]), " ")) + } + } +} + +// newPages are the chat manual pages that may appear without a baseline: they +// are written after the ratchet was set, and say what the word means as they go. +var newPages = map[string]bool{ + "remote-control.md": true, +} + +// TestTheRelayWordInTheChatManualOnlyFalls is the ratchet. Contract: the chat +// manual says "relay" for the server in 424 places, and a person reading it +// should meet fewer of them over time, not more. A page's count may fall and may +// not rise; a page with no baseline must be a new page. +// +// `-update` writes the lower of the two for every page that already had a +// baseline, so it can tighten the ratchet and never loosen it, and it adds a page +// that is new. +func TestTheRelayWordInTheChatManualOnlyFalls(t *testing.T) { + counts := map[string]int{} + for _, p := range manualPages(t) { + if p.corpus == "chat" { + counts[p.name] = strings.Count(strings.ToLower(p.text), "relay") + } + } + baseline := map[string]int{} + for _, line := range readGolden(t, manualGolden) { + parts := strings.Split(line, "\t") + n, err := strconv.Atoi(parts[len(parts)-1]) + if len(parts) != 2 || err != nil { + t.Fatalf("%s: a baseline line is `pagecount`, not %q", manualGolden, line) + } + baseline[parts[0]] = n + } + + if *update { + var lines []string + for name, n := range counts { + if old, ok := baseline[name]; ok && old < n { + n = old + } + lines = append(lines, fmt.Sprintf("%s\t%d", name, n)) + } + writeGolden(t, manualGolden, `# How many times each chat manual page says "relay" (any case, any form: relay, relays, relayed). +# A page's count may fall and may not rise. Regenerate with: go test ./internal/wordlaw -run Relay -update +# Format: pagecount`, lines) + return + } + + var names []string + for name := range counts { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + old, ok := baseline[name] + switch { + case !ok && newPages[name]: + case !ok: + t.Errorf("manual/chat/%s says \"relay\" %d times and has no baseline. A page that is not new must be in %s: run `go test ./internal/wordlaw -run Relay -update` and read the diff", name, counts[name], manualGolden) + case counts[name] > old: + t.Errorf("manual/chat/%s says \"relay\" %d times, up from %d. The word names the server; say \"your other computers\", \"live\" or \"relay storage\" where the sentence is about what a person does", name, counts[name], old) + } + } + for name := range baseline { + if _, ok := counts[name]; !ok { + t.Errorf("%s lists manual/chat/%s, which is gone; run `go test ./internal/wordlaw -run Relay -update` to drop it", manualGolden, name) + } + } +} + +// TestTheRetiredPatternsMatchWhatTheyShouldAndNothingElse gives the other tests +// their teeth. A law whose pattern silently stopped matching would pass forever, +// so each spelling the law fences is written down here with a sentence it must +// catch (including one the manual wraps over two lines) and a sentence it must +// leave alone. +func TestTheRetiredPatternsMatchWhatTheyShouldAndNothingElse(t *testing.T) { + for _, tc := range []struct { + name string + pattern *regexp.Regexp + hits []string + misses []string + }{ + {"the old label", continueHere, + []string{"Continue here", "press continue here to resume", "Continue this chat here?", "continue the chat here first", "continue it here", "continuing here…", "Continue tower's latest chat here?", "beside every Continue\nhere"}, + []string{"Move here", "so it cannot be continued here", "a kept run that continues here later", "continue in the working chat", "Continue the plan's remaining steps"}}, + {"the old names for the server and its storage", syncWords, + []string{"the sync service", "Sync storage is off", "hosted sync\nstorage", "SYNC SERVICE"}, + []string{"relay storage", "the relay", "sync space", "your chats sync", "a sync in progress"}}, + {"relay as a feature or an act", relayAsAFeature, + []string{"the node relays the answer", "it relayed your message", "relaying other people's words", "relay mode", "relay your chat", "the Factory manager relays\nthe answer"}, + []string{"both relays", "the relay at tower", "your relay stores sealed text", "a self-hosted relay", "relay storage"}}, + } { + for _, text := range tc.hits { + if !tc.pattern.MatchString(text) { + t.Errorf("%s: the law would miss %q", tc.name, text) + } + } + for _, text := range tc.misses { + if tc.pattern.MatchString(text) { + t.Errorf("%s: the law would wrongly flag %q", tc.name, text) + } + } + } +} + +// repoRelative turns a path found under ../.. or .. into the repository-relative +// spelling the kept and class tables use. +func repoRelative(path string) string { + clean := filepath.ToSlash(filepath.Clean(path)) + clean = strings.TrimPrefix(clean, "../../") + if strings.HasPrefix(clean, "../") { + clean = "internal/" + strings.TrimPrefix(clean, "../") + } + return clean +} diff --git a/relay/hosted/README.md b/relay/hosted/README.md index 89dc2344c9..c2336f4d49 100644 --- a/relay/hosted/README.md +++ b/relay/hosted/README.md @@ -204,6 +204,19 @@ socket stopped answering (a pong is asked for and not given within 5 s) replaces machine whose network dropped comes back before the platform has closed its old socket. A colliding key never replaces an existing registration, silent or live. +A dial may say what it is for in a `Codeaf-Door` request header. `live` is a viewer watching or driving a chat: +it is refused (`429`) once the machine already has `LIVE_STREAMS` (14) streams attached, counting every stream +whoever holds it, so two are always free for `move`, which is held only to `MAX_STREAMS` (16). A dial with no +header, or a value that is neither, is held to 16 exactly as before the header existed, so an older client +behaves as it always did and an older Worker, which never reads the header, behaves as it always did for a +newer one. The class is a claim and not an authentication: it only decides how the machine's streams are +shared, and who may speak on one is settled by the host. A `live` stream also has a breaker (`src/engine/breaker.js`) +that closes it with `1008` if it sustains more than 4 MiB/s over 5 s in either direction, for a host that ignores +the pace it is meant to keep. It is computed when a message arrives. There is no timer and no alarm in a machine +object, and a test pins it, because either would keep an idle live view from hibernating. The two `429`s for a +caller's rate (30 dials and 10 registrations a minute) carry `Retry-After`. A live session adds no stored object and +no field to any record: the only write on the dial path is the stream-id counter, which exists today. + ## Base path A deployment can share a hostname by using a path prefix, such as @@ -258,7 +271,9 @@ npx wrangler deploy --config wrangler.custom.toml | link requests: reads a minute, misses a minute, open polls, per IP | 60, 20, 4 | `429 rate_limited` | | link requests: live in all | 2,000 | `503 full` | | machine doors: surfaces on one machine at once (`MAX_STREAMS`) | 16 | `429` | -| machine doors: dials and registrations a minute, per network at the Worker front (`MACHINE_DIAL_LIMIT`, `MACHINE_REGISTER_LIMIT`) and per machine name in memory | 30, 10 | `429` | +| machine doors: surfaces a dial that sends `Codeaf-Door: live` may leave attached (`LIVE_STREAMS`, against the machine's total, so the last two are kept for `Codeaf-Door: move`; a dial with no class or an unknown one gets all 16) | 14 | `429` | +| machine doors: a live stream's rate, in each direction, before it is cut (`BREAKER_BYTES_PER_SECOND` over `BREAKER_WINDOW_MS`, computed when a message arrives, never from a timer or an alarm) | 4 MiB/s over 5 s | close `1008` | +| machine doors: dials and registrations a minute, per network at the Worker front (`MACHINE_DIAL_LIMIT`, `MACHINE_REGISTER_LIMIT`) and per machine name in memory | 30, 10 | `429`, `Retry-After` | Stored quotas (bytes, objects, frames a day), the stats counts and the per-IP counters live in the identity object's SQLite and survive eviction. A frame the store already holds costs no quota, so a client that resends is never refused diff --git a/relay/hosted/src/engine/breaker.js b/relay/hosted/src/engine/breaker.js new file mode 100644 index 0000000000..df4ed364b2 --- /dev/null +++ b/relay/hosted/src/engine/breaker.js @@ -0,0 +1,34 @@ +// The abuse breaker for a live stream. It is the relay's one answer to a surface that sends more than any live view ever +// does, and it is computed from the clock of the message that arrives: there is NO timer and NO alarm behind it, because +// a timer is exactly what would keep an idle object awake, and an idle live view must cost nothing (room.js). +// +// IT CUTS AND DOES NOT SHAPE. The relay cannot read a byte it carries, so it cannot batch, delay or fold anything: its +// only move is to end the stream, and the host and the viewer pace themselves long before this matters. The number is four +// times the pace a correct host holds, so a correct host never trips it; it exists for a modified one. +import { BREAKER_BYTES_PER_SECOND, BREAKER_WINDOW_MS } from './carrier.js'; + +/** + * Breaker is a leaky bucket that holds BREAKER_WINDOW_MS worth of BREAKER_BYTES_PER_SECOND and drains at that rate, so + * a stream is over its rate when it has sent more than that rate sustained across the window, whether as one burst or as a + * steady flow a little above the line. Its state is two numbers, and it is lost with the object's memory, which only ever + * forgives a stream. + */ +export class Breaker { + #level = 0; + #at = null; + + constructor(perSecond = BREAKER_BYTES_PER_SECOND, windowMs = BREAKER_WINDOW_MS) { + this.perSecond = perSecond; + this.capacity = (perSecond * windowMs) / 1000; + } + + /** charge counts `bytes` arriving at `now` (milliseconds) and answers true once the stream is over its rate. */ + charge(bytes, now) { + if (this.#at !== null && now > this.#at) { + this.#level = Math.max(0, this.#level - ((now - this.#at) * this.perSecond) / 1000); + } + this.#at = this.#at === null ? now : Math.max(this.#at, now); + this.#level += bytes; + return this.#level > this.capacity; + } +} diff --git a/relay/hosted/src/engine/carrier.js b/relay/hosted/src/engine/carrier.js index 77f000d8dd..813133cc74 100644 --- a/relay/hosted/src/engine/carrier.js +++ b/relay/hosted/src/engine/carrier.js @@ -12,6 +12,12 @@ const LABEL = new TextEncoder().encode('aforge relay registration v1'); // legac // The tuning of internal/relay/relay.go, kept in lockstep under the same names. export const MAX_PAYLOAD = 1 << 17; // relay.MaxPayload export const MAX_STREAMS = 16; // relay.MaxStreams +export const LIVE_STREAMS = 14; // relay.LiveStreams: how many streams a live dial may leave attached, whoever holds the rest +export const HEADER_DOOR = 'codeaf-door'; // relay.HeaderDoor +export const DOOR_LIVE = 'live'; // relay.DoorLive +export const DOOR_MOVE = 'move'; // relay.DoorMove +export const BREAKER_BYTES_PER_SECOND = 4 << 20; // relay.BreakerRate +export const BREAKER_WINDOW_MS = 5000; // relay.BreakerWindow export const HANDSHAKE_MS = 20000; // relay.HandshakeWithin export const PROBE_MS = 5000; // relay.ProbeWithin export const DIALS_PER_MINUTE = 30; // relay.DialsPerMinute (and MACHINE_DIAL_LIMIT in wrangler.toml) @@ -19,13 +25,39 @@ export const REGISTRATIONS_PER_MINUTE = 10; // relay.RegistrationsPerMinute (and export const TOO_MANY_DIALS = 'too many connections from here — wait a minute'; export const TOO_MANY_REGISTRATIONS = 'too many registrations from here — wait a minute'; +/** TOO_MANY_LIVE is a live dial turned away while the last streams are kept for moving a chat. */ +export const TOO_MANY_LIVE = `that machine already has ${LIVE_STREAMS} live connections open; the last ${MAX_STREAMS - LIVE_STREAMS} are kept for moving a chat`; +/** The sentence a closed stream's socket carries when the breaker cut it, with close code 1008. */ +export const BREAKER_REASON = 'sending faster than a live view does'; + +/** The rate limits count in fixed windows of this many seconds, which is also the longest a refused caller can be told to wait. */ +export const RATE_PERIOD_SECONDS = 60; + +/** + * doorOf reads a dial's class from its header. ONLY THE TWO KNOWN CLASSES ARE CLASSES: anything else, an absent header + * included, is no class, so an older client and a class a later build adds are held to the full MAX_STREAMS exactly as every + * dial was before the header existed. + */ +export const doorOf = (request) => { + const said = request.headers.get(HEADER_DOOR); + return said === DOOR_LIVE || said === DOOR_MOVE ? said : ''; +}; + +/** secondsToNextMinute is how long until the fixed per-minute window `now` (milliseconds) is in rolls over, never less than one. */ +export const secondsToNextMinute = (now) => Math.max(1, Math.ceil((60000 - (now % 60000)) / 1000)); /** The two doors, beneath the deployment's base path. */ export const ENGINE_PATH = '/v1/engine'; export const DIAL_PREFIX = '/v1/dial/'; -/** plain is a refusal in the relay's own sentence, which the Go client passes on as it is. */ -export const plain = (status, sentence) => new Response(sentence, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } }); +/** + * plain is a refusal in the relay's own sentence, which the Go client passes on as it is. A rate limit's refusal also says + * when to come back, in `retry-after`, so a client waits for the window and not for a guess. + */ +export const plain = (status, sentence, headers = {}) => new Response(sentence, { + status, + headers: { 'content-type': 'text/plain; charset=utf-8', ...headers }, +}); const FRAME_HEADER = 13; export const OP = { open: 1, data: 2, close: 3, ping: 4, pong: 5 }; diff --git a/relay/hosted/src/engine/door.js b/relay/hosted/src/engine/door.js index a83fc9d079..f9186c5cf3 100644 --- a/relay/hosted/src/engine/door.js +++ b/relay/hosted/src/engine/door.js @@ -3,8 +3,8 @@ import { ipOf } from '../wire.js'; import { validName } from './names.js'; import { - DIALS_PER_MINUTE, DIAL_PREFIX, ENGINE_PATH, HEADER_NAME, PROTOCOL, REGISTRATIONS_PER_MINUTE, - TOO_MANY_DIALS, TOO_MANY_REGISTRATIONS, plain, + DIALS_PER_MINUTE, DIAL_PREFIX, ENGINE_PATH, HEADER_NAME, PROTOCOL, RATE_PERIOD_SECONDS, REGISTRATIONS_PER_MINUTE, + TOO_MANY_DIALS, TOO_MANY_REGISTRATIONS, plain, secondsToNextMinute, } from './carrier.js'; /** isMachineDoor is a path this module serves. */ @@ -16,21 +16,27 @@ export const isMachineDoor = (pathname) => pathname === ENGINE_PATH || pathname. */ const fallbackBuckets = new Map(); -async function allowCaller(request, env, register) { +/** + * waitFor is null when the caller is within its allowance, and otherwise how many seconds it should wait to be let in. The + * Cloudflare binding does not say where in its window a caller is, so a refusal it gives is told the whole period, which + * is never too short; the in-memory count knows its minute and says exactly how much of it is left. + */ +async function waitFor(request, env, register) { const ip = ipOf(request, env); const limiter = register ? env.MACHINE_REGISTER_LIMIT : env.MACHINE_DIAL_LIMIT; if (limiter && typeof limiter.limit === 'function') { const { success } = await limiter.limit({ key: ip }); - return Boolean(success); + return success ? null : RATE_PERIOD_SECONDS; } const perMinute = register ? REGISTRATIONS_PER_MINUTE : DIALS_PER_MINUTE; - const minute = Math.floor(Date.now() / 60000); + const now = Date.now(); + const minute = Math.floor(now / 60000); for (const [key, bucket] of fallbackBuckets) if (bucket.minute !== minute) fallbackBuckets.delete(key); const key = (register ? 'register ' : 'dial ') + ip; const bucket = fallbackBuckets.get(key) ?? { minute, count: 0 }; bucket.count += 1; fallbackBuckets.set(key, bucket); - return bucket.count <= perMinute; + return bucket.count <= perMinute ? null : secondsToNextMinute(now); } /** @@ -46,8 +52,9 @@ export async function serveMachineDoor(request, env) { } const { pathname } = new URL(request.url); const register = pathname === ENGINE_PATH; - if (!(await allowCaller(request, env, register))) { - return plain(429, register ? TOO_MANY_REGISTRATIONS : TOO_MANY_DIALS); + const wait = await waitFor(request, env, register); + if (wait !== null) { + return plain(429, register ? TOO_MANY_REGISTRATIONS : TOO_MANY_DIALS, { 'retry-after': String(wait) }); } const name = register ? request.headers.get(HEADER_NAME) ?? '' : pathname.slice(DIAL_PREFIX.length); if (!validName(name)) return plain(400, 'that is not a machine name'); diff --git a/relay/hosted/src/engine/room.js b/relay/hosted/src/engine/room.js index e3c3a38612..21391c396f 100644 --- a/relay/hosted/src/engine/room.js +++ b/relay/hosted/src/engine/room.js @@ -10,13 +10,20 @@ // survive hibernation. A quiet machine therefore costs nothing: its liveness is proved by WebSocket pings from the // machine, which the platform answers without waking the object. The one timer is a registration's bounded wait for // an older socket's pong under the same key, while the object is awake anyway. +// +// A DIAL MAY CLAIM A CLASS (carrier.js, doorOf). A live dial stops at LIVE_STREAMS of the machine's streams and the rest are +// kept for a move; a dial with no class is held to MAX_STREAMS exactly as it always was. A live stream also has a breaker +// that ends it, with close code 1008, if it sends far faster than a correct host ever lets a live view. THE BREAKER IS +// COMPUTED WHEN A MESSAGE ARRIVES: there is no timer and no alarm in this object, because either would keep an idle live +// view awake, and an idle live view is meant to cost nothing. import { nameFor } from './names.js'; import { ipOf } from '../wire.js'; import { - DIALS_PER_MINUTE, ENGINE_PATH, HANDSHAKE_MS, HEADER_KEY, HEADER_NAME, MAX_PAYLOAD, MAX_STREAMS, OP, PROBE_MS, - PROTOCOL, REGISTRATIONS_PER_MINUTE, TOO_MANY_DIALS, TOO_MANY_REGISTRATIONS, - challenge, frame, plain as refuse, readFrame, verdict, + BREAKER_REASON, DIALS_PER_MINUTE, DOOR_LIVE, ENGINE_PATH, HANDSHAKE_MS, HEADER_KEY, HEADER_NAME, LIVE_STREAMS, MAX_PAYLOAD, + MAX_STREAMS, OP, PROBE_MS, PROTOCOL, REGISTRATIONS_PER_MINUTE, TOO_MANY_DIALS, TOO_MANY_LIVE, TOO_MANY_REGISTRATIONS, + challenge, doorOf, frame, plain as refuse, readFrame, secondsToNextMinute, verdict, } from './carrier.js'; +import { Breaker } from './breaker.js'; const ENGINE = 'engine'; const DIAL = 'dial'; @@ -45,15 +52,17 @@ export class MachineRoom { this.claiming = false; /** buckets are this minute's counts per caller network and door, kept as a second line behind door.js. */ this.buckets = new Map(); + /** breakers are the live streams' rate counts, one per stream and direction; waking from hibernation forgets them, which only forgives. */ + this.breakers = new Map(); } async fetch(request) { this.#sweepPending(); const register = new URL(request.url).pathname === ENGINE_PATH; if (!this.#allow(ipOf(request, this.env), register ? 'register' : 'dial', register ? REGISTRATIONS_PER_MINUTE : DIALS_PER_MINUTE)) { - return refuse(429, register ? TOO_MANY_REGISTRATIONS : TOO_MANY_DIALS); + return refuse(429, register ? TOO_MANY_REGISTRATIONS : TOO_MANY_DIALS, { 'retry-after': String(secondsToNextMinute(this.clock())) }); } - return register ? this.#register(request) : this.#dial(); + return register ? this.#register(request) : this.#dial(doorOf(request)); } /** allow spends one of a caller's per-minute allowance at this machine's door. */ @@ -117,11 +126,16 @@ export class MachineRoom { return new Response(null, { status: 101, webSocket: client, headers: { 'sec-websocket-protocol': PROTOCOL } }); } - /** dial matches a surface to the machine and opens a stream on its carrier. */ - async #dial() { + /** + * dial matches a surface to the machine and opens a stream on its carrier. A live dial is held to LIVE_STREAMS against the + * machine's TOTAL, so live dials can never take the last streams, which are kept for a move; every other dial, and every dial + * from a build that predates the class, is held to MAX_STREAMS. + */ + async #dial(door) { const engine = this.#engine(); if (!engine) return refuse(404, 'no machine is connected under that name'); const active = this.ctx.getWebSockets(DIAL).filter((ws) => ws.deserializeAttachment()?.role === 'surface'); + if (door === DOOR_LIVE && active.length >= LIVE_STREAMS) return refuse(429, TOO_MANY_LIVE); if (active.length >= MAX_STREAMS) { return refuse(429, `that machine already has ${MAX_STREAMS} connections open, which is as many as the relay carries at once`); } @@ -137,7 +151,9 @@ export class MachineRoom { } const { 0: client, 1: server } = new WebSocketPair(); this.ctx.acceptWebSocket(server, [DIAL, 's:' + id]); - server.serializeAttachment({ role: 'surface', id }); + // THE CLASS RIDES THE SOCKET'S OWN ATTACHMENT, which survives hibernation, and only for a live stream: the breaker needs + // it after a wake-up and nothing else does. No other socket's attachment changes, and no storage is touched. + server.serializeAttachment(door === DOOR_LIVE ? { role: 'surface', id, door } : { role: 'surface', id }); return new Response(null, { status: 101, webSocket: client, headers: { 'sec-websocket-protocol': PROTOCOL } }); } @@ -150,15 +166,17 @@ export class MachineRoom { const seen = ws.deserializeAttachment(); if (!seen || seen.role === 'ended') return; const bytes = bytesOf(message); - if (seen.role === 'surface') return this.#fromSurface(seen.id, bytes); + if (seen.role === 'surface') return this.#fromSurface(seen, bytes); if (seen.role === 'pending') return this.#proof(ws, seen, bytes); if (seen.role === 'engine') return this.#fromMachine(ws, bytes); } /** fromSurface carries a surface's bytes to the machine, cut into carrier-sized frames. */ - #fromSurface(id, bytes) { + #fromSurface(seen, bytes) { + const { id } = seen; const engine = this.#engine(); if (!engine) return this.#closeStream(id, 1011, 'the machine left'); + if (this.#overRate(seen, 'up', bytes.length)) return this.#cut(id, engine); try { for (let at = 0; at < bytes.length; at += MAX_PAYLOAD) { engine.send(frame(OP.data, id, bytes.subarray(at, at + MAX_PAYLOAD))); @@ -181,9 +199,11 @@ export class MachineRoom { } return; } - const surface = this.ctx.getWebSockets('s:' + got.stream).find((s) => s.deserializeAttachment()?.role === 'surface'); + let seen = null; + const surface = this.ctx.getWebSockets('s:' + got.stream).find((s) => (seen = s.deserializeAttachment())?.role === 'surface'); if (!surface) return; if (got.op === OP.data) { + if (this.#overRate(seen, 'down', got.payload.length)) return this.#cut(got.stream, ws); try { surface.send(got.payload); } catch { @@ -291,12 +311,34 @@ export class MachineRoom { } catch {} } + /** + * overRate counts `bytes` against a live stream's breaker for one direction and says whether the stream is now over its + * rate. A stream that did not claim the live class has none, so a move's large answers and every older client's traffic + * are never counted. Each direction has its own breaker, so a heavy flow one way cannot hide in a quiet flow the other. + */ + #overRate(seen, direction, bytes) { + if (seen?.door !== DOOR_LIVE) return false; + const key = `${seen.id}:${direction}`; + let breaker = this.breakers.get(key); + if (!breaker) this.breakers.set(key, (breaker = new Breaker())); + return breaker.charge(bytes, this.clock()); + } + + /** cut ends a stream the breaker tripped: the surface is closed with 1008 and the machine is told, as for any close. */ + #cut(id, engine) { + this.#closeStream(id, 1008, BREAKER_REASON); + try { + engine.send(frame(OP.close, id)); + } catch {} + } + /** gone tells the other end of whatever the socket that ended was carrying, once. */ #gone(ws) { const seen = ws.deserializeAttachment(); if (!seen || seen.role === 'ended') return; ws.serializeAttachment({ ...seen, role: 'ended' }); if (seen.role === 'surface') { + this.#forgetBreakers(seen.id); try { this.#engine()?.send(frame(OP.close, seen.id)); } catch {} @@ -315,7 +357,14 @@ export class MachineRoom { } catch {} } + /** forgetBreakers drops a stream's counts when it ends, so a long-lived object holds only the streams that are open. */ + #forgetBreakers(id) { + this.breakers.delete(`${id}:up`); + this.breakers.delete(`${id}:down`); + } + #closeStream(id, code, reason) { + this.#forgetBreakers(id); for (const surface of this.ctx.getWebSockets('s:' + id)) { surface.serializeAttachment({ role: 'ended', id }); try { diff --git a/relay/hosted/src/rules.js b/relay/hosted/src/rules.js index 18c9f46a59..1fbc1900f4 100644 --- a/relay/hosted/src/rules.js +++ b/relay/hosted/src/rules.js @@ -26,7 +26,7 @@ function holder(c, device, fence) { /** makeRules binds the pure lease rules to one policy. Nothing here reads a clock or a store. */ export function makeRules({ ttlMs, renewOnPublish }) { - // force is the amendment: a person who chose "continue here" takes a live lease at once. + // force is the amendment: a person who chose "move here" takes a live lease at once. // The fence still goes up, so the old holder's next write is refused as before. const acquire = (c, device, now, force = false, expect = undefined) => { if (expect != null && (c.lease.device !== expect.device || diff --git a/relay/hosted/test/engine.test.js b/relay/hosted/test/engine.test.js index 7ac5a3b7f5..a1fe2090fe 100644 --- a/relay/hosted/test/engine.test.js +++ b/relay/hosted/test/engine.test.js @@ -1,11 +1,14 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { nameFor, validName } from '../src/engine/names.js'; +import { readFileSync } from 'node:fs'; import { - DIALS_PER_MINUTE, ENGINE_PATH, HEADER_KEY, HEADER_NAME, MAX_PAYLOAD, MAX_STREAMS, OP, PROTOCOL, - REGISTRATIONS_PER_MINUTE, TOO_MANY_DIALS, TOO_MANY_REGISTRATIONS, - frame, readFrame, registrationProof, verdict, + BREAKER_BYTES_PER_SECOND, BREAKER_REASON, BREAKER_WINDOW_MS, DIALS_PER_MINUTE, DOOR_LIVE, DOOR_MOVE, ENGINE_PATH, HEADER_DOOR, + HEADER_KEY, HEADER_NAME, LIVE_STREAMS, MAX_PAYLOAD, MAX_STREAMS, OP, PROTOCOL, + REGISTRATIONS_PER_MINUTE, TOO_MANY_DIALS, TOO_MANY_LIVE, TOO_MANY_REGISTRATIONS, + doorOf, frame, readFrame, registrationProof, secondsToNextMinute, verdict, } from '../src/engine/carrier.js'; +import { Breaker } from '../src/engine/breaker.js'; import { serveMachineDoor } from '../src/engine/door.js'; import { MachineRoom } from '../src/engine/room.js'; @@ -61,6 +64,9 @@ function makeRoom(options = {}) { const sockets = []; const kv = new Map(); const clock = { now: 1_000_000 }; + /** Every storage write and every alarm the object asks for, so a test can say none happened beyond the stream counter. */ + const puts = []; + const alarms = []; function makeSocket(peerRef) { const ws = { @@ -112,7 +118,11 @@ function makeRoom(options = {}) { }; const ctx = { - storage: { kv: { get: (k) => kv.get(k), put: (k, v) => kv.set(k, v) } }, + storage: { + kv: { get: (k) => kv.get(k), put: (k, v) => (puts.push(k), kv.set(k, v)) }, + setAlarm: (at) => alarms.push(['set', at]), + deleteAlarm: () => alarms.push(['delete']), + }, acceptWebSocket(ws, tags = []) { ws.accepted = true; ws.tags = [...tags]; @@ -163,18 +173,19 @@ function makeRoom(options = {}) { return { res, client: res.webSocket, server, verdict: last }; } - async function dial(name, ip = '198.51.100.2') { + async function dial(name, ip = '198.51.100.2', headers = {}) { const req = new Request('https://relay.example/v1/dial/' + name, { headers: { upgrade: 'websocket', 'sec-websocket-protocol': PROTOCOL, 'cf-connecting-ip': ip, + ...headers, }, }); return room.fetch(req); } - return { room, ctx, sockets, clock, register, dial, restore }; + return { room, ctx, sockets, clock, register, dial, restore, puts, alarms }; } async function withRoom(options, fn) { @@ -493,3 +504,338 @@ test('MachineRoom cleans up throwing sends, closing surfaces, dropped challenger assert.equal(pending.deserializeAttachment()?.role, 'ended'); }); }); + +// --------------------------------------------------------------------------------------------------------------- +// The dial class (contract V21). A live dial stops at LIVE_STREAMS of a machine's streams, a move keeps the last +// MAX_STREAMS - LIVE_STREAMS, and a dial that claims no class behaves exactly as it did before the header existed. +// --------------------------------------------------------------------------------------------------------------- + +const asClass = (door) => (door === undefined ? {} : { [HEADER_DOOR]: door }); +const ipN = (n) => `198.51.100.${n}`; + +// dialN opens `count` dials of one class from distinct networks, so only the stream ceiling can refuse them. +async function dialN(h, name, count, door, from = 10) { + const opened = []; + for (let i = 0; i < count; i += 1) { + const res = await h.dial(name, ipN(from + i), asClass(door)); + assert.equal(res.status, 101, `dial ${i + 1} of class ${JSON.stringify(door)} should have been accepted`); + opened.push(res.webSocket.server); + } + return opened; +} + +test('V21 live dials stop at fourteen and a move still gets the last two', async () => { + const [owner] = await collidingKeys(); + await withRoom({}, async (h) => { + await h.register(owner); + await dialN(h, owner.name, LIVE_STREAMS, DOOR_LIVE); + const fifteenthLive = await h.dial(owner.name, ipN(100), asClass(DOOR_LIVE)); + assert.equal(fifteenthLive.status, 429, 'the 15th live dial is refused'); + assert.equal(await fifteenthLive.text(), TOO_MANY_LIVE); + + assert.equal((await h.dial(owner.name, ipN(101), asClass(DOOR_MOVE))).status, 101, 'a move dial is accepted at 14 streams'); + assert.equal((await h.dial(owner.name, ipN(102), asClass(DOOR_MOVE))).status, 101, 'a second move dial is accepted at 15 streams'); + const seventeenth = await h.dial(owner.name, ipN(103), asClass(DOOR_MOVE)); + assert.equal(seventeenth.status, 429, 'nothing is accepted past the sixteen the machine carries'); + assert.equal((await h.dial(owner.name, ipN(104))).status, 429, 'an unclassified dial is refused at sixteen too'); + }); +}); + +test('V21 a dial with no class, or a class nobody knows, behaves as every dial did before: sixteen, first come', async () => { + const [owner] = await collidingKeys(); + for (const door of [undefined, '', 'bogus', 'LIVE', 'live,move']) { + await withRoom({}, async (h) => { + await h.register(owner); + await dialN(h, owner.name, MAX_STREAMS, door); + const refused = await h.dial(owner.name, ipN(100), asClass(door)); + assert.equal(refused.status, 429, `class ${JSON.stringify(door)}: the 17th dial is refused`); + assert.match(await refused.text(), new RegExp(`already has ${MAX_STREAMS} connections open`)); + }); + } +}); + +test('V21 the reservation is measured against the total, so unclassified streams cannot crowd a move out of its two', async () => { + const [owner] = await collidingKeys(); + await withRoom({}, async (h) => { + await h.register(owner); + await dialN(h, owner.name, LIVE_STREAMS); // fourteen older clients + assert.equal((await h.dial(owner.name, ipN(100), asClass(DOOR_LIVE))).status, 429, 'a live dial is refused at a total of 14'); + assert.equal((await h.dial(owner.name, ipN(101), asClass(DOOR_MOVE))).status, 101, 'a move is not'); + assert.equal((await h.dial(owner.name, ipN(102))).status, 101, 'an unclassified dial is not, either'); + assert.equal((await h.dial(owner.name, ipN(103), asClass(DOOR_MOVE))).status, 429, 'the machine is full at 16'); + }); +}); + +test('V21 a live stream that ends gives its slot back to the next live dial', async () => { + const [owner] = await collidingKeys(); + await withRoom({}, async (h) => { + await h.register(owner); + const live = await dialN(h, owner.name, LIVE_STREAMS, DOOR_LIVE); + assert.equal((await h.dial(owner.name, ipN(100), asClass(DOOR_LIVE))).status, 429); + await h.room.webSocketClose(live[3], 1000); + assert.equal((await h.dial(owner.name, ipN(101), asClass(DOOR_LIVE))).status, 101); + }); +}); + +test('the class is read only from the exact header values, and other dials carry no class on their socket', async () => { + const request = (value) => new Request('https://relay.example/v1/dial/x', { headers: value === undefined ? {} : { [HEADER_DOOR]: value } }); + assert.equal(doorOf(request(DOOR_LIVE)), DOOR_LIVE); + assert.equal(doorOf(request(DOOR_MOVE)), DOOR_MOVE); + for (const odd of [undefined, '', 'Live', 'LIVE', 'door', 'live;move', 'live,move']) assert.equal(doorOf(request(odd)), '', JSON.stringify(odd)); + + const [owner] = await collidingKeys(); + await withRoom({}, async (h) => { + await h.register(owner); + const [unclassified] = await dialN(h, owner.name, 1, undefined, 10); + const [move] = await dialN(h, owner.name, 1, DOOR_MOVE, 20); + const [live] = await dialN(h, owner.name, 1, DOOR_LIVE, 30); + assert.deepEqual(Object.keys(unclassified.deserializeAttachment()).sort(), ['id', 'role']); + assert.deepEqual(Object.keys(move.deserializeAttachment()).sort(), ['id', 'role']); + assert.equal(live.deserializeAttachment().door, DOOR_LIVE); + }); +}); + +// --------------------------------------------------------------------------------------------------------------- +// The abuse breaker. It cuts a live stream that sustains more than BREAKER_BYTES_PER_SECOND across BREAKER_WINDOW_MS, +// and it is computed from the arrival of the message itself: no timer, no alarm. +// --------------------------------------------------------------------------------------------------------------- + +const MiB = 1 << 20; +const payload = (n) => new Uint8Array(n); +const toMachine = (h, machine, id, n) => h.room.webSocketMessage(machine.server, frame(OP.data, id, payload(n))); +const closesFor = (machine, id) => machine.server.sent.filter((m) => m instanceof Uint8Array && m.length === 13 && m[0] === OP.close && readFrame(m)?.stream === String(id)); + +test('the breaker is a leaky bucket: a burst over the window, or a flow over the rate, trips it, and a flow under the rate never does', () => { + const capacity = (BREAKER_BYTES_PER_SECOND * BREAKER_WINDOW_MS) / 1000; + const burst = new Breaker(); + assert.equal(burst.charge(capacity, 0), false, 'exactly the window of allowance is not over'); + assert.equal(burst.charge(1, 0), true, 'one byte more is'); + + const over = new Breaker(); + let at = 0; + let tripped = null; + // 8 MiB every second is twice the rate: it must trip, and not before the allowance has been spent. + for (let second = 1; second <= 20 && tripped === null; second += 1) { + at = second * 1000; + if (over.charge(8 * MiB, at)) tripped = second; + } + assert.ok(tripped !== null && tripped >= 5 && tripped <= 6, `twice the rate tripped at second ${tripped}, want 5 or 6`); + + const under = new Breaker(); + for (let second = 1; second <= 3600; second += 1) { + assert.equal(under.charge(3 * MiB, second * 1000), false, `3 MiB a second is under the rate (second ${second})`); + } + + const rests = new Breaker(); + assert.equal(rests.charge(capacity, 0), false); + assert.equal(rests.charge(capacity, BREAKER_WINDOW_MS), false, 'a stream that rested for the window starts again from empty'); + assert.equal(new Breaker().charge(capacity + 1, 0), true); +}); + +test('the breaker holds the Go side to the same rate and window', () => { + assert.equal(BREAKER_BYTES_PER_SECOND, 4 * MiB); + assert.equal(BREAKER_WINDOW_MS, 5000); +}); + +test('a live stream sending far faster than a correct host is cut with 1008 and the machine is told; a correct pace never is', async () => { + const [owner] = await collidingKeys(); + await withRoom({}, async (h) => { + const machine = await h.register(owner); + const [paced, abusive] = await dialN(h, owner.name, 2, DOOR_LIVE); + const [pacedId, abusiveId] = [paced, abusive].map((s) => s.deserializeAttachment().id); + + // One MiB a second for a minute: the pace a correct host holds. Nothing is cut. + for (let second = 0; second < 60; second += 1) { + h.clock.now += 1000; + await h.room.webSocketMessage(paced, payload(MiB)); + machine.server.sent.length = 0; // the harness keeps every frame it is sent; this test does not need them + } + assert.equal(paced.closed, null, 'a stream at the correct pace is left alone'); + + // 8 MiB every second is twice the rate. It is cut, with 1008, inside the window and after its allowance is spent. + let cutAt = null; + for (let second = 1; second <= 20 && cutAt === null; second += 1) { + h.clock.now += 1000; + await h.room.webSocketMessage(abusive, payload(8 * MiB)); + if (abusive.closed) cutAt = second; + } + assert.ok(cutAt >= 5 && cutAt <= 6, `cut at second ${cutAt}`); + assert.deepEqual(abusive.closed, [1008, BREAKER_REASON]); + assert.equal(abusive.deserializeAttachment().role, 'ended'); + assert.equal(closesFor(machine, abusiveId).length, 1, 'the machine is told the stream is over'); + assert.equal(closesFor(machine, pacedId).length, 0); + assert.equal(h.room.breakers.size, 1, 'the cut stream left no counts behind; only the paced stream has its one'); + + // The cut stream's own close arriving afterwards is not a second cut and sends nothing more. + await h.room.webSocketClose(abusive, 1006); + assert.equal(closesFor(machine, abusiveId).length, 1); + }); +}); + +test('the machine sending a live stream too fast is cut the same way, and the surface is told 1008', async () => { + const [owner] = await collidingKeys(); + await withRoom({}, async (h) => { + const machine = await h.register(owner); + const [live] = await dialN(h, owner.name, 1, DOOR_LIVE); + const id = live.deserializeAttachment().id; + let cutAt = null; + for (let second = 1; second <= 20 && cutAt === null; second += 1) { + h.clock.now += 1000; + // The carrier's own frame is at most MAX_PAYLOAD, so 8 MiB a second is many frames a second. + for (let sent = 0; sent < 8 * MiB; sent += MAX_PAYLOAD) await toMachine(h, machine, id, MAX_PAYLOAD); + if (live.closed) cutAt = second; + } + assert.ok(cutAt >= 5 && cutAt <= 6, `cut at second ${cutAt}`); + assert.equal(live.closed[0], 1008); + assert.equal(closesFor(machine, id).length, 1, 'the machine hears the stream closed'); + }); +}); + +test('streams that did not claim the live class are never counted: a move may carry its large answers', async () => { + const [owner] = await collidingKeys(); + await withRoom({}, async (h) => { + const machine = await h.register(owner); + const [move] = await dialN(h, owner.name, 1, DOOR_MOVE, 10); + const [old] = await dialN(h, owner.name, 1, undefined, 20); + for (const stream of [move, old]) { + const id = stream.deserializeAttachment().id; + for (let i = 0; i < 64; i += 1) { + await toMachine(h, machine, id, MAX_PAYLOAD); // 8 MiB at once, in no time at all + await h.room.webSocketMessage(stream, payload(MAX_PAYLOAD)); + } + assert.equal(stream.closed, null); + } + assert.equal(h.room.breakers.size, 0, 'nothing was counted for a stream with no live class'); + }); +}); + +// --------------------------------------------------------------------------------------------------------------- +// A live session costs the object nothing it did not cost before (contract V5 and V15, the Worker's half): no new stored +// object, no timer and no alarm, so an idle live view lets the object hibernate. +// --------------------------------------------------------------------------------------------------------------- + +test('V5 V15 a whole live session stores only the stream counter, and schedules no timer and no alarm', async () => { + const [owner] = await collidingKeys(); + const real = { setTimeout: globalThis.setTimeout, setInterval: globalThis.setInterval }; + const fromRoom = []; + const spy = (kind) => (...args) => { + // Only a timer the room's own code asked for counts: the test runner has timers of its own. + if (new Error().stack.includes('/src/engine/')) fromRoom.push(kind); + return real[kind](...args); + }; + await withRoom({}, async (h) => { + const machine = await h.register(owner); + globalThis.setTimeout = spy('setTimeout'); + globalThis.setInterval = spy('setInterval'); + try { + const putsBefore = h.puts.length; + const [viewer] = await dialN(h, owner.name, 1, DOOR_LIVE); + const id = viewer.deserializeAttachment().id; + for (let i = 0; i < 100; i += 1) { + h.clock.now += 40; + await h.room.webSocketMessage(viewer, payload(512)); + await toMachine(h, machine, id, 512); + } + await h.room.webSocketClose(viewer, 1000); + assert.deepEqual(h.puts.slice(putsBefore), ['next'], 'the one write is the stream-id counter, once per accepted dial'); + } finally { + globalThis.setTimeout = real.setTimeout; + globalThis.setInterval = real.setInterval; + } + assert.deepEqual(fromRoom, [], 'the object scheduled no timer while a live stream was dialled, carried and closed'); + assert.deepEqual(h.alarms, [], 'the object asked for no alarm'); + }); +}); + +// --------------------------------------------------------------------------------------------------------------- +// Retry-After on both rate limits' refusals, so a client waits for its window and not for a guess. +// --------------------------------------------------------------------------------------------------------------- + +test('the room tells a refused caller how long is left in its minute', async () => { + const [owner] = await collidingKeys(); + await withRoom({}, async (h) => { + await h.register(owner); + // The clock starts 40 s into a minute, so 20 s of it are left. + assert.equal(secondsToNextMinute(h.clock.now), 20); + for (let i = 0; i < DIALS_PER_MINUTE; i += 1) await h.dial(owner.name, '198.51.100.7'); + const refused = await h.dial(owner.name, '198.51.100.7'); + assert.equal(refused.status, 429); + assert.equal(await refused.text(), TOO_MANY_DIALS); + assert.equal(refused.headers.get('retry-after'), '20'); + + h.clock.now += 19_500; + const later = await h.dial(owner.name, '198.51.100.7'); + assert.equal(later.status, 429); + assert.equal(later.headers.get('retry-after'), '1', 'never less than a second, so a client is not told to retry at once'); + + h.clock.now += 1000; + const rolled = await h.dial(owner.name, '198.51.100.7'); + assert.notEqual(await rolled.text(), TOO_MANY_DIALS, 'the minute rolled over, and the caller is not refused for its rate'); + assert.equal(rolled.headers.get('retry-after'), null); + + for (let i = 0; i < REGISTRATIONS_PER_MINUTE; i += 1) await h.room.fetch(new Request('https://relay.example' + ENGINE_PATH, { + headers: { upgrade: 'websocket', 'sec-websocket-protocol': PROTOCOL, 'cf-connecting-ip': '198.51.100.8', [HEADER_NAME]: 'amber-anchor-10' }, + })); + const refusedRegistration = await h.room.fetch(new Request('https://relay.example' + ENGINE_PATH, { + headers: { upgrade: 'websocket', 'sec-websocket-protocol': PROTOCOL, 'cf-connecting-ip': '198.51.100.8', [HEADER_NAME]: 'amber-anchor-10' }, + })); + assert.equal(refusedRegistration.status, 429); + assert.equal(await refusedRegistration.text(), TOO_MANY_REGISTRATIONS); + assert.match(refusedRegistration.headers.get('retry-after'), /^\d+$/); + }); +}); + +test('the front door tells a refused caller when to come back, on both its paths', async () => { + const reached = []; + const machine = { idFromName: (n) => n, get: (id) => ({ async fetch() { reached.push(id); return new Response('no machine is connected under that name', { status: 404 }); } }) }; + const ws = { upgrade: 'websocket', 'sec-websocket-protocol': PROTOCOL }; + + // The Cloudflare binding does not say where in its window a caller is, so a refusal it gives is told the whole period. + const refusing = { async limit() { return { success: false }; } }; + const bound = await serveMachineDoor( + new Request('https://relay.example/v1/dial/acorn-alder-10', { headers: { ...ws, 'cf-connecting-ip': '198.51.100.1' } }), + { MACHINE: machine, MACHINE_DIAL_LIMIT: refusing, MACHINE_REGISTER_LIMIT: refusing }, + ); + assert.equal(bound.status, 429); + assert.equal(bound.headers.get('retry-after'), '60'); + const boundRegistration = await serveMachineDoor( + new Request('https://relay.example' + ENGINE_PATH, { headers: { ...ws, 'cf-connecting-ip': '198.51.100.1', [HEADER_NAME]: 'acorn-alder-10' } }), + { MACHINE: machine, MACHINE_DIAL_LIMIT: refusing, MACHINE_REGISTER_LIMIT: refusing }, + ); + assert.equal(boundRegistration.status, 429); + assert.equal(boundRegistration.headers.get('retry-after'), '60'); + + // With no binding the Worker counts in memory, knows its minute, and says exactly how much of it is left. + const ip = '203.0.113.' + (Date.now() % 200); + let last; + for (let i = 0; i <= DIALS_PER_MINUTE; i += 1) { + last = await serveMachineDoor(new Request('https://relay.example/v1/dial/acorn-alder-10', { headers: { ...ws, 'cf-connecting-ip': ip } }), { MACHINE: machine }); + } + assert.equal(last.status, 429); + const wait = Number(last.headers.get('retry-after')); + assert.ok(Number.isInteger(wait) && wait >= 1 && wait <= 60, `retry-after ${wait}`); + assert.equal(reached.length, DIALS_PER_MINUTE, 'the refused dial woke no object'); +}); + +// --------------------------------------------------------------------------------------------------------------- +// One source of truth: the Worker's numbers are the Go relay's, under the same names (internal/relay/relay.go). +// --------------------------------------------------------------------------------------------------------------- + +test('the numbers the Worker enforces are the Go relay\'s: live streams, the class names and the breaker', () => { + const go = readFileSync(new URL('../../../internal/relay/relay.go', import.meta.url), 'utf8'); + const number = (name) => { + const found = go.match(new RegExp(`^\\s*(?:const\\s+)?${name}\\s*=\\s*(.+?)\\s*(?://.*)?$`, 'm')); + assert.ok(found, `relay.go has no ${name}`); + return found[1]; + }; + assert.equal(Number(number('MaxStreams')), MAX_STREAMS); + assert.equal(Number(number('LiveStreams')), LIVE_STREAMS); + assert.equal(number('DoorLive'), JSON.stringify(DOOR_LIVE)); + assert.equal(number('DoorMove'), JSON.stringify(DOOR_MOVE)); + assert.equal(number('HeaderDoor').toLowerCase(), JSON.stringify(HEADER_DOOR)); + assert.equal(number('BreakerRate'), '4 << 20'); + assert.equal(number('BreakerWindow'), '5 * time.Second'); + assert.equal(BREAKER_BYTES_PER_SECOND, 4 << 20); + assert.equal(BREAKER_WINDOW_MS, 5 * 1000); + assert.equal(MAX_STREAMS - LIVE_STREAMS, 2, 'two streams are kept for a move'); +}); diff --git a/relay/hosted/test/storage.test.js b/relay/hosted/test/storage.test.js index 6c8b50ab8f..62484d409e 100644 --- a/relay/hosted/test/storage.test.js +++ b/relay/hosted/test/storage.test.js @@ -11,7 +11,7 @@ import { Tenant } from '../src/tenant.js'; import { RaftBlobTenant } from '../src/raft/effects.js'; import { sealFrame } from '../src/store.js'; import { matchRoute } from '../src/routes.js'; -import { PROTOCOL, HEADER_NAME } from '../src/engine/carrier.js'; +import { PROTOCOL, HEADER_NAME, HEADER_DOOR, DOOR_LIVE } from '../src/engine/carrier.js'; import { Flight } from '../src/flight.js'; import { NOBODY } from '../src/watch.js'; import { policyOf } from '../src/rules.js'; @@ -162,6 +162,23 @@ test('R3 pairing and machine tunnel ingress remain available with storage off', assert.equal(machines,2); }); +// Contract V5, the Worker's half: a live dial adds no stored object and no field to any record. It reaches the machine's +// own object with its class intact, and never touches the identity's storage approval or the frames bucket. +test('R3 a live dial with storage off reaches its machine object with its class and touches neither R2 nor the identity', async () => { + const seen = []; + const env={CAF_LIMITS:'{"storageOpen":false}', + MACHINE:{idFromName:x=>x,get:()=>({fetch:async(request)=>{seen.push(request.headers.get(HEADER_DOOR));return new Response('live',{status:200});}})}, + MACHINE_DIAL_LIMIT:{limit:async()=>({success:true})},MACHINE_REGISTER_LIMIT:{limit:async()=>({success:true})}, + FRAMES:new Proxy({}, {get(){throw Error('live access touched R2');}}), + IDENTITY:new Proxy({}, {get(){throw Error('live access consulted storage approval');}})}; + for(const door of [DOOR_LIVE,undefined]) { + const headers={upgrade:'websocket','sec-websocket-protocol':PROTOCOL,...(door?{[HEADER_DOOR]:door}:{})}; + const response=await respond(()=>dispatch(new Request('https://relay.test/v1/dial/amber-forest-42',{headers}),env)); + assert.equal(response.status,200,await response.text()); + } + assert.deepEqual(seen,[DOOR_LIVE,null],'the class header crosses the front door unchanged, and an unclassified dial has none'); +}); + test('S2 a fixed valid signature refuses changed bytes, whitespace and a missing domain label', async () => { const a=admin(), raw=JSON.stringify(a.body), signature=a.signature(raw); for(const changed of [raw.replace('random-test-nonce','random-test-noncf'),raw+' ']) assert.equal((await a.send({}, {raw:changed,signature})).status,401);