Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions e2e/tests/header-ui-scale.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { test, expect, collapseScratchpad } from "../lib/test";
import type { Page } from "@playwright/test";

// Phone header at every UI scale step ("tamanho da fonte", 80%–150%).
// The scale is CSS zoom on <html>, so 390px at 150% leaves only 260 CSS px
// for the header. Every header action — especially the + new-session button —
// must stay fully inside the viewport and not overlap its neighbours.

const SCALES = [80, 90, 100, 110, 120, 130, 140, 150];
const BUTTONS = [
".session-header-back",
"#tree-toggle",
".session-header-projects",
".zc-theme-btn",
".session-header-schedules",
"#new-session-header-btn",
"#toggle-right-sidebar-btn",
"#command-menu-btn",
];

async function openDemoSession(page: Page) {
await collapseScratchpad(page);
await page.goto("/");
await page.locator(".session-card", { hasText: "add deepseek-v4-pro" }).click();
await expect(page).toHaveURL(/\/session\?id=/);
await page.locator(".session-header-bar").waitFor();
}

test.describe("session header at 390px across UI scales", () => {
test.use({ viewport: { width: 390, height: 844 } });

for (const scale of SCALES) {
test(`all header buttons visible at ${scale}%`, async ({ page }) => {
await openDemoSession(page);
await page.evaluate((v) => {
const root = document.documentElement;
if (v === 100) {
delete root.dataset.uiScale;
root.style.removeProperty("zoom");
} else {
root.dataset.uiScale = String(v);
root.style.zoom = String(v / 100);
}
window.dispatchEvent(new Event("resize"));
}, scale);
// Worst case on the multi-user hub: a colleague's session shows a long
// owner badge in the right cluster. Inject one when the server isn't in
// multi-user mode so the budget always includes it.
await page.evaluate(() => {
const right = document.querySelector(".session-header-right");
if (right && !right.querySelector(".session-owner-badge")) {
const badge = document.createElement("span");
badge.className = "session-owner-badge others";
badge.textContent = "de Henrique Fiuza · claude-code";
right.prepend(badge);
}
});
await page.waitForTimeout(100);

const viewport = page.viewportSize()!;
const boxes: { sel: string; x: number; r: number }[] = [];
for (const sel of BUTTONS) {
const loc = page.locator(`.session-header-bar ${sel}`).first();
await expect(loc, `${sel} at ${scale}%`).toBeVisible();
const b = (await loc.boundingBox())!;
expect(b.width, `${sel} width at ${scale}%`).toBeGreaterThanOrEqual(20);
expect(b.x, `${sel} left edge at ${scale}%`).toBeGreaterThanOrEqual(0);
expect(b.x + b.width, `${sel} right edge at ${scale}%`).toBeLessThanOrEqual(
viewport.width + 0.5,
);
boxes.push({ sel, x: b.x, r: b.x + b.width });
}
// No two buttons overlap horizontally (they share one row).
const sorted = [...boxes].sort((a, b) => a.x - b.x);
for (let i = 1; i < sorted.length; i++) {
expect(
sorted[i].x,
`${sorted[i].sel} overlaps ${sorted[i - 1].sel} at ${scale}%`,
).toBeGreaterThanOrEqual(sorted[i - 1].r - 0.5);
}
// The + button is really clickable (not covered by title/badge).
const plus = (await page.locator("#new-session-header-btn").boundingBox())!;
const hit = await page.evaluate(
([x, y]) => document.elementFromPoint(x, y)?.closest("#new-session-header-btn") != null,
[plus.x + plus.width / 2, plus.y + plus.height / 2],
);
expect(hit, `+ button hit-test at ${scale}%`).toBe(true);
if (process.env.HEADER_SHOT_DIR) {
await page.screenshot({
path: `${process.env.HEADER_SHOT_DIR}/header-${scale}.png`,
clip: { x: 0, y: 0, width: viewport.width, height: 80 },
});
}
});
}
});
37 changes: 36 additions & 1 deletion internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"os"
"os/signal"
"path/filepath"
"pi-web/internal/identity"
"strings"
"syscall"
"time"

Expand Down Expand Up @@ -97,18 +99,26 @@ func Main(version string) {
RunInstall: runInstall,
RunRestart: runRestart,
DisableBackgroundJobs: developmentMode,
MultiUser: os.Getenv("PI_WEB_MULTIUSER") == "1",
Identity: newIdentityResolver(),
})
if srvErr != nil {
fmt.Fprintf(os.Stderr, "failed to initialize server: %v\n", srvErr)
os.Exit(1)
}

ui.SetThemeProvider(srv.ThemeSetting)
ui.SetPresetProvider(srv.ZcodePresetSetting)
ui.SetActProvider(srv.ZcodeActSetting)
ui.SetScaleProvider(srv.UIScaleSetting)
ui.SetFontProvider(srv.FontStyles)

mux := http.NewServeMux()
srv.Register(mux)
ui.RegisterPWAHandlers(mux)
// Compress HTML/JSON responses for slow links (mobile, remote desktops).
// SSE and already-compressed assets are skipped inside the handler itself.
gzMux := server.GzipMiddleware(mux)
dfs := web.DistFS()
if scripts, err := frontend.LoadScripts(dfs, frontend.AppEntry); err == nil {
for _, script := range scripts {
Expand Down Expand Up @@ -192,7 +202,7 @@ func Main(version string) {

httpServer := &http.Server{
Addr: addr,
Handler: mux,
Handler: gzMux,
ReadHeaderTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
// WriteTimeout intentionally 0 — SSE streams are long-lived.
Expand Down Expand Up @@ -229,6 +239,21 @@ func Main(version string) {
shutdownCode <- code
}()

// PI_WEB_EXTRA_LISTEN (e.g. "100.67.73.47:31416") serves the same app on a
// second address — used on the Symetrix hub to keep a plain tailnet-IP URL
// alive next to the `tailscale serve` HTTPS one. Callers there are
// identified by `tailscale whois`, never by headers.
if extra := strings.TrimSpace(os.Getenv("PI_WEB_EXTRA_LISTEN")); extra != "" {
authMiddleware.AllowHost(extra)
extraServer := &http.Server{Addr: extra, Handler: gzMux, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 120 * time.Second}
go func() {
if err := extraServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Fprintf(os.Stderr, "extra listener %s: %v\n", extra, err)
}
}()
fmt.Printf("Also listening on http://%s\n", extra)
}

serveErr := httpServer.ListenAndServe()
if serveErr != nil && serveErr != http.ErrServerClosed {
fmt.Fprintf(os.Stderr, "server error: %v\n", serveErr)
Expand All @@ -238,3 +263,13 @@ func Main(version string) {
// the sole Shutdown caller; wait so cleanup is not cut short by exiting.
os.Exit(<-shutdownCode)
}

// newIdentityResolver builds the multi-user identity resolver from env:
// PI_WEB_FALLBACK_OWNER (login for non-tailnet callers; empty = no access) and
// PI_WEB_TRUST_SERVE_HEADERS=1 (trust Tailscale-User-Login from loopback; only
// for a 127.0.0.1 bind behind `tailscale serve` in HTTP proxy mode).
func newIdentityResolver() *identity.Resolver {
r := identity.NewResolver(os.Getenv("PI_WEB_FALLBACK_OWNER"))
r.TrustServeHeaders = os.Getenv("PI_WEB_TRUST_SERVE_HEADERS") == "1"
return r
}
180 changes: 180 additions & 0 deletions internal/identity/identity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
// Package identity resolves which person is making a request to a multi-user
// pi-web hub. Identity comes from the tailnet itself, never from a value the
// browser can choose:
//
// 1. Requests proxied by `tailscale serve` arrive from loopback and carry the
// Tailscale-User-Login / Tailscale-User-Name headers, which tailscaled sets
// (and strips from client requests). They are only trusted from loopback.
// 2. Requests that reach pi-web directly on its tailnet IP come from a
// 100.64.0.0/10 (or fd7a:115c:a1e0::/48) peer address; the login is looked
// up with `tailscale whois --json <ip>` and cached.
// 3. Anything else (plain loopback, LAN) maps to the configured fallback
// owner, or to an anonymous identity.
package identity

import (
"context"
"encoding/json"
"net"
"net/http"
"net/netip"
"os/exec"
"strings"
"sync"
"time"
)

// User is a resolved person.
type User struct {
Login string `json:"login"` // e.g. vinicius@symetrixtrading.com
Name string `json:"name"` // display name, e.g. "Vinicius"
Short string `json:"short"` // e.g. "vinicius" (login local part)
Via string `json:"via"` // "serve-header" | "whois" | "fallback" | "anonymous"
}

// Known reports whether the user has a real login.
func (u User) Known() bool { return u.Login != "" }

// WhoisFunc looks up a tailnet peer IP. It returns login and display name.
type WhoisFunc func(ctx context.Context, ip string) (login, name string, err error)

// Resolver maps HTTP requests to users.
type Resolver struct {
Whois WhoisFunc
Fallback string // login used for non-tailnet, header-less requests
// TrustServeHeaders accepts Tailscale-User-Login from loopback peers. Only
// enable it when pi-web binds 127.0.0.1 behind `tailscale serve` (HTTP
// proxy mode); otherwise identity headers are always ignored.
TrustServeHeaders bool
TTL time.Duration
now func() time.Time

mu sync.Mutex
cache map[string]cachedUser
}

type cachedUser struct {
user User
expires time.Time
}

// NewResolver returns a resolver that shells out to the tailscale CLI.
func NewResolver(fallback string) *Resolver {
return &Resolver{Whois: TailscaleWhois, Fallback: fallback, TTL: 10 * time.Minute}
}

var (
cgnat = netip.MustParsePrefix("100.64.0.0/10")
tsULA = netip.MustParsePrefix("fd7a:115c:a1e0::/48")
)

// ShortName returns the local part of a login (before '@'), lowercased.
func ShortName(login string) string {
l := strings.ToLower(strings.TrimSpace(login))
if i := strings.IndexByte(l, '@'); i > 0 {
return l[:i]
}
return l
}

func makeUser(login, name, via string) User {
login = strings.ToLower(strings.TrimSpace(login))
if name == "" {
name = ShortName(login)
}
return User{Login: login, Name: name, Short: ShortName(login), Via: via}
}

func remoteAddr(r *http.Request) (netip.Addr, bool) {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr
}
a, err := netip.ParseAddr(host)
if err != nil {
return netip.Addr{}, false
}
return a.Unmap(), true
}

// IsTailnetAddr reports whether a is a Tailscale peer address.
func IsTailnetAddr(a netip.Addr) bool { return cgnat.Contains(a) || tsULA.Contains(a) }

// Identify resolves the user behind r.
func (res *Resolver) Identify(r *http.Request) User {
if res == nil {
return User{Via: "anonymous"}
}
addr, ok := remoteAddr(r)
if ok && addr.IsLoopback() && res.TrustServeHeaders {
if login := r.Header.Get("Tailscale-User-Login"); login != "" {
return makeUser(login, r.Header.Get("Tailscale-User-Name"), "serve-header")
}
}
if ok && IsTailnetAddr(addr) && res.Whois != nil {
if u, ok := res.lookup(r.Context(), addr.String()); ok {
return u
}
}
if res.Fallback != "" {
return makeUser(res.Fallback, "", "fallback")
}
return User{Via: "anonymous"}
}

func (res *Resolver) clock() time.Time {
if res.now != nil {
return res.now()
}
return time.Now()
}

func (res *Resolver) lookup(ctx context.Context, ip string) (User, bool) {
res.mu.Lock()
if c, ok := res.cache[ip]; ok && res.clock().Before(c.expires) {
res.mu.Unlock()
return c.user, true
}
res.mu.Unlock()
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
login, name, err := res.Whois(ctx, ip)
if err != nil || login == "" || strings.HasPrefix(login, "tagged-devices") {
return User{}, false
}
u := makeUser(login, name, "whois")
ttl := res.TTL
if ttl <= 0 {
ttl = 10 * time.Minute
}
res.mu.Lock()
if res.cache == nil {
res.cache = map[string]cachedUser{}
}
res.cache[ip] = cachedUser{user: u, expires: res.clock().Add(ttl)}
res.mu.Unlock()
return u, true
}

// TailscaleWhois runs `tailscale whois --json <ip>`.
func TailscaleWhois(ctx context.Context, ip string) (string, string, error) {
out, err := exec.CommandContext(ctx, "tailscale", "whois", "--json", ip).Output()
if err != nil {
return "", "", err
}
return ParseWhoisJSON(out)
}

// ParseWhoisJSON extracts login and display name from `tailscale whois --json`.
func ParseWhoisJSON(b []byte) (string, string, error) {
var w struct {
UserProfile struct {
LoginName string `json:"LoginName"`
DisplayName string `json:"DisplayName"`
} `json:"UserProfile"`
}
if err := json.Unmarshal(b, &w); err != nil {
return "", "", err
}
return w.UserProfile.LoginName, w.UserProfile.DisplayName, nil
}
Loading