diff --git a/docs/research/native-client-media.md b/docs/research/native-client-media.md index 8f65496d9..4eb42a170 100644 --- a/docs/research/native-client-media.md +++ b/docs/research/native-client-media.md @@ -540,12 +540,20 @@ The reporter retracted the initial CBR bitrate-ceiling diagnosis after finding that the experimental fixture changed bitrate during the measured interval. That switching belongs to `PIIK_H264_FIXTURE` in `windows/main.cpp`, not live capture. The corrected experiment reports CBR reaching its requested bitrate. -Production `h264_encoder.cpp` explicitly requests and validates Baseline; the +Production `h264_encoder.cpp` explicitly requests and validates Constrained Baseline; the Browser's negotiated `profile-level-id` alone is not an inspection of emitted SPS. The later experimental CABAC result cannot establish the production Baseline bitstream's behavior. Microsoft's [encoder reference](https://learn.microsoft.com/en-us/windows/win32/medfound/h-264-video-encoder) distinguishes profile, rate control and optional quality/speed settings. +The MFT request uses `eAVEncH264VProfile_ConstrainedBase` (256), matching the +negotiated coding-tool subset. Microsoft's [profile enumeration](https://learn.microsoft.com/en-us/windows/win32/api/codecapi/ne-codecapi-eavench264vprofile) +distinguishes it from ordinary Baseline (66). In [#538](https://github.com/TNTcraftHIM/Piik/issues/538), +an AMD encoder produced `420420` for 66 and `424020` for 256; only the latter +passes the unchanged Constrained Baseline bitstream check. Request and readback +must use the same profile; relaxing the emitted-SPS check would change the +negotiated contract. + The original 720p comparison remains unresolved. An equal-content comparison must preserve actual bitrate, frame rate, latency and production codec settings, inspect the resulting bitstream and retain reference/decoded pictures. Raising diff --git a/docs/standards/presentation-lifecycle.md b/docs/standards/presentation-lifecycle.md index 238c2318e..1fef522b5 100644 --- a/docs/standards/presentation-lifecycle.md +++ b/docs/standards/presentation-lifecycle.md @@ -66,9 +66,16 @@ connection state. Android adds an explicit wake action. Browser and camera actions retain their own capability checks. A Site's explicit App action discovers the local approval page, where the user confirms its exact origin. The launcher lists approvals and -revokes each independently. Starring one approved Site makes an ordinary App launch open it; -without a star, the launcher opens. This preference grants no access and starts -no room. Revoking that Site clears its star; other approvals leave it intact. Explicit CLI entry keeps +revokes each independently. Starring an external Site makes an ordinary App launch +open its fixed address without starting a room. Starring the current App-owned +Site records its launch selection instead: the next App run starts that mode and +enters its fresh ready address. The current runtime's exact origins determine +ownership; a temporary invitation hostname alone does not. Without a startup +choice, the launcher opens. This preference grants no access or capture permission. +Its launcher checkbox can clear an App-owned choice; revoking its current origin +also clears it. Other approvals leave the choice intact. Older saved temporary +URLs have no ownership information: start the Site from the launcher and select +the startup checkbox again on its current entry. Explicit CLI entry keeps precedence. The ready App button and terminal launcher address return to its management page in every mode. A pending or healthy Local/public room keeps its startup selection; reopening the launcher does not stop or replace that room. diff --git a/internal/app/app.go b/internal/app/app.go index 27c696824..ab85b19a5 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -61,6 +61,7 @@ type Options struct { CaptureProcess string TunnelProcess string Ready func(string) + localReady func(string, string) console *console logger *slog.Logger } @@ -274,7 +275,7 @@ func runLauncher( launcher.Options{ DefaultMode: mode, StartupSite: startupSite, - SaveStartupSite: func(site string) error { + SaveStartupSite: func(site launcher.StartupIntent) error { return launcher.SaveStartupSite(configPath, site) }, Sites: config.ApprovedSites(), Version: buildinfo.Version(), Revision: buildinfo.Revision, @@ -324,15 +325,18 @@ func runLauncher( if err != nil { return errors.Join(failure.NativeControl, err) } - if !automatic && startupSite == "" { + if !automatic && (startupSite.Site == "" || startupSite.Owned != nil) { + if startupSite.Owned != nil { + launch.Begin() + } options.console.show(consoleView{state: "setup", entry: launch.URL()}) - options.console.openBrowser(launch.URL()) + options.console.openBrowser(launch.EntryURL()) } else if initialConfig.Site != "" && !options.Local && !options.Link { // A starred Site changes only the opening page. --site also remains an // explicit approval shortcut; the launcher can start a Local room later. site := initialConfig.Site if !automatic { - site = startupSite + site = startupSite.Site } openSite(site, options, control.Endpoint().Port) } @@ -365,13 +369,14 @@ func runLauncher( if !directRoom { options.DisableBrowser = true } - ready := make(chan string, 1) + type localResult struct{ target, invitation string } + ready := make(chan localResult, 1) onReady := options.Ready - options.Ready = func(target string) { + options.localReady = func(target, invitation string) { if onReady != nil { onReady(target) } - ready <- target + ready <- localResult{target, invitation} } runtimeContext, cancelRuntime := context.WithCancel(ctx) runtimeDone := make(chan struct{}) @@ -383,7 +388,7 @@ func runLauncher( var exitErr error select { case target := <-ready: - launch.SetResult(target, nil) + launch.SetReady(target.target, target.invitation, selection) select { case <-runtimeDone: case exitErr = <-launch.Done(): @@ -398,9 +403,14 @@ func runLauncher( return errors.Join(exitErr, runtimeErr) } var roomErr error + startupOwned := startupSite.Owned for { var selection launcher.Selection - if directRoom { + if !automatic && startupOwned != nil { + selection = launcher.Selection{Mode: startupOwned.Mode, LANAddress: startupOwned.LANAddress, LocalAccessPassword: initialConfig.LocalAccessPassword} + startupOwned = nil + launch.Begin() + } else if directRoom { selection = launcher.Selection{Mode: launcher.ModeLocal, LocalAccessPassword: initialConfig.LocalAccessPassword} if initialOptions.Link { selection.Mode = launcher.ModeLink @@ -636,7 +646,9 @@ func runLocal(ctx context.Context, options Options, config appconfig.Config, if !options.DisableBrowser { options.console.openBrowser(launchURL) } - if options.Ready != nil { + if options.localReady != nil { + options.localReady(launchURL, view.invite) + } else if options.Ready != nil { options.Ready(launchURL) } var tunnelDone <-chan struct{} diff --git a/internal/app/app_test.go b/internal/app/app_test.go index 3f17301e3..f16e9f3c5 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -40,7 +40,11 @@ func TestMain(tests *testing.M) { os.Exit(7) } if mode == "ready" || mode == "ready-failed" { - fmt.Println(`{"message":"https://test-room.trycloudflare.com"}`) + origin := os.Getenv("PIIK_APP_TUNNEL_ORIGIN") + if origin == "" { + origin = "https://test-room.trycloudflare.com" + } + fmt.Printf("{\"message\":%q}\n", origin) fmt.Println(`{"message":"Registered tunnel connection"}`) } if mode == "ready-failed" { @@ -421,7 +425,7 @@ func TestHungBrowserHandoffDoesNotBlockLauncherOrSiteExit(t *testing.T) { t.Fatal(err) } if mode == "starred-site" || mode == "revoked-site" { - if err := launcher.SaveStartupSite(configPath, "https://share.example"); err != nil { + if err := launcher.SaveStartupSite(configPath, launcher.StartupIntent{Site: "https://share.example"}); err != nil { t.Fatal(err) } if mode == "starred-site" { @@ -430,7 +434,7 @@ func TestHungBrowserHandoffDoesNotBlockLauncherOrSiteExit(t *testing.T) { } if mode == "starred-second-site" { config.SetApprovedSites([]string{"https://first.example", "https://share.example"}) - if err := launcher.SaveStartupSite(configPath, "https://share.example"); err != nil { + if err := launcher.SaveStartupSite(configPath, launcher.StartupIntent{Site: "https://share.example"}); err != nil { t.Fatal(err) } } @@ -634,6 +638,124 @@ func TestSavedSiteAllowsBrowserOriginAtNativeControl(t *testing.T) { } } +func TestOwnedStartupUsesFreshInvitation(t *testing.T) { + t.Setenv("PIIK_APP_TUNNEL_FIXTURE", "ready") + t.Setenv("PIIK_APP_TUNNEL_STARTED", filepath.Join(t.TempDir(), "started")) + executable, _ := os.Executable() + path := filepath.Join(t.TempDir(), "client.json") + config, err := appconfig.LoadOrCreate(path) + if err != nil { + t.Fatal(err) + } + old := "https://first-start.trycloudflare.com" + config.SetApprovedSites([]string{old, "https://external.example"}) + for turn := 0; turn < 2; turn++ { + invitation := old + if turn == 1 { + invitation = "https://next-start.trycloudflare.com" + } + t.Setenv("PIIK_APP_TUNNEL_ORIGIN", invitation) + listener, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := listener.Addr().(*net.TCPAddr).Port + listener.Close() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + control, err := loopback.Start(ctx, loopback.Options{}) + if err != nil { + t.Fatal(err) + } + opened := make(chan string, 4) + console := newConsole(cancel, true) + console.openURL = func(target string) error { opened <- target; return nil } + done := make(chan error, 1) + go func() { + done <- runLauncher(ctx, Options{Port: port, console: console, TunnelProcess: executable}, path, config, control, func(*Options, appconfig.Config) error { return nil }) + }() + var entry string + select { + case entry = <-opened: + case <-time.After(5 * time.Second): + t.Fatal("missing startup entry") + } + parsed, _ := url.Parse(entry) + origin := parsed.Scheme + "://" + parsed.Host + api := origin + "/api/client-launcher" + post := func(route, body string) map[string]any { + req, _ := http.NewRequest(http.MethodPost, api+route, strings.NewReader(body)) + req.Header.Set("Origin", origin) + req.Header.Set("Content-Type", "application/json") + response, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + var result map[string]any + if err := json.NewDecoder(response.Body).Decode(&result); err != nil || response.StatusCode != 200 { + t.Fatalf("%s: %d %+v %v", route, response.StatusCode, result, err) + } + return result + } + if turn == 0 { + post("/launch", `{"mode":"link","language":"en","localAccessPassword":""}`) + } else if parsed.Query().Get("start") != "1" || strings.Contains(entry, old) { + t.Fatalf("stale startup entry: %s", entry) + } + var state map[string]any + deadline := time.Now().Add(5 * time.Second) + for { + response, err := http.Get(api) + if err != nil { + t.Fatal(err) + } + json.NewDecoder(response.Body).Decode(&state) + response.Body.Close() + if state["target"] != "" { + break + } + if time.Now().After(deadline) { + t.Fatalf("missing ready state: %+v", state) + } + time.Sleep(time.Millisecond) + } + if !strings.HasPrefix(state["target"].(string), fmt.Sprintf("http://127.0.0.1:%d/", port)) { + t.Fatal(state) + } + if turn == 0 { + result := post("/startup-site", fmt.Sprintf(`{"site":%q}`, old)) + if result["startupSite"] != old { + t.Fatal(result) + } + stored, err := launcher.LoadStartupSite(path, config.ApprovedSites()...) + if err != nil || stored.Owned == nil || stored.Owned.Mode != launcher.ModeLink || stored.Site != "" { + t.Fatalf("not owned: %+v %v", stored, err) + } + } else { + if state["startupSite"] != invitation { + t.Fatalf("stale star: %+v", state) + } + post("/startup-site", `{"site":"https://external.example"}`) + stored, err := launcher.LoadStartupSite(path, config.ApprovedSites()...) + if err != nil || stored.Site != "https://external.example" || stored.Owned != nil { + t.Fatalf("external startup changed: %+v %v", stored, err) + } + } + cancel() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("App did not retire") + } + control.Close() + console.finish(nil, "") + } +} + func TestOccupiedPortRejectsLinkBeforeStartingATunnel(t *testing.T) { listener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4zero}) if err != nil { diff --git a/internal/app/launcher/preference.go b/internal/app/launcher/preference.go index c4c320b72..d713f4f76 100644 --- a/internal/app/launcher/preference.go +++ b/internal/app/launcher/preference.go @@ -1,6 +1,7 @@ package launcher import ( + "encoding/json" "errors" "os" "slices" @@ -31,26 +32,57 @@ func SaveMode(configPath string, mode Mode) error { return os.WriteFile(configPath+".mode", []byte(string(mode)+"\n"), 0o600) } -// Startup preference selects one approved origin; it never grants access. -func LoadStartupSite(configPath string, approvedSites ...string) (string, error) { +// StartupIntent selects an external origin or this App's launch, never access. +type StartupIntent struct { + Site string `json:"site,omitempty"` + Owned *StartupLaunch `json:"owned,omitempty"` +} + +type StartupLaunch struct { + Mode Mode `json:"mode"` + LANAddress *string `json:"lanAddress,omitempty"` +} + +func LoadStartupSite(configPath string, approvedSites ...string) (StartupIntent, error) { payload, err := os.ReadFile(configPath + ".startup-site") if errors.Is(err, os.ErrNotExist) { - return "", nil + return StartupIntent{}, nil } if err != nil { - return "", err + return StartupIntent{}, err } site := strings.TrimSpace(string(payload)) + if strings.HasPrefix(site, "{") { + var intent StartupIntent + if err := json.Unmarshal(payload, &intent); err != nil { + return StartupIntent{}, err + } + if intent.Owned == nil || intent.Site != "" || !validMode(intent.Owned.Mode) { + return StartupIntent{}, errors.New("invalid saved startup intent") + } + return intent, nil + } if site == "" || slices.Contains(approvedSites, site) { - return site, nil + return StartupIntent{Site: site}, nil } // CLI/config changes also retire the old choice, rather than letting a // later approval of that same address resurrect it. - return "", SaveStartupSite(configPath, "") + return StartupIntent{}, SaveStartupSite(configPath, StartupIntent{}) } -func SaveStartupSite(configPath, site string) error { - return os.WriteFile(configPath+".startup-site", []byte(site+"\n"), 0o600) +func SaveStartupSite(configPath string, intent StartupIntent) error { + payload := []byte(intent.Site) + if intent.Owned != nil { + if intent.Site != "" || !validMode(intent.Owned.Mode) { + return errors.New("invalid startup intent") + } + var err error + payload, err = json.Marshal(intent) + if err != nil { + return err + } + } + return os.WriteFile(configPath+".startup-site", append(payload, '\n'), 0o600) } func validMode(mode Mode) bool { diff --git a/internal/app/launcher/preference_test.go b/internal/app/launcher/preference_test.go index d0b340bf7..bde7d112c 100644 --- a/internal/app/launcher/preference_test.go +++ b/internal/app/launcher/preference_test.go @@ -86,7 +86,7 @@ func TestStarredSiteSurvivesOtherApprovalsAndClearsOnRevocation(t *testing.T) { } sites := []string{"https://share.example"} server, err := Start(t.Context(), appAssets(), Options{Sites: sites, ControlPort: 39730, - SaveStartupSite: func(site string) error { return SaveStartupSite(path, site) }, + SaveStartupSite: func(site StartupIntent) error { return SaveStartupSite(path, site) }, ChangeSite: func(site string, allowed bool) ([]string, error) { sites = editSites(sites, site, allowed) return sites, nil @@ -121,8 +121,8 @@ func TestStarredSiteSurvivesOtherApprovalsAndClearsOnRevocation(t *testing.T) { if err != nil || response.StatusCode != test.status || state.StartupSite != test.want { t.Fatalf("%+v: %+v %v", test, state, err) } - if saved, err := LoadStartupSite(path, state.Sites...); err != nil || saved != test.want { - t.Fatalf("saved startup: %q %v", saved, err) + if saved, err := LoadStartupSite(path, state.Sites...); err != nil || saved.Site != test.want { + t.Fatalf("saved startup: %+v %v", saved, err) } entry := server.URL() if test.want != "" { diff --git a/internal/app/launcher/server.go b/internal/app/launcher/server.go index 926932a87..81e1ac068 100644 --- a/internal/app/launcher/server.go +++ b/internal/app/launcher/server.go @@ -52,7 +52,7 @@ type Options struct { Modes []Mode DefaultMode Mode Sites []string - StartupSite string + StartupSite StartupIntent Version string Revision string ControlPort int @@ -60,7 +60,7 @@ type Options struct { Debug bool LANAddress string ChangeSite func(string, bool) ([]string, error) - SaveStartupSite func(string) error + SaveStartupSite func(StartupIntent) error EnableDebug func() error } @@ -75,7 +75,7 @@ type Server struct { static http.Handler client http.Handler sites []string - startupSite string + startupSite StartupIntent modes []Mode defaultMode Mode localAccessPassword string @@ -85,7 +85,7 @@ type Server struct { debug bool lanAddress string changeSite func(string, bool) ([]string, error) - saveStartupSite func(string) error + saveStartupSite func(StartupIntent) error enableDebug func() error selection chan Selection done chan error @@ -97,10 +97,12 @@ type Server struct { } type launchAttempt struct { - ready chan struct{} - completed bool - target string - err error + ready chan struct{} + completed bool + target string + err error + invitation string + selection *Selection } // Start serves the launcher page and its API on a loopback port. assets is the @@ -173,8 +175,11 @@ func (server *Server) EntryURL() string { server.mu.Lock() startup := server.startupSite server.mu.Unlock() - if startup != "" { - return EntryURL(startup+"/", server.controlPort) + if startup.Owned != nil { + return server.URL() + "?start=1" + } + if startup.Site != "" { + return EntryURL(startup.Site+"/", server.controlPort) } return server.URL() } @@ -202,13 +207,50 @@ func (server *Server) begin() (*launchAttempt, bool) { return server.attempt, true } +// SetReady records the actual entry, invitation and selection together. +func (server *Server) SetReady(target, invitation string, selection Selection) { + server.mu.Lock() + defer server.mu.Unlock() + server.attempt.invitation, server.attempt.selection = invitation, &selection + server.setResult(target, nil) +} + +func (server *Server) ownedOrigins() []string { + if server.attempt == nil || server.attempt.err != nil || server.attempt.selection == nil { + return []string{} + } + target, _ := url.Parse(server.attempt.target) + return []string{target.Scheme + "://" + target.Host, server.attempt.invitation} +} + +func (server *Server) startupMode() Mode { + if server.startupSite.Owned != nil { + return server.startupSite.Owned.Mode + } + return "" +} + +func (server *Server) startupOrigin() string { + if server.startupSite.Owned == nil { + return server.startupSite.Site + } + if server.attempt != nil && server.attempt.err == nil { + return server.attempt.invitation + } + return "" +} + // SetResult is called by the serial room owner after readiness or full retirement. func (server *Server) SetResult(target string, resultErr error) { + server.mu.Lock() + defer server.mu.Unlock() + server.setResult(target, resultErr) +} + +func (server *Server) setResult(target string, resultErr error) { if resultErr == nil && !validTarget(target) { resultErr = errors.New("App target is invalid") } - server.mu.Lock() - defer server.mu.Unlock() attempt := server.attempt attempt.target = target attempt.err = resultErr @@ -300,7 +342,9 @@ func (server *Server) handleState(response http.ResponseWriter, request *http.Re } state := map[string]any{ "sites": slices.Clone(server.sites), - "startupSite": server.startupSite, + "startupSite": server.startupOrigin(), + "ownedSites": server.ownedOrigins(), + "startupMode": server.startupMode(), "localAccessPassword": server.localAccessPassword, "version": server.version, "revision": server.revision, @@ -357,7 +401,7 @@ func (server *Server) handleSite(response http.ResponseWriter, request *http.Req server.mu.Lock() defer server.mu.Unlock() result := func() map[string]any { - return map[string]any{"sites": slices.Clone(server.sites), "startupSite": server.startupSite} + return map[string]any{"sites": slices.Clone(server.sites), "startupSite": server.startupOrigin(), "ownedSites": server.ownedOrigins(), "startupMode": server.startupMode()} } if startupOnly { if site != "" && !slices.Contains(server.sites, site) { @@ -368,11 +412,16 @@ func (server *Server) handleSite(response http.ResponseWriter, request *http.Req http.Error(response, "startup preference is unavailable", http.StatusServiceUnavailable) return } - if err := server.saveStartupSite(site); err != nil { + intent := StartupIntent{Site: site} + if site != "" && slices.Contains(server.ownedOrigins(), site) { + selection := server.attempt.selection + intent = StartupIntent{Owned: &StartupLaunch{Mode: selection.Mode, LANAddress: selection.LANAddress}} + } + if err := server.saveStartupSite(intent); err != nil { writeJSON(response, http.StatusServiceUnavailable, result()) return } - server.startupSite = site + server.startupSite = intent writeJSON(response, http.StatusOK, result()) return } @@ -383,9 +432,9 @@ func (server *Server) handleSite(response http.ResponseWriter, request *http.Req current, err := server.changeSite(site, *change.Allowed) // Permission can be revoked even if its media cleanup times out. server.sites = current - if server.startupSite != "" && !slices.Contains(current, server.startupSite) { - server.startupSite = "" - err = errors.Join(err, server.saveStartupSite("")) + if !*change.Allowed && (server.startupSite.Site == site || server.startupSite.Owned != nil && slices.Contains(server.ownedOrigins(), site)) { + server.startupSite = StartupIntent{} + err = errors.Join(err, server.saveStartupSite(StartupIntent{})) } if err != nil { failure := result() diff --git a/mobile/bridge/runtime.go b/mobile/bridge/runtime.go index 3342833f6..c0fb1e2cf 100644 --- a/mobile/bridge/runtime.go +++ b/mobile/bridge/runtime.go @@ -41,6 +41,7 @@ type Runtime struct { cancel context.CancelFunc once sync.Once url string + invitation string configMu sync.Mutex configPath string config appconfig.Config @@ -144,7 +145,7 @@ func Start(platform Platform, lanAddress string, codecCapabilities string, dataD r.configMu.Unlock() return sites, err }, - SaveStartupSite: func(site string) error { return launcher.SaveStartupSite(r.configPath, site) }, + SaveStartupSite: func(site launcher.StartupIntent) error { return launcher.SaveStartupSite(r.configPath, site) }, }) if err != nil { return nil, errors.Join(err, r.Close()) @@ -156,38 +157,52 @@ func Start(platform Platform, lanAddress string, codecCapabilities string, dataD if err != nil { return nil, errors.Join(err, r.Close()) } + if startup.Owned != nil { + r.launcher.Begin() + } r.launchDone = make(chan struct{}) go func() { defer close(r.launchDone) - r.runLauncher(lanAddress) + r.runLauncher(lanAddress, startup.Owned) }() go r.watchServices() return r, nil } // Failed startup has already retired its resources before a new selection starts. -func (r *Runtime) runLauncher(lanAddress string) { +func (r *Runtime) runLauncher(lanAddress string, initial *launcher.StartupLaunch) { for { - select { - case selected := <-r.launcher.Selection(): - if err := launcher.SaveMode(r.configPath, selected.Mode); err != nil { - slog.Debug("Could not save the launcher mode", diagnostics.Error(err)) + var selected launcher.Selection + if initial != nil { + r.configMu.Lock() + selected = launcher.Selection{Mode: initial.Mode, LANAddress: initial.LANAddress, LocalAccessPassword: r.config.LocalAccessPassword} + r.configMu.Unlock() + initial = nil + } else { + select { + case selected = <-r.launcher.Selection(): + case <-r.ctx.Done(): + return } - target, err := r.startLocal(selected, lanAddress) + } + if err := launcher.SaveMode(r.configPath, selected.Mode); err != nil { + slog.Debug("Could not save the launcher mode", diagnostics.Error(err)) + } + target, err := r.startLocal(selected, lanAddress) + if err != nil { r.launcher.SetResult(target, err) - if err == nil { - r.configMu.Lock() - server, tunnel := r.server, r.tunnel - r.configMu.Unlock() - err = r.watchRoom(server, tunnel) - if r.ctx.Err() != nil { - r.closeErr = errors.Join(r.closeErr, err) - return - } - r.launcher.SetResult("", err) + } + if err == nil { + r.configMu.Lock() + invitation, server, tunnel := r.invitation, r.server, r.tunnel + r.configMu.Unlock() + r.launcher.SetReady(target, invitation, selected) + err = r.watchRoom(server, tunnel) + if r.ctx.Err() != nil { + r.closeErr = errors.Join(r.closeErr, err) + return } - case <-r.ctx.Done(): - return + r.launcher.SetResult("", err) } } } @@ -287,6 +302,7 @@ func (r *Runtime) startLocal(selection launcher.Selection, address string) (targ return "", err } r.server, r.tunnel, r.url = server, tunnel, target + r.invitation = config.Origin(configuration.PublicBaseURL) committed = true r.configMu.Unlock() return target, nil @@ -325,6 +341,7 @@ func (r *Runtime) watchRoom(server *serverapp.Server, tunnel *publictunnel.Proce origin = r.localOrigin() } r.server, r.tunnel, r.url = nil, nil, "" + r.invitation = "" } r.configMu.Unlock() if origin != "" { diff --git a/mobile/bridge/runtime_test.go b/mobile/bridge/runtime_test.go index 78d5a931a..08db82507 100644 --- a/mobile/bridge/runtime_test.go +++ b/mobile/bridge/runtime_test.go @@ -110,7 +110,7 @@ func TestEntryTracksCurrentStartupPreferenceAndSiteRevocation(t *testing.T) { if err := appconfig.Save(configPath, appconfig.Config{Version: 1, Sites: []string{"https://first.example", "https://second.example"}}); err != nil { t.Fatal(err) } - if err := launcher.SaveStartupSite(configPath, "https://first.example"); err != nil { + if err := launcher.SaveStartupSite(configPath, launcher.StartupIntent{Site: "https://first.example"}); err != nil { t.Fatal(err) } r, err := Start(&testPlatform{}, "", `{"platform":"android","provider":"Android MediaCodec","systemAudio":true,"encoders":[]}`, directory, t.TempDir(), "", "piik://media") diff --git a/mobile/bridge/runtime_tunnel_test.go b/mobile/bridge/runtime_tunnel_test.go index 6daacb598..c7f33f233 100644 --- a/mobile/bridge/runtime_tunnel_test.go +++ b/mobile/bridge/runtime_tunnel_test.go @@ -60,7 +60,7 @@ func TestCloseJoinsLocalControlRetirementWithoutFalseError(t *testing.T) { t.Fatal(err) } r.launchDone = make(chan struct{}) - go func() { defer close(r.launchDone); r.runLauncher("") }() + go func() { defer close(r.launchDone); r.runLauncher("", nil) }() launcherOrigin := strings.TrimSuffix(r.launcher.URL(), "/client") request, _ := http.NewRequest("POST", launcherOrigin+"/api/client-launcher/launch", strings.NewReader(`{"mode":"link","language":"en"}`)) request.Header.Set("Origin", launcherOrigin) @@ -256,6 +256,42 @@ func TestStartupAndSiteRevocationCommitOneOriginAuthority(t *testing.T) { if status := <-launched; status != http.StatusOK { t.Fatalf("startup = %d", status) } + platform.siteChanged = nil + if post("site", `{"site":"https://android-fixture.trycloudflare.com","allowed":true}`) != 200 || + post("startup-site", `{"site":"https://android-fixture.trycloudflare.com"}`) != 200 { + t.Fatal("owned startup preference was not saved") + } + if err := r.Close(); err != nil { + t.Fatal(err) + } + r, err = Start(&testPlatform{}, "", `{"platform":"android","provider":"fixture","encoders":[]}`, dir, t.TempDir(), executable, "") + if err != nil { + t.Fatal(err) + } + defer r.Close() + if r.EntryURL() != r.URL()+"?start=1" { + t.Fatal("mobile startup reused the old invitation") + } + deadline = time.Now().Add(5 * time.Second) + for { + response, err := client.Get(strings.TrimSuffix(r.URL(), "/client") + "/api/client-launcher") + if err != nil { + t.Fatal(err) + } + var state struct{ Target, StartupSite, StartupMode string } + json.NewDecoder(response.Body).Decode(&state) + response.Body.Close() + if state.Target != "" { + if state.Target == target || state.StartupSite != "https://android-fixture.trycloudflare.com" || state.StartupMode != "link" { + t.Fatalf("bad restored startup: %+v", state) + } + break + } + if time.Now().After(deadline) { + t.Fatal("owned startup did not reach Ready without a browser command") + } + time.Sleep(time.Millisecond) + } } type runtimePlatform struct { @@ -369,7 +405,7 @@ func TestLauncherRetriesFailedStartupAndKeepsSuccessfulRoom(t *testing.T) { t.Fatal(err) } r.launchDone = make(chan struct{}) - go func() { defer close(r.launchDone); r.runLauncher("") }() + go func() { defer close(r.launchDone); r.runLauncher("", nil) }() endpoint := strings.TrimSuffix(r.launcher.URL(), "/client") + "/api/client-launcher/launch" client := &http.Client{Timeout: 5 * time.Second} post := func(body string) *http.Response { diff --git a/native/capture/windows/h264_encoder.cpp b/native/capture/windows/h264_encoder.cpp index 3d143293d..4933e0b3c 100644 --- a/native/capture/windows/h264_encoder.cpp +++ b/native/capture/windows/h264_encoder.cpp @@ -345,7 +345,8 @@ ComPtr CreateOutputType( Check(type->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive), "output-type-interlace"); - Check(type->SetUINT32(MF_MT_MPEG2_PROFILE, eAVEncH264VProfile_Base), + // Baseline alone does not require the constrained tools negotiated by WebRTC. + Check(type->SetUINT32(MF_MT_MPEG2_PROFILE, eAVEncH264VProfile_ConstrainedBase), "output-type-profile"); // MF recommends automatic level selection. Forcing a valid level can still // make hardware reject the type; validate the actual SPS instead. @@ -399,7 +400,7 @@ void ValidateMediaTypes( RequireTypeU32(output.Get(), MF_MT_AVG_BITRATE, profile.bit_rate, "output-type-bitrate"); RequireTypeU32(output.Get(), MF_MT_MPEG2_PROFILE, - eAVEncH264VProfile_Base, "output-type-profile"); + eAVEncH264VProfile_ConstrainedBase, "output-type-profile"); UINT32 width = 0; UINT32 height = 0; diff --git a/native/fixtures/mf-h264-hardware/README.md b/native/fixtures/mf-h264-hardware/README.md index cee9cab0f..ace1e0aeb 100644 --- a/native/fixtures/mf-h264-hardware/README.md +++ b/native/fixtures/mf-h264-hardware/README.md @@ -13,15 +13,15 @@ fallback. Exit code zero requires all of these checks in one 360-frame run: - adapter-LUID-bound hardware H.264 enumeration; - asynchronous and D3D11-aware transform readback; -- exact low-latency, CBR, 3 Mbps and 60-frame GOP property - readback, plus Baseline media-type request/readback and output-order +- exact CBR, 3 Mbps and 60-frame GOP property + readback, plus Constrained Baseline media-type request/readback and output-order no-reordering checks; - 360 GPU-surface NV12 inputs and 360 ordered outputs; - one live `3 Mbps -> 1.5 Mbps -> 3 Mbps` rate change whose three equal phases lower and then restore actual encoded bytes without recreating the MFT; - Annex-B SPS/PPS/IDR at frames 0, 60, 120, 180, 240, and 300; -- an SPS `profile-level-id` exactly present in the fixture's default Pion - mode-1 fmtp set; and +- an SPS `profile-level-id` accepted by the production Constrained Baseline + coding-tool and level check; and - process-and-adapter-attributed Windows `VideoEncode` activity. The generated executable must stay outside the repository. From PowerShell: @@ -42,7 +42,7 @@ encoded bitstream. A nonzero exit is a measured no-go at the reported stage; it must not be worked around by adding a software retry. Pion transport and browser decode remain separate from this offline fixture; -the product path reuses its exact `42c01f`, Annex-B, adapter-bound hardware +the product path reuses the same Constrained Baseline, Annex-B, adapter-bound hardware contract without adding those network concerns to this executable. Primary API references, accessed 2026-08-20: diff --git a/src/client/components/living/LauncherForm.tsx b/src/client/components/living/LauncherForm.tsx index b36427d6b..908b25cb1 100644 --- a/src/client/components/living/LauncherForm.tsx +++ b/src/client/components/living/LauncherForm.tsx @@ -39,6 +39,8 @@ export function LauncherForm({ onModeChange, sites, startupSite, + ownedStartup, + ownedSites = [], onToggleStartupSite, onRemoveSite, onSelectSite, @@ -60,6 +62,8 @@ export function LauncherForm({ onModeChange: (mode: AppMode) => void; sites: readonly string[]; startupSite: string; + ownedStartup?: AppMode; + ownedSites?: readonly string[]; onToggleStartupSite: (site: string) => void; onRemoveSite: (site: string) => void; onSelectSite?: (site: string) => void; @@ -153,7 +157,7 @@ export function LauncherForm({ {sites.length > 0 &&
{sites.map((site, index) =>
{site}
- onToggleStartupSite(site)} /> { const button = standbyRef.current?.ownerDocument.activeElement; @@ -164,6 +168,11 @@ export function LauncherForm({
)}
} + {ownedStartup && } {roomError} {target ? {vis ? null : {t("client.launch.go")}} diff --git a/src/client/locales/en.ts b/src/client/locales/en.ts index 71aef416a..acbb5be6e 100644 --- a/src/client/locales/en.ts +++ b/src/client/locales/en.ts @@ -260,6 +260,7 @@ export const en: Record = { "client.connect.standbyHint": "Click App at the top right of a Piik site, choose Open App page, then confirm Allow access.", "client.connect.remove": "Revoke this Site's App access", "client.connect.openOnStart": "Open this site when App starts", + "client.connect.openOwnedOnStart": "Open my site when App starts ({mode})", "client.connect.manage": "App is ready. Manage App.", "client.connect.update": "App {current}. Update to {version}.", "client.connect.approveTitle": "Allow this Site to use Piik App?", diff --git a/src/client/locales/zh.ts b/src/client/locales/zh.ts index a305e3c7a..2bd13e437 100644 --- a/src/client/locales/zh.ts +++ b/src/client/locales/zh.ts @@ -260,6 +260,7 @@ export const zh = { "client.connect.standbyHint": "在 Piik 站点右上角点击 App,选择「打开 App 页面」,再确认「允许使用」。", "client.connect.remove": "取消此站点的 App 授权", "client.connect.openOnStart": "启动 App 时打开此站点", + "client.connect.openOwnedOnStart": "启动 App 时打开我的站点({mode})", "client.connect.manage": "App 已就绪,点击管理。", "client.connect.update": "App {current},可更新至 {version}。", "client.connect.approveTitle": "允许使用 Piik App?", diff --git a/src/client/pages/AppLauncherPage.tsx b/src/client/pages/AppLauncherPage.tsx index 99145baf7..84f957504 100644 --- a/src/client/pages/AppLauncherPage.tsx +++ b/src/client/pages/AppLauncherPage.tsx @@ -19,6 +19,8 @@ import { useReleaseUpdate } from "../lib/use-release-update"; const launcherStateSchema = z.object({ sites: z.array(z.string()), startupSite: z.string(), + ownedSites: z.array(z.string()).default([]), + startupMode: z.enum(["local", "link", ""]).nullish(), localAccessPassword: z.string(), defaultMode: z.enum(["local", "link"]), modes: z.array(z.enum(["local", "link"])).default(["local", "link"]), @@ -49,6 +51,8 @@ export function AppLauncherPage() { const [modes, setModes] = useState(["local", "link"]); const [sites, setSites] = useState([]); const [startupSite, setStartupSite] = useState(""); + const [ownedSites, setOwnedSites] = useState([]); + const [startupMode, setStartupMode] = useState(); const [openOnApproval, setOpenOnApproval] = useState(false); const [localAccessPassword, setLocalAccessPassword] = useState(""); const [error, setError] = useState<{ kind: "load" | "launch"; reason?: string; detail?: string } | null>(null); @@ -78,7 +82,7 @@ export function AppLauncherPage() { } catch { return false; } })(); const approvalCurrent = validSite && sites.includes(requestedSite); - const openSiteOnStart = Boolean(approvalCurrent && startupSite === requestedSite); + const openSiteOnStart = Boolean(approvalCurrent && (startupSite === requestedSite || startupMode && ownedSites.includes(requestedSite))); useEffect(() => { // The App's saved exact origin owns permission, including repeat connections. @@ -92,6 +96,7 @@ export function AppLauncherPage() { let current = true; let timer: ReturnType | undefined; let restoredSettings = false; + let enterOnReady = new URLSearchParams(window.location.search).get("start") === "1"; let reading = false; const readState = () => { if (reading || !current) return; @@ -115,6 +120,7 @@ export function AppLauncherPage() { setModes(state.modes); setLocalAccessPassword(state.localAccessPassword); setLan(state.lan); + if (state.startupMode && state.modes.includes(state.startupMode)) setMode(state.startupMode); restoredSettings = true; } setVersion(state.version === "development" && /^[a-f0-9]{40}$/i.test(state.revision) @@ -124,11 +130,17 @@ export function AppLauncherPage() { setStarting(state.starting === true); setSites(state.sites); setStartupSite(state.startupSite); + setStartupMode(state.startupMode || undefined); + setOwnedSites(state.ownedSites); setAppDebug(state.debug); setDebug(state.debug === true); setError(previous => state.detail ? { kind: "launch", reason: state.reason, detail: state.detail } - : previous?.kind === "load" ? null : previous); + : state.target || previous?.kind === "load" ? null : previous); setLoading(false); + if (enterOnReady && (state.target || state.detail)) { + enterOnReady = false; + if (state.target) window.location.replace(launchURL(state.target, { debug: state.debug === true, controlPort: state.controlPort })); + } if (state.starting) timer = setTimeout(() => void readState(), 750); setBuild({ version: state.version, revision: state.revision, packageTarget: state.packageTarget }); }) @@ -174,7 +186,7 @@ export function AppLauncherPage() { finally { finish(); setDebugBusy(false); } } - function launchURL(target: string): string { + function launchURL(target: string, settings = { debug: debug, controlPort }): string { const theme = currentThemePreference(); const presentation: ClientLaunchPresentation = { lang, vis, theme, @@ -183,7 +195,7 @@ export function AppLauncherPage() { ...(theme !== null ? ["theme" as const] : []), ], }; - return clientLaunchURL(target, presentation, debug, controlPort); + return clientLaunchURL(target, presentation, settings.debug, settings.controlPort); } async function launch(event: FormEvent): Promise { @@ -237,10 +249,12 @@ export function AppLauncherPage() { body: JSON.stringify({ site: nextSite, ...(setting === "site" ? { allowed } : {}) }), signal: controller.signal, }); - const result = launcherStateSchema.pick({ sites: true, startupSite: true }).safeParse(await response.json().catch(() => null)); + const result = launcherStateSchema.pick({ sites: true, startupSite: true, startupMode: true, ownedSites: true }).safeParse(await response.json().catch(() => null)); if (result.success) { setSites(result.data.sites); setStartupSite(result.data.startupSite); + setStartupMode(result.data.startupMode || undefined); + setOwnedSites(result.data.ownedSites); } if (response.status === 409 && result.success) { setSiteError(t("client.connect.changed")); @@ -356,7 +370,9 @@ export function AppLauncherPage() { setSiteError(undefined); }} startupSite={startupSite} - onToggleStartupSite={site => void changeSite(startupSite === site ? "" : site, "startup-site")} + ownedStartup={startupMode} + ownedSites={ownedSites} + onToggleStartupSite={site => void changeSite(startupSite === site || startupMode && ownedSites.includes(site) ? "" : site, "startup-site")} localAccessPassword={localAccessPassword} onModeChange={setMode} onRemoveSite={site => void changeSite(site, "site", false, false)} diff --git a/src/client/styles.css b/src/client/styles.css index 1bd82549f..ddced0ca5 100644 --- a/src/client/styles.css +++ b/src/client/styles.css @@ -1814,7 +1814,7 @@ body.lr-theater-open .lr-top { visibility: hidden; } .lr-top-right { gap: 8px; } .lr-leds { gap: 4px; padding: 6px; } .lr-top .lr-btn.is-compact { width: var(--control-compact-size); padding: 0; } - .lr-top .lr-btn.is-compact .lr-cap { display: none; } + .lr-top .lr-btn.is-compact .lr-cap:not([popover] .lr-cap) { display: none; } .lr-top .lr-header-options[popover] .lr-btn.is-compact { width: auto; padding-inline: 12px; } .lr-top .lr-header-options[popover] .lr-cap { display: inline; } .lr-top .lr-header-options[popover] .lr-help-content nav .lr-btn { width: 100%; } diff --git a/tests/app-launcher-recovery.test.ts b/tests/app-launcher-recovery.test.ts index d99d9b204..93d4a7f53 100644 --- a/tests/app-launcher-recovery.test.ts +++ b/tests/app-launcher-recovery.test.ts @@ -19,7 +19,7 @@ function collect(node: ts.Node): void { if (ts.isVariableDeclaration(node) && /^launcher.*Schema$/.test(node.name.getText(source))) { declarations.push(`const ${node.getText(source)};`); } - if (ts.isFunctionDeclaration(node) && ["beginStateChange", "changeSite", "approveSite", "enableDebug", "launch"].includes(node.name?.text ?? "")) { + if (ts.isFunctionDeclaration(node) && ["beginStateChange", "changeSite", "approveSite", "enableDebug", "launchURL", "launch"].includes(node.name?.text ?? "")) { declarations.push(node.getText(source)); } if (ts.isCallExpression(node) && node.expression.getText(source) === "useEffect" @@ -39,26 +39,26 @@ const saved = { revision: "test", version: "development", debug: false, lan: { addresses: [{ address: "192.0.2.1", name: "LAN" }], selected: "192.0.2.1" }, }; -const response = (state: typeof saved & { detail?: string } = saved) => ({ ok: true, status: 200, json: async () => state }); +const response = (state: typeof saved & { detail?: string; target?: string } = saved) => ({ ok: true, status: 200, json: async () => state }); -function mount(fetch: ReturnType, manualSite = false) { +function mount(fetch: ReturnType, manualSite = false, { startup = false }: { startup?: boolean } = {}) { const state: Record = {}; const setters = Object.fromEntries([ - "Mode", "Modes", "LocalAccessPassword", "Lan", "Version", "ControlPort", "Target", "Starting", "Sites", "StartupSite", + "Mode", "Modes", "LocalAccessPassword", "Lan", "Version", "ControlPort", "Target", "Starting", "Sites", "StartupSite", "StartupMode", "OwnedSites", "AppDebug", "Debug", "Error", "Loading", "Build", "RemoteControlPrototype", "SiteBusy", "SiteError", "DebugBusy", "DebugError", "Reload", ].map(name => [`set${name}`, vi.fn((value: unknown) => { state[name] = typeof value === "function" ? value(state[name]) : value; })])); - const window = Object.assign(new EventTarget(), { location: { replace: vi.fn() } }); + const window = Object.assign(new EventTarget(), { location: { replace: vi.fn(), search: startup ? "?start=1" : "" } }); const timers = new Map void; delay: number }>(); let nextTimer = 0; const actions = runInNewContext(executable, { - ...setters, z, fetch, window, + ...setters, z, fetch, window, URLSearchParams, stateChanges: { current: { revision: 0, pending: 0 } }, siteBusy: false, debugBusy: false, starting: false, sites: saved.sites, manualSite, openOnApproval: false, mode: "link", lang: "en", vis: false, debug: false, appDebug: false, localAccessPassword: "", - consoleLanguage: () => "en", launchURL: (target: string) => target, t: (key: string) => key, + consoleLanguage: () => "en", clientLaunchURL, currentThemePreference: () => null, hasCopyPreference: () => false, controlPort: undefined, t: (key: string) => key, AbortController, setTimeout: (callback: () => void, delay: number) => { const id = ++nextTimer; @@ -86,6 +86,32 @@ function mount(fetch: ReturnType, manualSite = false) { } describe("App launcher state recovery", () => { + it("offers an available mode after the saved startup mode becomes unavailable", async () => { + const page = mount(vi.fn().mockResolvedValue({ + ok: true, status: 200, json: async () => ({ + ...saved, modes: ["local"], startupMode: "link", detail: "public-link helper unavailable", + }), + }), false, { startup: true }); + try { + await settle(); + expect(page.state).toMatchObject({ Mode: "local", StartupMode: "link", Error: { kind: "launch" } }); + expect(page.navigate).not.toHaveBeenCalled(); + } finally { page.cleanup(); } + }); + it("replaces a failed launch response with the running App's state on return", async () => { + const fetch = vi.fn().mockResolvedValueOnce(response(saved)) + .mockRejectedValueOnce(new Error("Startup response disconnected")); + const page = mount(fetch); + try { + await settle(); + await page.launch({ preventDefault() {} }); + expect(page.state.Error).toEqual({ kind: "launch" }); + fetch.mockResolvedValueOnce(response({ ...saved, target: "http://127.0.0.1:8791/" })); + page.focus(); await settle(); + expect(page.state).toMatchObject({ Target: "http://127.0.0.1:8791/", Starting: false, Error: null }); + expect(page.navigate).not.toHaveBeenCalled(); + } finally { page.cleanup(); } + }); it.each([ ["v2.4.1", "v2.4.1"], ["development", "development (aaaaaaa)"], @@ -113,7 +139,7 @@ describe("App launcher state recovery", () => { expect(page.state).toMatchObject({ Starting: false, Error: { kind: "launch", detail: "Startup failed" } }); fetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ target: "https://room.example/#piik-client=1" }) }); await page.launch(event); - expect(page.navigate).toHaveBeenCalledWith("https://room.example/#piik-client=1"); + expect(page.navigate).toHaveBeenCalledWith("https://room.example/#piik-client=1&piik-lang=en&piik-mode=text&piik-theme=system"); page.cleanup(); }); @@ -128,6 +154,7 @@ describe("App launcher state recovery", () => { expect(html).toContain('value="saved password"'); expect(html).toMatch(/type="submit"[^>]*aria-label="(?:Retry|重试)"/); expect(html).toContain(saved.sites[0]); + expect(html).toContain('aria-pressed="false"'); }); it("reopens a healthy room without offering another mode or password", () => { @@ -181,7 +208,7 @@ describe("App launcher state recovery", () => { expect(page.state.SiteError).toBe("client.connect.saveFailed"); fetch.mockResolvedValueOnce(response({ ...saved, sites: [...saved.sites, "https://next.example"] })); await page.approveSite("https://next.example"); - if (manual) expect(page.navigate).toHaveBeenCalledWith("https://next.example/#piik-client=1"); + if (manual) expect(page.navigate).toHaveBeenCalledWith("https://next.example/#piik-client=1&piik-lang=en&piik-mode=text&piik-theme=system"); else expect(page.navigate).not.toHaveBeenCalled(); expect(fetch.mock.calls[1]).toEqual(["/api/client-launcher/site", expect.objectContaining({ body: JSON.stringify({ site: "https://next.example", allowed: true }), @@ -239,7 +266,7 @@ describe("App launcher state recovery", () => { expect(page.navigate).not.toHaveBeenCalled(); fetch.mockResolvedValueOnce(response({ ...saved, sites: [...saved.sites, "https://next.example"] })); await page.approveSite("https://next.example"); - expect(page.navigate).toHaveBeenCalledWith("https://next.example/#piik-client=1"); + expect(page.navigate).toHaveBeenCalledWith("https://next.example/#piik-client=1&piik-lang=en&piik-mode=text&piik-theme=system"); expect(page.state.SiteBusy).toBe(false); page.cleanup(); }); @@ -364,3 +391,69 @@ describe("App launcher state recovery", () => { page.cleanup(); }); }); + +it("enters the fresh App-owned startup result once with its current debug setting and port", async () => { + vi.stubGlobal("window", { location: { href: "http://127.0.0.1:39731/client?start=1" } }); + const fetch = vi.fn().mockResolvedValueOnce(response({ ...saved, starting: true } as typeof saved)); + const page = mount(fetch, false, { startup: true }); + try { + await settle(); + expect(page.navigate).not.toHaveBeenCalled(); + const fresh = "http://127.0.0.1:45678/#piik-client=1"; + fetch.mockResolvedValue({ ok: true, status: 200, json: async () => ({ ...saved, target: fresh, debug: true, controlPort: 39732 }) }); + page.retry(); + await settle(); + const destination = new URL(page.navigate.mock.calls[0]![0]); + expect(destination.origin).toBe("http://127.0.0.1:45678"); + expect(destination.searchParams.get("debug")).toBe("1"); + expect(destination.searchParams.get("piik-client-port")).toBe("39732"); + page.focus(); + await settle(); + expect(page.navigate).toHaveBeenCalledTimes(1); + expect(fetch.mock.calls.every(call => !call[1]?.method)).toBe(true); + } finally { + page.cleanup(); + vi.unstubAllGlobals(); + } +}); + +it("leaves a failed owned startup available for manual retry", async () => { + const fetch = vi.fn().mockResolvedValueOnce(response({ ...saved, detail: "tunnel failed" })); + const page = mount(fetch, false, { startup: true }); + try { + await settle(); + expect(page.state.Starting).toBe(false); + expect(page.state.Error).toMatchObject({ kind: "launch" }); + fetch.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ target: "http://127.0.0.1:45678/" }) }); + await page.launch({ preventDefault() {} }); + expect(page.navigate).toHaveBeenCalledTimes(1); + } finally { page.cleanup(); } +}); + +it("clears an owned startup from the existing settings operation", async () => { + const fetch = vi.fn().mockResolvedValueOnce({ + ok: true, status: 200, json: async () => ({ ...saved, startupMode: "link", ownedSites: ["https://current.example"] }), + }); + const page = mount(fetch); + try { + await settle(); + expect(page.state.StartupMode).toBe("link"); + fetch.mockResolvedValueOnce(response(saved)); + expect(await page.changeSite("", "startup-site")).toBe(true); + expect(JSON.parse(fetch.mock.calls[1]![1].body)).toEqual({ site: "" }); + expect(page.state.StartupMode).toBeUndefined(); + expect(page.navigate).not.toHaveBeenCalled(); + } finally { page.cleanup(); } +}); + + +it.each(["local", "link"] as const)("names the owned startup site and saved %s mode", mode => { + const html = renderToStaticMarkup(createElement(LauncherForm, { + mode, sites: saved.sites, startupSite: "", ownedStartup: mode, + onModeChange() {}, onToggleStartupSite() {}, onRemoveSite() {}, onSubmit() {}, + localAccessPassword: "", onLocalAccessPasswordChange() {}, + })); + expect(html).toMatch(/my site|我的站点/); + expect(html).toMatch(mode === "local" ? /Local room|本地房间/ : /Public invite|公网邀请/); + expect(html).toMatch(/type="checkbox"[^>]*checked/); +});