diff --git a/e2e/tests/header-ui-scale.spec.ts b/e2e/tests/header-ui-scale.spec.ts new file mode 100644 index 00000000..8d8258e8 --- /dev/null +++ b/e2e/tests/header-ui-scale.spec.ts @@ -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 , 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 }, + }); + } + }); + } +}); diff --git a/internal/app/app.go b/internal/app/app.go index e5a0f33c..e99c80a5 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -10,6 +10,8 @@ import ( "os" "os/signal" "path/filepath" + "pi-web/internal/identity" + "strings" "syscall" "time" @@ -97,6 +99,8 @@ 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) @@ -104,11 +108,17 @@ func Main(version string) { } 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 { @@ -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. @@ -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) @@ -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 +} diff --git a/internal/identity/identity.go b/internal/identity/identity.go new file mode 100644 index 00000000..027b471b --- /dev/null +++ b/internal/identity/identity.go @@ -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 ` 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 `. +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 +} diff --git a/internal/identity/identity_test.go b/internal/identity/identity_test.go new file mode 100644 index 00000000..544ae43c --- /dev/null +++ b/internal/identity/identity_test.go @@ -0,0 +1,84 @@ +package identity + +import ( + "context" + "errors" + "net/http/httptest" + "testing" +) + +func TestIdentifyServeHeaderOnlyFromLoopback(t *testing.T) { + // Header trust is off by default. + off := &Resolver{} + r0 := httptest.NewRequest("GET", "/", nil) + r0.RemoteAddr = "127.0.0.1:5555" + r0.Header.Set("Tailscale-User-Login", "ana@symetrix.com") + if u := off.Identify(r0); u.Known() { + t.Fatalf("header trusted without TrustServeHeaders: %+v", u) + } + res := &Resolver{TrustServeHeaders: true} + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr = "127.0.0.1:5555" + r.Header.Set("Tailscale-User-Login", "Ana@Symetrix.com") + r.Header.Set("Tailscale-User-Name", "Ana Lima") + u := res.Identify(r) + if u.Login != "ana@symetrix.com" || u.Name != "Ana Lima" || u.Short != "ana" || u.Via != "serve-header" { + t.Fatalf("unexpected user %+v", u) + } + // Spoofed header from a non-loopback peer must be ignored. + r2 := httptest.NewRequest("GET", "/", nil) + r2.RemoteAddr = "192.168.1.9:5555" + r2.Header.Set("Tailscale-User-Login", "boss@symetrix.com") + if u := res.Identify(r2); u.Known() { + t.Fatalf("spoofed header accepted: %+v", u) + } +} + +func TestIdentifyWhoisAndCache(t *testing.T) { + calls := 0 + res := &Resolver{Whois: func(ctx context.Context, ip string) (string, string, error) { + calls++ + if ip != "100.70.165.106" { + t.Fatalf("ip %s", ip) + } + return "vinicius@symetrixtrading.com", "Vinicius", nil + }} + for i := 0; i < 3; i++ { + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr = "100.70.165.106:1234" + r.Header.Set("Tailscale-User-Login", "ignored@x.com") + u := res.Identify(r) + if u.Short != "vinicius" || u.Via != "whois" { + t.Fatalf("unexpected %+v", u) + } + } + if calls != 1 { + t.Fatalf("whois called %d times, want 1 (cached)", calls) + } +} + +func TestIdentifyFallbackAndTagged(t *testing.T) { + res := &Resolver{Fallback: "symetrix", Whois: func(context.Context, string) (string, string, error) { + return "tagged-devices", "", nil + }} + r := httptest.NewRequest("GET", "/", nil) + r.RemoteAddr = "100.89.162.73:1" + if u := res.Identify(r); u.Via != "fallback" || u.Login != "symetrix" { + t.Fatalf("tagged device should fall back: %+v", u) + } + res.Whois = func(context.Context, string) (string, string, error) { return "", "", errors.New("x") } + if u := res.Identify(r); u.Via != "fallback" { + t.Fatalf("whois error should fall back: %+v", u) + } + res.Fallback = "" + if u := res.Identify(r); u.Known() { + t.Fatalf("want anonymous, got %+v", u) + } +} + +func TestParseWhoisJSON(t *testing.T) { + l, n, err := ParseWhoisJSON([]byte(`{"Node":{},"UserProfile":{"LoginName":"a@b.c","DisplayName":"A B"}}`)) + if err != nil || l != "a@b.c" || n != "A B" { + t.Fatalf("%q %q %v", l, n, err) + } +} diff --git a/internal/render/etag.go b/internal/render/etag.go new file mode 100644 index 00000000..6d52f7e9 --- /dev/null +++ b/internal/render/etag.go @@ -0,0 +1,61 @@ +package render + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "strings" +) + +// WriteJSONConditional writes payload as JSON with a strong ETag over the +// exact encoded bytes. A request whose If-None-Match matches returns 304 with +// no body, so repeat fetches of an unchanged payload cost a header round trip +// instead of the full transfer. Responses carry Cache-Control: private, +// must-revalidate — the browser may store them (auth-scoped data must not sit +// in shared caches) and must revalidate before every reuse, so a stale copy +// is never shown. Returns true when it wrote a bare 304. +func WriteJSONConditional(w http.ResponseWriter, r *http.Request, payload any) bool { + body, err := json.Marshal(payload) + if err != nil { + WriteJSONError(w, http.StatusInternalServerError, err.Error()) + return false + } + etag := ETagOf(body) + w.Header().Set("ETag", etag) + w.Header().Set("Cache-Control", "private, must-revalidate") + if MatchesETag(r.Header.Get("If-None-Match"), etag) { + w.WriteHeader(http.StatusNotModified) + return true + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(body) + return false +} + +// ETagOf returns a strong ETag (quoted) for the exact content bytes. +func ETagOf(body []byte) string { + sum := sha256.Sum256(body) + return `"` + hex.EncodeToString(sum[:16]) + `"` +} + +// MatchesETag reports whether an If-None-Match header matches etag, +// tolerating weak (W/) candidates and comma-separated lists per RFC 7232. +func MatchesETag(header, etag string) bool { + header = strings.TrimSpace(header) + if header == "" { + return false + } + if header == "*" { + return true + } + bare := strings.Trim(etag, `"`) + for _, part := range strings.Split(header, ",") { + cand := strings.TrimPrefix(strings.TrimSpace(part), "W/") + cand = strings.Trim(cand, `"`) + if cand != "" && cand == bare { + return true + } + } + return false +} diff --git a/internal/render/etag_test.go b/internal/render/etag_test.go new file mode 100644 index 00000000..bda7eb7c --- /dev/null +++ b/internal/render/etag_test.go @@ -0,0 +1,77 @@ +package render + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestWriteJSONConditionalServesBodyAndETag(t *testing.T) { + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodGet, "/x", nil) + if WriteJSONConditional(w, r, map[string]string{"a": "b"}) { + t.Fatal("first call must not 304") + } + if w.Header().Get("ETag") == "" { + t.Fatal("missing ETag") + } + if w.Header().Get("Cache-Control") != "private, must-revalidate" { + t.Fatalf("Cache-Control = %q", w.Header().Get("Cache-Control")) + } + if w.Body.String() != `{"a":"b"}` { + t.Fatalf("body = %q", w.Body.String()) + } +} + +func TestWriteJSONConditionalReturns304(t *testing.T) { + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodGet, "/x", nil) + WriteJSONConditional(w, r, map[string]string{"a": "b"}) + etag := w.Header().Get("ETag") + + w2 := httptest.NewRecorder() + r2 := httptest.NewRequest(http.MethodGet, "/x", nil) + r2.Header.Set("If-None-Match", etag) + if !WriteJSONConditional(w2, r2, map[string]string{"a": "b"}) { + t.Fatal("matching etag must 304") + } + if w2.Code != http.StatusNotModified || w2.Body.Len() != 0 { + t.Fatalf("code=%d body=%q", w2.Code, w2.Body.String()) + } +} + +func TestWriteJSONConditionalChangedPayload(t *testing.T) { + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodGet, "/x", nil) + WriteJSONConditional(w, r, map[string]string{"a": "b"}) + etag := w.Header().Get("ETag") + + w2 := httptest.NewRecorder() + r2 := httptest.NewRequest(http.MethodGet, "/x", nil) + r2.Header.Set("If-None-Match", etag) + if WriteJSONConditional(w2, r2, map[string]string{"a": "c"}) { + t.Fatal("changed payload must 200") + } + if w2.Code != http.StatusOK || w2.Body.String() != `{"a":"c"}` { + t.Fatalf("code=%d body=%q", w2.Code, w2.Body.String()) + } +} + +func TestMatchesETagWeakAndList(t *testing.T) { + etag := ETagOf([]byte("x")) + if !MatchesETag(`W/`+etag, etag) { + t.Fatal("weak candidate must match") + } + if !MatchesETag(`"other", `+etag, etag) { + t.Fatal("list containing etag must match") + } + if MatchesETag(`"other"`, etag) { + t.Fatal("different etag must not match") + } + if MatchesETag("", etag) { + t.Fatal("empty header must not match") + } + if !MatchesETag("*", etag) { + t.Fatal("* must match") + } +} diff --git a/internal/rpc/stream.go b/internal/rpc/stream.go index c23516c9..db772c5a 100644 --- a/internal/rpc/stream.go +++ b/internal/rpc/stream.go @@ -3,6 +3,8 @@ package rpc type StreamPreview struct { Content string `json:"content"` Done bool `json:"done"` + // Tool, when set, is a live tool progress update (not text preview). + Tool *ToolProgress `json:"tool,omitempty"` } type StreamEventSink func(StreamPreview) diff --git a/internal/rpc/tool_progress.go b/internal/rpc/tool_progress.go new file mode 100644 index 00000000..264a5470 --- /dev/null +++ b/internal/rpc/tool_progress.go @@ -0,0 +1,186 @@ +package rpc + +// Live progress for long-running tools (the subagent extension). pi emits +// tool_execution_update events with the tool's latest partial result; for +// subagent that is the full child transcript, so it is compacted here to what +// the browser card shows (agent, status, model, usage, last few items, final +// text) and throttled per tool call before being broadcast over SSE. + +import ( + "encoding/json" + "sync" + "time" +) + +// ToolProgress is broadcast as the "tool-progress" SSE event. +type ToolProgress struct { + ToolCallID string `json:"toolCallId"` + ToolName string `json:"toolName"` + Details json.RawMessage `json:"details"` +} + +const ( + toolProgressInterval = 400 * time.Millisecond + progressTextLimit = 4000 + progressTaskLimit = 400 + progressItemsKept = 6 +) + +// liveProgressTools lists tool names whose partial results are forwarded. +var liveProgressTools = map[string]bool{"subagent": true} + +type toolProgressThrottle struct { + mu sync.Mutex + last map[string]time.Time + now func() time.Time +} + +func newToolProgressThrottle() *toolProgressThrottle { + return &toolProgressThrottle{last: map[string]time.Time{}, now: time.Now} +} + +func (t *toolProgressThrottle) allow(id string) bool { + t.mu.Lock() + defer t.mu.Unlock() + n := t.now() + if prev, ok := t.last[id]; ok && n.Sub(prev) < toolProgressInterval { + return false + } + t.last[id] = n + if len(t.last) > 256 { // forget old calls + for k, v := range t.last { + if n.Sub(v) > time.Hour { + delete(t.last, k) + } + } + } + return true +} + +type progressItem struct { + Kind string `json:"kind"` // "tool" | "text" + Name string `json:"name,omitempty"` + Text string `json:"text"` +} + +type progressResult struct { + Agent string `json:"agent"` + Task string `json:"task"` + Status string `json:"status,omitempty"` + Model string `json:"model,omitempty"` + Step int `json:"step,omitempty"` + Exit *int `json:"exitCode,omitempty"` + Usage json.RawMessage `json:"usage,omitempty"` + Items []progressItem `json:"items,omitempty"` + Output string `json:"output,omitempty"` + Error string `json:"errorMessage,omitempty"` +} + +type progressDetails struct { + Mode string `json:"mode"` + Results []progressResult `json:"results"` +} + +func clip(s string, n int) string { + r := []rune(s) + if len(r) <= n { + return s + } + return string(r[:n]) + "…" +} + +func clipTail(s string, n int) string { + r := []rune(s) + if len(r) <= n { + return s + } + return "…" + string(r[len(r)-n:]) +} + +// compactSubagentDetails shrinks subagent partial details to a card summary. +func compactSubagentDetails(raw json.RawMessage) (json.RawMessage, bool) { + var in struct { + Mode string `json:"mode"` + Results []struct { + Agent string `json:"agent"` + Task string `json:"task"` + Status string `json:"status"` + Model string `json:"model"` + Step int `json:"step"` + ExitCode *int `json:"exitCode"` + Usage json.RawMessage `json:"usage"` + ErrorMessage string `json:"errorMessage"` + Messages []struct { + Role string `json:"role"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + Name string `json:"name"` + Arguments json.RawMessage `json:"arguments"` + } `json:"content"` + } `json:"messages"` + } `json:"results"` + } + if err := json.Unmarshal(raw, &in); err != nil || len(in.Results) == 0 { + return nil, false + } + out := progressDetails{Mode: in.Mode} + for _, r := range in.Results { + pr := progressResult{ + Agent: r.Agent, Task: clip(r.Task, progressTaskLimit), Status: r.Status, + Model: r.Model, Step: r.Step, Exit: r.ExitCode, Usage: r.Usage, + Error: clip(r.ErrorMessage, 600), + } + var items []progressItem + for _, m := range r.Messages { + if m.Role != "assistant" { + continue + } + for _, c := range m.Content { + switch c.Type { + case "toolCall": + items = append(items, progressItem{Kind: "tool", Name: c.Name, Text: clip(string(c.Arguments), 160)}) + case "text": + if c.Text != "" { + items = append(items, progressItem{Kind: "text", Text: clip(c.Text, 240)}) + pr.Output = c.Text + } + } + } + } + if len(items) > progressItemsKept { + items = items[len(items)-progressItemsKept:] + } + pr.Items = items + pr.Output = clipTail(pr.Output, progressTextLimit) + out.Results = append(out.Results, pr) + } + b, err := json.Marshal(out) + if err != nil { + return nil, false + } + return b, true +} + +// parseToolProgress turns a tool_execution_update RPC line into a broadcastable +// progress event (nil when the tool isn't tracked or the payload is unusable). +func parseToolProgress(line string) *ToolProgress { + var ev struct { + ToolCallID string `json:"toolCallId"` + ToolName string `json:"toolName"` + PartialResult struct { + Details json.RawMessage `json:"details"` + } `json:"partialResult"` + } + if err := json.Unmarshal([]byte(line), &ev); err != nil { + return nil + } + if ev.ToolCallID == "" || !liveProgressTools[ev.ToolName] { + return nil + } + d, ok := compactSubagentDetails(ev.PartialResult.Details) + if !ok { + return nil + } + return &ToolProgress{ToolCallID: ev.ToolCallID, ToolName: ev.ToolName, Details: d} +} diff --git a/internal/rpc/tool_progress_test.go b/internal/rpc/tool_progress_test.go new file mode 100644 index 00000000..82339d4e --- /dev/null +++ b/internal/rpc/tool_progress_test.go @@ -0,0 +1,64 @@ +package rpc + +import ( + "encoding/json" + "strings" + "testing" + "time" +) + +func TestParseToolProgressCompactsSubagent(t *testing.T) { + long := strings.Repeat("x", 9000) + line := `{"type":"tool_execution_update","toolCallId":"c1","toolName":"subagent","partialResult":{"content":[],"details":{"mode":"parallel","results":[` + + `{"agent":"scout","task":"find models","status":"running","model":"router/glm-5.3","messages":[{"role":"assistant","content":[{"type":"toolCall","name":"grep","arguments":{"pattern":"model"}},{"type":"text","text":"` + long + `"}]}]},` + + `{"agent":"scout","task":"find providers","status":"pending","messages":[]}]}}}` + tp := parseToolProgress(line) + if tp == nil { + t.Fatal("expected progress") + } + if tp.ToolCallID != "c1" || tp.ToolName != "subagent" { + t.Fatalf("bad ids: %+v", tp) + } + var d progressDetails + if err := json.Unmarshal(tp.Details, &d); err != nil { + t.Fatal(err) + } + if d.Mode != "parallel" || len(d.Results) != 2 { + t.Fatalf("bad details: %+v", d) + } + r := d.Results[0] + if r.Status != "running" || r.Model != "router/glm-5.3" || len(r.Items) != 2 || r.Items[0].Name != "grep" { + t.Fatalf("bad result: %+v", r) + } + if n := len([]rune(r.Output)); n > progressTextLimit+1 { + t.Fatalf("output not clipped: %d", n) + } + if len(tp.Details) > 8000 { + t.Fatalf("details too large: %d", len(tp.Details)) + } +} + +func TestParseToolProgressIgnoresOtherTools(t *testing.T) { + if parseToolProgress(`{"type":"tool_execution_update","toolCallId":"c","toolName":"bash","partialResult":{"details":{}}}`) != nil { + t.Fatal("bash must not be forwarded") + } + if parseToolProgress(`not json`) != nil { + t.Fatal("garbage must be ignored") + } +} + +func TestToolProgressThrottle(t *testing.T) { + th := newToolProgressThrottle() + now := time.Unix(0, 0) + th.now = func() time.Time { return now } + if !th.allow("a") || th.allow("a") { + t.Fatal("second immediate update must be throttled") + } + if !th.allow("b") { + t.Fatal("other calls are independent") + } + now = now.Add(toolProgressInterval) + if !th.allow("a") { + t.Fatal("allowed after interval") + } +} diff --git a/internal/rpc/worker.go b/internal/rpc/worker.go index 08f8a8d5..e7ec3bb4 100644 --- a/internal/rpc/worker.go +++ b/internal/rpc/worker.go @@ -38,6 +38,7 @@ type piRPCWorker struct { lastStreamActivity atomic.Int64 // unix nanos; stream/turn events keep worker visually running streamSink StreamEventSink streamPreview *streamPreviewAccumulator + toolThrottle *toolProgressThrottle } func (w *piRPCWorker) touch() { @@ -471,6 +472,9 @@ func (w *piRPCWorker) handleRPCLine(line string) { w.emitStreamPreview(msg.AssistantMessageEvent) } w.noteStreamActivity() + case "tool_execution_update": + w.noteStreamActivity() + w.emitToolProgress(line) case "message_end", "turn_end": w.noteStreamActivity() w.completeStreamPreview() @@ -502,6 +506,26 @@ func (w *piRPCWorker) emitStreamPreview(event assistantMessageEvent) { } } +func (w *piRPCWorker) emitToolProgress(line string) { + if w.streamSink == nil { + return + } + tp := parseToolProgress(line) + if tp == nil { + return + } + w.mu.Lock() + if w.toolThrottle == nil { + w.toolThrottle = newToolProgressThrottle() + } + th := w.toolThrottle + w.mu.Unlock() + if !th.allow(tp.ToolCallID) { + return + } + w.streamSink(StreamPreview{Tool: tp}) +} + func (w *piRPCWorker) completeStreamPreview() { if w.streamSink == nil || w.streamPreview == nil { return diff --git a/internal/server/chat_queue_drainer_test.go b/internal/server/chat_queue_drainer_test.go index f1b36c34..4cbcf28a 100644 --- a/internal/server/chat_queue_drainer_test.go +++ b/internal/server/chat_queue_drainer_test.go @@ -78,8 +78,8 @@ func TestDrainerSkipsWhenPaused(t *testing.T) { func TestDrainerSkipsWhenWorkerBusy(t *testing.T) { fake := &fakeSender{ - status: workers.WorkerStatus{State: workers.WorkerStateRunning}, - sendCh: make(chan struct{}, 1), + status: workers.WorkerStatus{State: workers.WorkerStateRunning}, + sendCh: make(chan struct{}, 1), } s, d, id := newDrainerServer(t, fake) s.chatQueue.Add(id, "wait your turn", "wait your turn") diff --git a/internal/server/chat_queue_test.go b/internal/server/chat_queue_test.go index 2ed825ae..8460af51 100644 --- a/internal/server/chat_queue_test.go +++ b/internal/server/chat_queue_test.go @@ -195,4 +195,3 @@ func TestChatQueueRejectsMissingPositionOnDelete(t *testing.T) { t.Fatalf("want 400, got %d", w.Code) } } - diff --git a/internal/server/gzip.go b/internal/server/gzip.go new file mode 100644 index 00000000..314b0709 --- /dev/null +++ b/internal/server/gzip.go @@ -0,0 +1,128 @@ +package server + +import ( + "compress/gzip" + "io" + "net/http" + "strings" + "sync" +) + +// gzipWriter wraps an http.ResponseWriter, gzipping the body when the client +// sent Accept-Encoding: gzip. Streaming responses (SSE) bypass it: they must +// flush progressively and must not be buffered behind a gzip writer. +type gzipWriter struct { + http.ResponseWriter + gz *gzip.Writer + passthrough bool + headerSent bool +} + +// WriteHeader is overridden so responses whose handler sets the status +// explicitly (auth 401 page) still get their headers before the flush. +func (g *gzipWriter) WriteHeader(code int) { + g.headerSent = true + ct := g.Header().Get("Content-Type") + if code < 400 && g.gz == nil && !g.passthrough && compressible(ct) && + !strings.HasPrefix(ct, "text/event-stream") { + g.Header().Set("Content-Encoding", "gzip") + g.Header().Del("Content-Length") + g.Header().Add("Vary", "Accept-Encoding") + g.gz = gzipWriterPool.Get().(*gzip.Writer) + g.gz.Reset(g.ResponseWriter) + } else { + g.passthrough = true + } + g.ResponseWriter.WriteHeader(code) +} + +func (g *gzipWriter) Write(b []byte) (int, error) { + if g.headerSent { + if g.passthrough { + return g.ResponseWriter.Write(b) + } + return g.gz.Write(b) + } + if g.gz == nil && !g.passthrough { + ct := g.Header().Get("Content-Type") + if compressible(ct) && ct != "text/plain; charset=utf-8" && !strings.HasPrefix(ct, "text/event-stream") { + g.Header().Set("Content-Encoding", "gzip") + g.Header().Del("Content-Length") + g.Header().Add("Vary", "Accept-Encoding") + g.gz = gzipWriterPool.Get().(*gzip.Writer) + g.gz.Reset(g.ResponseWriter) + } else { + g.passthrough = true + } + } + if g.passthrough { + return g.ResponseWriter.Write(b) + } + return g.gz.Write(b) +} + +// compressible reports whether a content type benefits from gzip. +func compressible(ct string) bool { + ct = strings.ToLower(ct) + for _, p := range []string{"text/", "application/json", "application/javascript", "application/xml", "image/svg"} { + if strings.HasPrefix(ct, p) { + return true + } + } + return false +} + +// Flush passes through so handlers that stream after the header is set keep +// working; the gzip buffer is flushed too. +func (g *gzipWriter) Flush() { + if g.gz != nil { + _ = g.gz.Flush() + } + if f, ok := g.ResponseWriter.(http.Flusher); ok { + f.Flush() + } +} + +// Close flushes and releases the gzip writer when one was created. +func (g *gzipWriter) Close() { + if g.gz != nil { + _ = g.gz.Close() + gzipWriterPool.Put(g.gz) + g.gz = nil + } +} + +var gzipWriterPool = sync.Pool{New: func() any { return gzip.NewWriter(io.Discard) }} + +// acceptsGzip reports whether the request can receive a gzip-encoded body. +func acceptsGzip(r *http.Request) bool { + for _, v := range r.Header.Values("Accept-Encoding") { + if strings.Contains(strings.ToLower(v), "gzip") { + return true + } + } + return false +} + +// gzipHandler wraps h with transparent gzip compression for compressible +// responses. SSE endpoints must be mounted outside of it (streaming). +func gzipHandler(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // /static/ assets are pre-compressed by frontend.ServeJS — compressing + // again yields gzip-inside-gzip ("Invalid or unexpected token"). + if !acceptsGzip(r) || strings.HasPrefix(r.URL.Path, "/static/") { + next.ServeHTTP(w, r) + return + } + gw := &gzipWriter{ResponseWriter: w} + defer gw.Close() + next.ServeHTTP(gw, r) + }) +} + +// GzipMiddleware is the public entry: wraps mux with gzip for compressible +// content types. Streaming endpoints (text/event-stream) and pre-compressed +// assets pass through untouched so progressive flush keeps working. +func GzipMiddleware(next http.Handler) http.Handler { + return gzipHandler(next) +} diff --git a/internal/server/gzip_test.go b/internal/server/gzip_test.go new file mode 100644 index 00000000..d76d123a --- /dev/null +++ b/internal/server/gzip_test.go @@ -0,0 +1,62 @@ +package server + +import ( + "compress/gzip" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestGzipHandler_CompressesJSON(t *testing.T) { + body := strings.Repeat(`{"a":1}`, 1000) + h := gzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + })) + req := httptest.NewRequest("GET", "/", nil) + req.Header.Set("Accept-Encoding", "gzip") + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if got := rec.Header().Get("Content-Encoding"); got != "gzip" { + t.Fatalf("Content-Encoding = %q, want gzip", got) + } + zr, err := gzip.NewReader(rec.Body) + if err != nil { + t.Fatalf("gzip reader: %v", err) + } + out, _ := io.ReadAll(zr) + if string(out) != body { + t.Fatalf("round-trip mismatch: got %d bytes, want %d", len(out), len(body)) + } +} + +func TestGzipHandler_SSEPassesThrough(t *testing.T) { + h := gzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = w.Write([]byte("data: hello\n\n")) + })) + req := httptest.NewRequest("GET", "/", nil) + req.Header.Set("Accept-Encoding", "gzip") + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if got := rec.Header().Get("Content-Encoding"); got == "gzip" { + t.Fatal("SSE must not be gzipped (streaming)") + } +} + +func TestGzipHandler_NoAcceptEncoding(t *testing.T) { + body := "plain" + h := gzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(body)) + })) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil)) + if got := rec.Header().Get("Content-Encoding"); got != "" { + t.Fatalf("Content-Encoding = %q, want empty", got) + } + if rec.Body.String() != body { + t.Fatal("body altered without gzip") + } +} diff --git a/internal/server/handlers.go b/internal/server/handlers.go index 1bd7ed16..8b2353cb 100644 --- a/internal/server/handlers.go +++ b/internal/server/handlers.go @@ -105,6 +105,7 @@ func (s *Server) handleApiForkSession(w http.ResponseWriter, r *http.Request) { } } + s.claimForCaller(r, id, "") writeJSON(w, 0, map[string]any{"ok": true, "id": id}) } @@ -154,11 +155,12 @@ func (s *Server) handleApiCloneSession(w http.ResponseWriter, r *http.Request) { } } + s.claimForCaller(r, id, "") writeJSON(w, 0, map[string]any{"ok": true, "id": id}) } func (s *Server) handleApiSessions(w http.ResponseWriter, r *http.Request) { - summaries, err := s.loadSummaries() + summaries, err := s.scopedSummaries(r) if err != nil { writeJSONError(w, http.StatusInternalServerError, err.Error()) return @@ -189,7 +191,7 @@ func (s *Server) handleApiSessions(w http.ResponseWriter, r *http.Request) { total := len(summaries) summaries = paginateSummaries(summaries, q.Get("offset"), q.Get("limit")) - writeJSON(w, 0, map[string]any{"sessions": summaries, "total": total}) + writeJSONConditional(w, r, map[string]any{"sessions": summaries, "total": total}) } // filterSummariesByQuery keeps summaries whose name, project, model, or UUID @@ -268,23 +270,14 @@ func (s *Server) handleApiSession(w http.ResponseWriter, r *http.Request) { entries, total, from = paginatedEntries(resolved.Session.Entries) } - writeJSON(w, 0, sessionResponseMap(resolved.Session, entries, total, from)) + writeJSONConditional(w, r, sessionResponseMap(resolved.Session, entries, total, from)) } // paginatedEntries returns the tail window embedded on the initial session load // for huge sessions (mirrors the ?paginate=1 API path). `total` is always the // full count; `from` is the index the returned window starts at. func paginatedEntries(entries []map[string]any) (out []map[string]any, total, from int) { - total = len(entries) - out = entries - if total > ui.LargeSessionThreshold { - from = total - ui.LargeSessionTailEntries - if from < 0 { - from = 0 - } - out = entries[from:] - } - return out, total, from + return ui.WindowEntries(entries) } // sessionResponseMap is the JSON shape the SPA consumes for a session, shared by @@ -368,6 +361,7 @@ func (s *Server) handleNewSession(w http.ResponseWriter, r *http.Request) { } } + s.claimForCaller(r, id, "") writeJSON(w, 0, map[string]any{"ok": true, "id": id}) } diff --git a/internal/server/owners.go b/internal/server/owners.go new file mode 100644 index 00000000..9aa72a3d --- /dev/null +++ b/internal/server/owners.go @@ -0,0 +1,286 @@ +package server + +// Multi-user hub support: every session has an owner (a tailnet login). The +// left sidebar shows only the caller's own sessions by default; a people +// switcher (cookie pi_view_owner) lets a person browse and open colleagues' +// sessions to work on them together. Disabled unless Deps.MultiUser is set, so +// single-user installs behave exactly as before. + +import ( + "net/http" + "net/url" + "sort" + "strings" + "time" + + "pi-web/internal/identity" + "pi-web/internal/sessions" +) + +const sessionOwnersSchema = `CREATE TABLE IF NOT EXISTS session_owners ( + session_id TEXT PRIMARY KEY, + owner TEXT NOT NULL, + source TEXT NOT NULL DEFAULT '', + created_at DATETIME +)` + +const ( + viewOwnerCookie = "pi_view_owner" + viewMine = "me" + viewAll = "all" + viewUnassigned = "_unassigned" + // archivedPrefix marks owners of people who left (e.g. "ex-daniel"). Their + // sessions stay stored (LoRA corpus) but are hidden from every default and + // "all" view; they are only listed under Pessoas → Arquivados. + archivedPrefix = "ex-" +) + +func isArchivedOwner(owner string) bool { return strings.HasPrefix(owner, archivedPrefix) } + +// currentUser resolves the caller. With multi-user disabled it is anonymous. +func (s *Server) currentUser(r *http.Request) identity.User { + if !s.multiUser || s.identity == nil { + return identity.User{Via: "anonymous"} + } + return s.identity.Identify(r) +} + +// setSessionOwner records owner for a session id (filename). Existing rows are +// kept: the first person to create a session owns it. +func (s *Server) setSessionOwner(sessionID, owner, source string) { + if s.db == nil || sessionID == "" || owner == "" { + return + } + _, _ = s.db.Exec(`INSERT OR IGNORE INTO session_owners (session_id, owner, source, created_at) VALUES (?, ?, ?, ?)`, + sessionID, strings.ToLower(owner), source, s.now().UTC().Format(time.RFC3339)) +} + +// claimForCaller records the caller as owner of a newly created session. +func (s *Server) claimForCaller(r *http.Request, sessionID, source string) { + if !s.multiUser { + return + } + if u := s.currentUser(r); u.Known() { + s.setSessionOwner(sessionID, u.Login, source) + } +} + +func (s *Server) ownerRegistry() map[string]string { + out := map[string]string{} + if s.db == nil { + return out + } + rows, err := s.db.Query(`SELECT session_id, owner FROM session_owners`) + if err != nil { + return out + } + defer rows.Close() + for rows.Next() { + var id, owner string + if rows.Scan(&id, &owner) == nil { + out[id] = owner + } + } + return out +} + +// annotateOwners fills Owner from the registry (which wins over the header). +func (s *Server) annotateOwners(summaries []sessions.SessionSummary) { + reg := s.ownerRegistry() + for i := range summaries { + if o, ok := reg[summaries[i].ID]; ok { + summaries[i].Owner = o + } + summaries[i].Owner = strings.ToLower(summaries[i].Owner) + } +} + +// ownerMatches reports whether a session owned by owner belongs to login. +// Owners recorded as a bare short name ("vinicius") match the full login. +func ownerMatches(owner, login string) bool { + if owner == "" || login == "" { + return false + } + return owner == login || owner == identity.ShortName(login) || identity.ShortName(owner) == identity.ShortName(login) && !strings.Contains(owner, "@") +} + +// viewOwner returns the requested sidebar scope: query ?owner= wins, then the +// pi_view_owner cookie, then "me". +func viewOwner(r *http.Request) string { + if v := strings.TrimSpace(r.URL.Query().Get("owner")); v != "" { + return strings.ToLower(v) + } + if c, err := r.Cookie(viewOwnerCookie); err == nil { + if v, err := url.QueryUnescape(c.Value); err == nil && strings.TrimSpace(v) != "" { + return strings.ToLower(strings.TrimSpace(v)) + } + } + return viewMine +} + +// filterByOwner keeps the sessions visible in the given scope. +// Unknown callers (anonymous, tagged devices, failed whois) see nothing. +func filterByOwner(summaries []sessions.SessionSummary, scope string, me identity.User) []sessions.SessionSummary { + if !me.Known() { + return []sessions.SessionSummary{} + } + if scope == viewAll { + out := make([]sessions.SessionSummary, 0, len(summaries)) + for _, sum := range summaries { + if !isArchivedOwner(sum.Owner) { + out = append(out, sum) + } + } + return out + } + if scope == viewMine { + scope = me.Login + } + out := make([]sessions.SessionSummary, 0, len(summaries)) + for _, sum := range summaries { + switch { + case scope == viewUnassigned: + if sum.Owner == "" { + out = append(out, sum) + } + case ownerMatches(sum.Owner, scope): + out = append(out, sum) + } + } + return out +} + +// scopedSummaries loads summaries with owners annotated and, in multi-user +// mode, filtered to the caller's current view. +func (s *Server) scopedSummaries(r *http.Request) ([]sessions.SessionSummary, error) { + summaries, err := s.loadSummaries() + if err != nil || !s.multiUser { + return summaries, err + } + cp := make([]sessions.SessionSummary, len(summaries)) + copy(cp, summaries) + s.annotateOwners(cp) + return filterByOwner(cp, viewOwner(r), s.currentUser(r)), nil +} + +type personInfo struct { + Login string `json:"login"` + Short string `json:"short"` + Name string `json:"name,omitempty"` + Sessions int `json:"sessions"` + Me bool `json:"me"` + Archived bool `json:"archived,omitempty"` +} + +// handleApiPeople returns the caller, the current view and everyone who owns +// sessions on this hub. +func (s *Server) handleApiPeople(w http.ResponseWriter, r *http.Request) { + me := s.currentUser(r) + if !s.multiUser { + writeJSON(w, 0, map[string]any{"multiUser": false, "me": me, "view": viewAll, "people": []personInfo{}}) + return + } + if !me.Known() { + writeJSON(w, 0, map[string]any{"multiUser": true, "me": me, "view": viewMine, "people": []personInfo{}, "unassigned": 0, "total": 0}) + return + } + summaries, err := s.loadSummaries() + if err != nil { + writeJSONError(w, http.StatusInternalServerError, err.Error()) + return + } + cp := make([]sessions.SessionSummary, len(summaries)) + copy(cp, summaries) + s.annotateOwners(cp) + counts := map[string]int{} + unassigned, visibleTotal := 0, 0 + for _, sum := range s.filterBtwSummaries(cp) { + if !isArchivedOwner(sum.Owner) { + visibleTotal++ + } + if sum.Owner == "" { + unassigned++ + continue + } + key := sum.Owner + if me.Known() && ownerMatches(sum.Owner, me.Login) { + key = me.Login + } + counts[key]++ + } + if me.Known() { + if _, ok := counts[me.Login]; !ok { + counts[me.Login] = 0 + } + } + people := make([]personInfo, 0, len(counts)) + for login, n := range counts { + p := personInfo{Login: login, Short: identity.ShortName(login), Sessions: n, Archived: isArchivedOwner(login)} + if p.Archived { + p.Name = strings.TrimPrefix(p.Short, archivedPrefix) + " (arquivado)" + } + if me.Known() && login == me.Login { + p.Me = true + p.Name = me.Name + } + people = append(people, p) + } + sort.Slice(people, func(i, j int) bool { + if people[i].Me != people[j].Me { + return people[i].Me + } + return people[i].Short < people[j].Short + }) + writeJSON(w, 0, map[string]any{ + "multiUser": true, + "me": me, + "view": viewOwner(r), + "people": people, + "unassigned": unassigned, + "total": visibleTotal, + }) +} + +// handleApiSessionOwner returns (GET) or reassigns (POST) a session's owner. +func (s *Server) handleApiSessionOwner(w http.ResponseWriter, r *http.Request) { + id := r.URL.Query().Get("id") + if r.Method == http.MethodPost { + var body struct { + ID string `json:"id"` + Owner string `json:"owner"` + } + if !decodeJSONBody(w, r, &body) { + return + } + if body.ID == "" || body.Owner == "" { + writeJSONError(w, http.StatusBadRequest, "id and owner are required") + return + } + if s.db != nil { + _, _ = s.db.Exec(`INSERT INTO session_owners (session_id, owner, source, created_at) VALUES (?, ?, '', ?) + ON CONFLICT(session_id) DO UPDATE SET owner = excluded.owner`, + body.ID, strings.ToLower(strings.TrimSpace(body.Owner)), s.now().UTC().Format(time.RFC3339)) + } + writeJSON(w, 0, map[string]any{"ok": true}) + return + } + if id == "" { + writeJSONError(w, http.StatusBadRequest, "id is required") + return + } + owner, source := "", "" + if resolved, err := s.cache.Resolve(s.sessionsDir, id); err == nil { + owner, source = resolved.Session.Owner, resolved.Session.Source + } + if o, ok := s.ownerRegistry()[id]; ok { + owner = o + } + me := s.currentUser(r) + writeJSON(w, 0, map[string]any{ + "multiUser": s.multiUser, + "owner": strings.ToLower(owner), + "short": identity.ShortName(owner), + "source": source, + "mine": me.Known() && ownerMatches(strings.ToLower(owner), me.Login), + }) +} diff --git a/internal/server/owners_test.go b/internal/server/owners_test.go new file mode 100644 index 00000000..08282649 --- /dev/null +++ b/internal/server/owners_test.go @@ -0,0 +1,194 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "pi-web/internal/identity" +) + +func newMultiUserServer(t *testing.T) *Server { + t.Helper() + s := newTestServer(t) + s.multiUser = true + s.identity = &identity.Resolver{Whois: func(_ context.Context, ip string) (string, string, error) { + switch ip { + case "100.64.0.1": + return "ana@symetrix.com", "Ana", nil + case "100.64.0.2": + return "bruno@symetrix.com", "Bruno", nil + } + return "", "", nil + }} + return s +} + +func writeOwnedSession(t *testing.T, root, project, name, owner string) { + t.Helper() + dir := filepath.Join(root, project) + if err := os.MkdirAll(dir, 0755); err != nil { + t.Fatal(err) + } + ownerField := "" + if owner != "" { + ownerField = `,"owner":` + jsonString(owner) + `,"source":"claude-code"` + } + content := `{"type":"session","version":3,"id":"` + name + `","timestamp":"2026-05-06T00:00:00.000Z","cwd":"/tmp"` + ownerField + `}` + "\n" + + `{"type":"message","id":"aaaaaaaa","parentId":null,"timestamp":"2026-05-06T00:00:01.000Z","message":{"role":"user","content":"hello","timestamp":1778025601000}}` + "\n" + if err := os.WriteFile(filepath.Join(dir, name+".jsonl"), []byte(content), 0644); err != nil { + t.Fatal(err) + } +} + +func sessionsAs(t *testing.T, s *Server, ip, query string, cookie string) []string { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "/api/sessions"+query, nil) + req.RemoteAddr = ip + ":4000" + if cookie != "" { + req.AddCookie(&http.Cookie{Name: viewOwnerCookie, Value: cookie}) + } + w := httptest.NewRecorder() + s.handleApiSessions(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status %d: %s", w.Code, w.Body.String()) + } + var body struct { + Sessions []struct{ ID, Owner string } `json:"sessions"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + var ids []string + for _, x := range body.Sessions { + ids = append(ids, x.ID) + } + return ids +} + +func TestMultiUserSidebarShowsOnlyOwnSessionsByDefault(t *testing.T) { + s := newMultiUserServer(t) + writeOwnedSession(t, s.sessionsDir, "--p--", "a1", "ana@symetrix.com") + writeOwnedSession(t, s.sessionsDir, "--p--", "a2", "ana") // short-name owner from an import + writeOwnedSession(t, s.sessionsDir, "--p--", "b1", "bruno@symetrix.com") + writeOwnedSession(t, s.sessionsDir, "--p--", "u1", "") + + got := strings.Join(sessionsAs(t, s, "100.64.0.1", "", ""), ",") + if !strings.Contains(got, "a1") || !strings.Contains(got, "a2") || strings.Contains(got, "b1") || strings.Contains(got, "u1") { + t.Fatalf("ana default view = %s", got) + } + // Browse a colleague via the switcher cookie and via ?owner=. + if got := strings.Join(sessionsAs(t, s, "100.64.0.1", "", "bruno@symetrix.com"), ","); got != "b1.jsonl" { + t.Fatalf("cookie view of bruno = %s", got) + } + if got := sessionsAs(t, s, "100.64.0.1", "?owner=all", ""); len(got) != 4 { + t.Fatalf("all view = %v", got) + } + if got := strings.Join(sessionsAs(t, s, "100.64.0.2", "?owner=_unassigned", ""), ","); got != "u1.jsonl" { + t.Fatalf("unassigned view = %s", got) + } +} + +func TestMultiUserNewSessionIsClaimedAndRegistryWins(t *testing.T) { + s := newMultiUserServer(t) + writeOwnedSession(t, s.sessionsDir, "--p--", "x1", "ana@symetrix.com") + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.RemoteAddr = "100.64.0.2:1" + s.claimForCaller(req, "x1.jsonl", "") + if got := strings.Join(sessionsAs(t, s, "100.64.0.2", "", ""), ","); got != "x1.jsonl" { + t.Fatalf("registry owner should win over header, bruno sees %q", got) + } + // INSERT OR IGNORE: a second claim does not steal ownership. + req.RemoteAddr = "100.64.0.1:1" + s.claimForCaller(req, "x1.jsonl", "") + if got := sessionsAs(t, s, "100.64.0.1", "", ""); len(got) != 0 { + t.Fatalf("ana should not own x1 anymore, got %v", got) + } +} + +func TestPeopleAndSessionOwnerEndpoints(t *testing.T) { + s := newMultiUserServer(t) + writeOwnedSession(t, s.sessionsDir, "--p--", "a1", "ana@symetrix.com") + writeOwnedSession(t, s.sessionsDir, "--p--", "b1", "bruno@symetrix.com") + writeOwnedSession(t, s.sessionsDir, "--p--", "u1", "") + req := httptest.NewRequest(http.MethodGet, "/api/people", nil) + req.RemoteAddr = "100.64.0.1:1" + w := httptest.NewRecorder() + s.handleApiPeople(w, req) + var body struct { + Me identity.User `json:"me"` + People []personInfo `json:"people"` + Unassigned int `json:"unassigned"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body.Me.Short != "ana" || len(body.People) != 2 || !body.People[0].Me || body.People[1].Short != "bruno" || body.Unassigned != 1 { + t.Fatalf("people = %+v", body) + } + + req = httptest.NewRequest(http.MethodGet, "/api/session-owner?id=b1.jsonl", nil) + req.RemoteAddr = "100.64.0.1:1" + w = httptest.NewRecorder() + s.handleApiSessionOwner(w, req) + if !strings.Contains(w.Body.String(), `"short":"bruno"`) || !strings.Contains(w.Body.String(), `"mine":false`) || !strings.Contains(w.Body.String(), `"source":"claude-code"`) { + t.Fatalf("session-owner = %s", w.Body.String()) + } +} + +func TestSingleUserModeUnchanged(t *testing.T) { + s := newTestServer(t) + writeOwnedSession(t, s.sessionsDir, "--p--", "a1", "ana@symetrix.com") + writeOwnedSession(t, s.sessionsDir, "--p--", "b1", "bruno@symetrix.com") + if got := sessionsAs(t, s, "100.64.0.1", "", ""); len(got) != 2 { + t.Fatalf("single-user should list everything, got %v", got) + } +} + +func TestMultiUserUnknownCallerSeesNothing(t *testing.T) { + s := newMultiUserServer(t) + writeOwnedSession(t, s.sessionsDir, "--p--", "a1", "ana@symetrix.com") + writeOwnedSession(t, s.sessionsDir, "--p--", "u1", "") + // 100.64.0.9 resolves to no login (e.g. a tagged device); 10.0.0.5 is off-tailnet. + for _, ip := range []string{"100.64.0.9", "10.0.0.5", "127.0.0.1"} { + for _, q := range []string{"", "?owner=all", "?owner=_unassigned", "?owner=ana@symetrix.com"} { + if got := sessionsAs(t, s, ip, q, ""); len(got) != 0 { + t.Fatalf("unknown caller %s%s saw %v", ip, q, got) + } + } + } + // A spoofed identity header from a tailnet peer is ignored (whois wins). + req := httptest.NewRequest(http.MethodGet, "/api/sessions", nil) + req.RemoteAddr = "100.64.0.9:1" + req.Header.Set("Tailscale-User-Login", "ana@symetrix.com") + w := httptest.NewRecorder() + s.handleApiSessions(w, req) + if strings.Contains(w.Body.String(), "a1") { + t.Fatalf("spoofed header leaked sessions: %s", w.Body.String()) + } +} + +func TestArchivedOwnerHiddenExceptExplicitView(t *testing.T) { + s := newMultiUserServer(t) + writeOwnedSession(t, s.sessionsDir, "--p--", "a1", "ana@symetrix.com") + writeOwnedSession(t, s.sessionsDir, "--p--", "d1", "") + s.setSessionOwner("d1.jsonl", "ex-daniel", "claude-code") + if got := strings.Join(sessionsAs(t, s, "100.64.0.1", "?owner=all", ""), ","); got != "a1.jsonl" { + t.Fatalf("all view should hide archived, got %s", got) + } + if got := strings.Join(sessionsAs(t, s, "100.64.0.1", "?owner=ex-daniel", ""), ","); got != "d1.jsonl" { + t.Fatalf("explicit archived view = %s", got) + } + req := httptest.NewRequest(http.MethodGet, "/api/people", nil) + req.RemoteAddr = "100.64.0.1:1" + w := httptest.NewRecorder() + s.handleApiPeople(w, req) + if !strings.Contains(w.Body.String(), `"archived":true`) || !strings.Contains(w.Body.String(), "daniel (arquivado)") { + t.Fatalf("people = %s", w.Body.String()) + } +} diff --git a/internal/server/projects.go b/internal/server/projects.go index 3699d620..78202e6f 100644 --- a/internal/server/projects.go +++ b/internal/server/projects.go @@ -162,7 +162,7 @@ func (s *Server) handleApiProjects(w http.ResponseWriter, r *http.Request) { writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed") return } - summaries, err := s.loadSummaries() + summaries, err := s.scopedSummaries(r) if err != nil { writeJSONError(w, http.StatusInternalServerError, err.Error()) return diff --git a/internal/server/ratings.go b/internal/server/ratings.go new file mode 100644 index 00000000..abdeead4 --- /dev/null +++ b/internal/server/ratings.go @@ -0,0 +1,76 @@ +package server + +// Per-message 👍/👎 ratings from the message footer. Stored in pi-web's sqlite +// (not appended to the session JSONL, which would fork pi's entry tree while a +// worker is writing). Exported alongside sessions for LoRA curation. + +import ( + "net/http" + "time" +) + +const messageRatingsSchema = `CREATE TABLE IF NOT EXISTS message_ratings ( + session_id TEXT NOT NULL, + entry_id TEXT NOT NULL, + rating INTEGER NOT NULL, + rated_by TEXT NOT NULL DEFAULT '', + updated_at DATETIME, + PRIMARY KEY (session_id, entry_id) +)` + +func (s *Server) handleMessageRating(w http.ResponseWriter, r *http.Request) { + sessionID := r.URL.Query().Get("id") + if sessionID == "" { + writeJSONError(w, http.StatusBadRequest, "id is required") + return + } + if s.db == nil { + writeJSONError(w, http.StatusServiceUnavailable, "database unavailable") + return + } + switch r.Method { + case http.MethodGet: + rows, err := s.db.Query(`SELECT entry_id, rating FROM message_ratings WHERE session_id = ?`, sessionID) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, err.Error()) + return + } + defer rows.Close() + out := map[string]int{} + for rows.Next() { + var id string + var v int + if rows.Scan(&id, &v) == nil { + out[id] = v + } + } + writeJSON(w, 0, map[string]any{"ratings": out}) + case http.MethodPost: + var body struct { + EntryID string `json:"entryId"` + Rating int `json:"rating"` + } + if !decodeJSONBody(w, r, &body) { + return + } + if body.EntryID == "" || body.Rating < -1 || body.Rating > 1 { + writeJSONError(w, http.StatusBadRequest, "entryId and rating (-1, 0, 1) are required") + return + } + var err error + if body.Rating == 0 { + _, err = s.db.Exec(`DELETE FROM message_ratings WHERE session_id = ? AND entry_id = ?`, sessionID, body.EntryID) + } else { + _, err = s.db.Exec(`INSERT INTO message_ratings (session_id, entry_id, rating, rated_by, updated_at) VALUES (?, ?, ?, ?, ?) + ON CONFLICT(session_id, entry_id) DO UPDATE SET rating = excluded.rating, rated_by = excluded.rated_by, updated_at = excluded.updated_at`, + sessionID, body.EntryID, body.Rating, s.currentUser(r).Login, s.now().UTC().Format(time.RFC3339)) + } + if err != nil { + writeJSONError(w, http.StatusInternalServerError, err.Error()) + return + } + writeJSON(w, 0, map[string]any{"ok": true}) + default: + writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed") + } +} diff --git a/internal/server/ratings_test.go b/internal/server/ratings_test.go new file mode 100644 index 00000000..f6a9d5a5 --- /dev/null +++ b/internal/server/ratings_test.go @@ -0,0 +1,40 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestMessageRatingRoundTrip(t *testing.T) { + s := newTestServer(t) + post := func(body string) int { + req := httptest.NewRequest(http.MethodPost, "/api/message-rating?id=s1.jsonl", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + s.handleMessageRating(w, req) + return w.Code + } + get := func() string { + w := httptest.NewRecorder() + s.handleMessageRating(w, httptest.NewRequest(http.MethodGet, "/api/message-rating?id=s1.jsonl", nil)) + return w.Body.String() + } + if c := post(`{"entryId":"e1","rating":1}`); c != 200 { + t.Fatalf("post %d", c) + } + if c := post(`{"entryId":"e2","rating":-1}`); c != 200 { + t.Fatalf("post %d", c) + } + if got := get(); !strings.Contains(got, `"e1":1`) || !strings.Contains(got, `"e2":-1`) { + t.Fatalf("ratings = %s", got) + } + post(`{"entryId":"e1","rating":0}`) + if got := get(); strings.Contains(got, `"e1"`) { + t.Fatalf("rating not cleared: %s", got) + } + if c := post(`{"entryId":"e1","rating":5}`); c != 400 { + t.Fatalf("invalid rating accepted: %d", c) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 4b8bfa28..590fbcac 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -13,6 +13,7 @@ import ( "net/http" "os" "path/filepath" + "pi-web/internal/identity" "sync" "time" @@ -59,6 +60,11 @@ type Deps struct { // DisableBackgroundJobs keeps the development server from duplicating the // installed server's scheduler, queue drainer, auto-titles, and pushes. DisableBackgroundJobs bool + // MultiUser enables per-person session ownership (sidebar shows only the + // caller's sessions; a people switcher opens colleagues'). Identity + // resolves the caller; when nil a tailscale-whois resolver is used. + MultiUser bool + Identity *identity.Resolver } // Server holds runtime state — connected SSE clients and last-seen modtimes @@ -97,6 +103,9 @@ type Server struct { runRestart func() error updateMu sync.Mutex // serializes install/restart operations disableBackgroundJobs bool + multiUser bool + identity *identity.Resolver + whisperBase string // test override for PI_WEB_WHISPER_URL // fileWalk caches bounded directory listings per cwd for the @mention // autocomplete so rapid keystrokes reuse a single filesystem walk. @@ -172,6 +181,8 @@ func New(deps Deps) (*Server, error) { runInstall: deps.RunInstall, runRestart: deps.RunRestart, disableBackgroundJobs: deps.DisableBackgroundJobs, + multiUser: deps.MultiUser, + identity: deps.Identity, metrics: metricsState{ startedAt: now(), cpuLast: make(map[int]cpuMark), @@ -268,6 +279,8 @@ func initDB(agentDir string) (*sql.DB, error) { {"chat_queue_items table", chatqueue.ItemsTableDDL}, {"chat_queue_items index", chatqueue.ItemsSessionIndexDDL}, {"chat_queue_state table", chatqueue.StateTableDDL}, + {"session_owners table", sessionOwnersSchema}, + {"message_ratings table", messageRatingsSchema}, } for _, s := range schema { if _, err := db.Exec(s.stmt); err != nil { @@ -343,6 +356,10 @@ func (s *Server) Register(mux *http.ServeMux) { mux.HandleFunc("/share", s.auth.Wrap(s.handleShare)) mux.HandleFunc("/events", s.auth.Wrap(s.handleEvents)) mux.HandleFunc("/api/new-session", s.auth.Wrap(s.handleNewSession)) + mux.HandleFunc("/api/people", s.auth.Wrap(s.handleApiPeople)) + mux.HandleFunc("/api/message-rating", s.auth.Wrap(s.handleMessageRating)) + mux.HandleFunc("/api/transcribe", s.auth.Wrap(s.handleTranscribe)) + mux.HandleFunc("/api/session-owner", s.auth.Wrap(s.handleApiSessionOwner)) mux.HandleFunc("/api/fork-session", s.auth.Wrap(s.handleApiForkSession)) mux.HandleFunc("/api/clone-session", s.auth.Wrap(s.handleApiCloneSession)) mux.HandleFunc("/api/rename-session", s.auth.Wrap(s.handleRenameSession)) @@ -375,6 +392,7 @@ func (s *Server) Register(mux *http.ServeMux) { s.push.Register(mux, s.auth.Wrap) } mux.HandleFunc("/api/sounds", s.auth.Wrap(s.handleApiSounds)) + mux.HandleFunc("/api/suggested-path", s.auth.Wrap(s.handleApiSuggestedPath)) mux.HandleFunc("/sounds/", s.handleSounds) if s.updater != nil { mux.HandleFunc("/api/version", s.auth.Wrap(s.handleVersion)) @@ -456,6 +474,12 @@ func (s *Server) BroadcastChatPreview(sessionID string, preview rpc.StreamPrevie if sessionID == "" || sessionID == globalSessID { return } + if preview.Tool != nil { + if msg, err := formatSSEJSONEvent("tool-progress", preview.Tool); err == nil { + s.broadcast(sessionID, msg) + } + return + } msg, err := formatSSEJSONEvent("chat-preview", preview) if err != nil { return @@ -499,3 +523,9 @@ func writeJSONError(w http.ResponseWriter, status int, message string) { func writeJSON(w http.ResponseWriter, status int, payload any) { render.WriteJSON(w, status, payload) } + +// writeJSONConditional writes payload as JSON with ETag/304 revalidation so +// unchanged GET payloads cost a header round trip instead of a full transfer. +func writeJSONConditional(w http.ResponseWriter, r *http.Request, payload any) { + render.WriteJSONConditional(w, r, payload) +} diff --git a/internal/server/server_etag_test.go b/internal/server/server_etag_test.go new file mode 100644 index 00000000..369b182a --- /dev/null +++ b/internal/server/server_etag_test.go @@ -0,0 +1,66 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "pi-web/internal/sessions" +) + +func TestApiSessions_ETagRevalidation(t *testing.T) { + sessionsDir := t.TempDir() + writeSessionWithCWD(t, filepath.Join(sessionsDir, "sub1"), "session-a.jsonl", "/home/user/project-a") + s := &Server{sessionsDir: sessionsDir, cache: sessions.NewCache()} + + req := httptest.NewRequest(http.MethodGet, "/api/sessions", nil) + w := httptest.NewRecorder() + s.handleApiSessions(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status = %d", w.Code) + } + etag := w.Header().Get("ETag") + if etag == "" { + t.Fatal("missing ETag on /api/sessions") + } + + req2 := httptest.NewRequest(http.MethodGet, "/api/sessions", nil) + req2.Header.Set("If-None-Match", etag) + w2 := httptest.NewRecorder() + s.handleApiSessions(w2, req2) + if w2.Code != http.StatusNotModified { + t.Fatalf("expected 304, got %d", w2.Code) + } + if w2.Body.Len() != 0 { + t.Fatalf("304 must have empty body, got %q", w2.Body.String()) + } +} + +func TestApiSession_ETagRevalidation(t *testing.T) { + root := t.TempDir() + writeSessionWithNMessages(t, root, "proj", "s.jsonl", 5) + s := &Server{sessionsDir: root, cache: sessions.NewCache()} + + req := httptest.NewRequest(http.MethodGet, "/api/session?id=s.jsonl", nil) + w := httptest.NewRecorder() + s.handleApiSession(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status = %d", w.Code) + } + etag := w.Header().Get("ETag") + if etag == "" { + t.Fatal("missing ETag on /api/session") + } + + req2 := httptest.NewRequest(http.MethodGet, "/api/session?id=s.jsonl", nil) + req2.Header.Set("If-None-Match", etag) + w2 := httptest.NewRecorder() + s.handleApiSession(w2, req2) + if w2.Code != http.StatusNotModified { + t.Fatalf("expected 304, got %d", w2.Code) + } + if w2.Body.Len() != 0 { + t.Fatalf("304 must have empty body, got %q", w2.Body.String()) + } +} diff --git a/internal/server/settings.go b/internal/server/settings.go index 1c576119..cdea046d 100644 --- a/internal/server/settings.go +++ b/internal/server/settings.go @@ -1,9 +1,12 @@ package server import ( + "bytes" "fmt" "net/http" + "os" + "pi-web/internal/render" "strconv" "strings" "time" @@ -22,16 +25,26 @@ func (s *Server) handleAppShell(w http.ResponseWriter, r *http.Request, bootstra http.NotFound(w, r) return } - w.Header().Set("Content-Type", "text/html; charset=utf-8") - // The shell references content-hashed asset paths, so it must never be - // cached: a stale shell would point at old (now-404) chunks and pin the - // browser to an outdated bundle after a rebuild. - w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") - if err := s.renderAppShell(w, bootstrap); err != nil { + // Render to a buffer so the response can be hashed. no-cache (not + // no-store) keeps the browser holding a copy that must be revalidated on + // every use: an unchanged shell costs a 304, and a rebuilt one still + // updates because its ETag changes - the stale shell is never served. + var buf bytes.Buffer + if err := s.renderAppShell(&buf, bootstrap); err != nil { if !isBrokenPipe(err) { fmt.Fprintf(os.Stderr, "app shell template error: %v\n", err) } + return + } + etag := render.ETagOf(buf.Bytes()) + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("ETag", etag) + if render.MatchesETag(r.Header.Get("If-None-Match"), etag) { + w.WriteHeader(http.StatusNotModified) + return } + _, _ = w.Write(buf.Bytes()) } // settingDefaults defines the server-backed user settings and their default @@ -42,6 +55,9 @@ func (s *Server) handleAppShell(w http.ResponseWriter, r *http.Request, bootstra // listed here — it stays in localStorage only. var settingDefaults = map[string]string{ "pi-web-theme": "dark", + "pi-web:v1:zcode-preset": "", + "pi-web:v1:zcode-act": "", + "pi-web:v1:ui-scale": "100", "pi-web:v1:locale": "en", "pi-web:v1:custom-languages": "", "pi-web:v1:font-ui": "mono", @@ -121,6 +137,24 @@ func (s *Server) ThemeSetting() string { return s.getSetting("pi-web-theme", "dark") } +// ZcodePresetSetting returns the persisted zcode colour preset (empty = none), +// injected server-side as so every device paints the +// chosen preset on first load. +func (s *Server) ZcodePresetSetting() string { + return s.getSetting("pi-web:v1:zcode-preset", "") +} + +// UIScaleSetting returns the persisted whole-UI scale in percent (80–150). +func (s *Server) UIScaleSetting() string { + return s.getSetting("pi-web:v1:ui-scale", "100") +} + +// ZcodeActSetting returns the persisted action-colour scheme ("" = follow the +// preset), injected as . +func (s *Server) ZcodeActSetting() string { + return s.getSetting("pi-web:v1:zcode-act", "") +} + // fontKeywords maps a curated font name to a full CSS font-family stack. The // stored font value is either one of these keywords or a raw family name the // user typed / picked from their installed fonts. Kept in sync with diff --git a/internal/server/share_test.go b/internal/server/share_test.go index 2a34cdfc..e919c343 100644 --- a/internal/server/share_test.go +++ b/internal/server/share_test.go @@ -30,9 +30,9 @@ func newShareTestServer(t *testing.T, runner shareCmdRunner) (*Server, string) { root := t.TempDir() writeSessionFile(t, root, "--tmp--project--", "session.jsonl") s := &Server{ - sessionsDir: root, - cache: sessions.NewCache(), - shareRunner: runner, + sessionsDir: root, + cache: sessions.NewCache(), + shareRunner: runner, renderExportSession: func(sess sessions.Session, theme string) string { return "" }, } return s, root diff --git a/internal/server/suggested_path.go b/internal/server/suggested_path.go new file mode 100644 index 00000000..4e9e7a64 --- /dev/null +++ b/internal/server/suggested_path.go @@ -0,0 +1,55 @@ +package server + +import ( + "net/http" + "os" + "path/filepath" + "strings" + + "pi-web/internal/identity" +) + +// sharedRoot is the prefix every per-user folder lives under. +const sharedRoot = "/home/symetrix/shared" + +// handleApiSuggestedPath returns the caller's own shared folder, so the +// new-session modal can pre-fill it. With multi-user off it returns "" and the +// frontend keeps its normal behaviour. The folder must exist on disk; we do +// not create it — ops owns the shared tree. +func (s *Server) handleApiSuggestedPath(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed") + return + } + me := s.currentUser(r) + if !me.Known() { + writeJSON(w, 0, map[string]any{"path": ""}) + return + } + name := identity.ShortName(me.Login) + if name == "" { + writeJSON(w, 0, map[string]any{"path": ""}) + return + } + for _, p := range []string{ + filepath.Join(sharedRoot, name), + filepath.Join("/home", name), + } { + if fi, err := os.Stat(p); err == nil && fi.IsDir() { + writeJSON(w, 0, map[string]any{"path": p}) + return + } + } + writeJSON(w, 0, map[string]any{"path": ""}) +} + +// suggestedPathEnabled is true only in multi-user mode with an identity +// resolver; single-user installs keep the modal as-is. +func (s *Server) suggestedPathEnabled() bool { + return s.multiUser && s.identity != nil +} + +// isUserSharedPath reports whether p is under the shared root. +func isUserSharedPath(p string) bool { + return strings.HasPrefix(filepath.Clean(p), sharedRoot+"/") +} diff --git a/internal/server/transcribe.go b/internal/server/transcribe.go new file mode 100644 index 00000000..e02fb718 --- /dev/null +++ b/internal/server/transcribe.go @@ -0,0 +1,87 @@ +package server + +// Voice input: the composer mic records audio in the browser and posts it here; +// pi-web forwards it to a local OpenAI-compatible Whisper server +// (PI_WEB_WHISPER_URL, e.g. http://127.0.0.1:8786) so audio never leaves the +// host. GET reports availability so the UI can fall back to Web Speech. + +import ( + "bytes" + "context" + "io" + "mime/multipart" + "net/http" + "net/textproto" + "os" + "strings" + "time" +) + +const maxAudioBytes = 25 << 20 + +func (s *Server) whisperURL() string { + if s.whisperBase != "" { + return strings.TrimRight(s.whisperBase, "/") + } + return strings.TrimRight(os.Getenv("PI_WEB_WHISPER_URL"), "/") +} + +func (s *Server) handleTranscribe(w http.ResponseWriter, r *http.Request) { + base := s.whisperURL() + client := &http.Client{Timeout: 120 * time.Second} + switch r.Method { + case http.MethodGet: + ok := false + if base != "" { + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, base+"/health", nil) + if resp, err := client.Do(req); err == nil { + ok = resp.StatusCode == http.StatusOK + resp.Body.Close() + } + } + writeJSON(w, 0, map[string]any{"available": ok}) + case http.MethodPost: + if base == "" { + writeJSONError(w, http.StatusServiceUnavailable, "transcription server not configured") + return + } + audio, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxAudioBytes)) + if err != nil || len(audio) == 0 { + writeJSONError(w, http.StatusBadRequest, "audio body required (max 25MB)") + return + } + lang := r.URL.Query().Get("language") + if lang == "" { + lang = "auto" + } + ctype := r.Header.Get("Content-Type") + if ctype == "" { + ctype = "application/octet-stream" + } + var buf bytes.Buffer + mw := multipart.NewWriter(&buf) + h := make(textproto.MIMEHeader) + h.Set("Content-Disposition", `form-data; name="file"; filename="audio"`) + h.Set("Content-Type", ctype) + part, _ := mw.CreatePart(h) + _, _ = part.Write(audio) + _ = mw.WriteField("language", lang) + _ = mw.WriteField("model", "whisper-1") + _ = mw.Close() + req, _ := http.NewRequestWithContext(r.Context(), http.MethodPost, base+"/v1/audio/transcriptions", &buf) + req.Header.Set("Content-Type", mw.FormDataContentType()) + resp, err := client.Do(req) + if err != nil { + writeJSONError(w, http.StatusBadGateway, "transcription server unavailable") + return + } + defer resp.Body.Close() + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(resp.StatusCode) + _, _ = io.Copy(w, io.LimitReader(resp.Body, 1<<20)) + default: + writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed") + } +} diff --git a/internal/server/transcribe_test.go b/internal/server/transcribe_test.go new file mode 100644 index 00000000..e15b7e02 --- /dev/null +++ b/internal/server/transcribe_test.go @@ -0,0 +1,63 @@ +package server + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestTranscribeProxiesToWhisper(t *testing.T) { + var gotAudio, gotLang, gotType string + whisper := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/health" { + w.WriteHeader(200) + return + } + if err := r.ParseMultipartForm(1 << 20); err != nil { + t.Fatalf("multipart: %v", err) + } + f, fh, _ := r.FormFile("file") + b, _ := io.ReadAll(f) + gotAudio, gotLang, gotType = string(b), r.FormValue("language"), fh.Header.Get("Content-Type") + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"text":"olá mundo","language":"pt"}`)) + })) + defer whisper.Close() + s := newTestServer(t) + s.whisperBase = whisper.URL + + w := httptest.NewRecorder() + s.handleTranscribe(w, httptest.NewRequest(http.MethodGet, "/api/transcribe", nil)) + if !strings.Contains(w.Body.String(), `"available":true`) { + t.Fatalf("availability = %s", w.Body.String()) + } + + req := httptest.NewRequest(http.MethodPost, "/api/transcribe?language=pt", strings.NewReader("AUDIO")) + req.Header.Set("Content-Type", "audio/mp4") + w = httptest.NewRecorder() + s.handleTranscribe(w, req) + if w.Code != 200 || !strings.Contains(w.Body.String(), "olá mundo") { + t.Fatalf("transcribe = %d %s", w.Code, w.Body.String()) + } + if gotAudio != "AUDIO" || gotLang != "pt" || gotType != "audio/mp4" { + t.Fatalf("forwarded %q %q %q", gotAudio, gotLang, gotType) + } +} + +func TestTranscribeUnavailableWithoutServer(t *testing.T) { + s := newTestServer(t) + s.whisperBase = "" + t.Setenv("PI_WEB_WHISPER_URL", "") + w := httptest.NewRecorder() + s.handleTranscribe(w, httptest.NewRequest(http.MethodGet, "/api/transcribe", nil)) + if !strings.Contains(w.Body.String(), `"available":false`) { + t.Fatalf("got %s", w.Body.String()) + } + w = httptest.NewRecorder() + s.handleTranscribe(w, httptest.NewRequest(http.MethodPost, "/api/transcribe", strings.NewReader("x"))) + if w.Code != http.StatusServiceUnavailable { + t.Fatalf("code %d", w.Code) + } +} diff --git a/internal/sessions/cache.go b/internal/sessions/cache.go index 369ba025..c9e7d88a 100644 --- a/internal/sessions/cache.go +++ b/internal/sessions/cache.go @@ -27,6 +27,26 @@ type Cache struct { parses int // diagnostic: number of ParseSummary calls hits int // diagnostic: number of cache hits + + // Whole-scan result cache (see resultCacheTTL). + resDir string + resAt time.Time + resSummaries []SessionSummary + resErr error +} + +// resultCacheTTL bounds how long a full LoadAll scan is reused. Directory +// listings over NFS cost ~1 stat per project dir per call (800+ dirs here); +// without it every index poll re-walked them all (~0.8s server-side). New +// sessions appear within the TTL window, which is fine for a UI that polls. +const resultCacheTTL = 1500 * time.Millisecond + +// Invalidate drops the whole-scan result cache so the next LoadAll re-walks +// the tree (used by tests and by anything that writes sessions directly). +func (c *Cache) Invalidate() { + c.mu.Lock() + defer c.mu.Unlock() + c.resDir = "" } func NewCache() *Cache { @@ -42,6 +62,14 @@ func NewCache() *Cache { // that are new or modified are re-parsed; files that have disappeared are // evicted. It also maintains a path index for O(1) lookup by filename. func (c *Cache) LoadAll(dir string) ([]SessionSummary, error) { + c.mu.Lock() + if c.resDir == dir && time.Since(c.resAt) < resultCacheTTL { + out, err := c.resSummaries, c.resErr + c.mu.Unlock() + return out, err + } + c.mu.Unlock() + entries, err := os.ReadDir(dir) if err != nil { return nil, err @@ -172,6 +200,14 @@ func (c *Cache) LoadAll(dir string) ([]SessionSummary, error) { c.mu.Unlock() SortSummariesByActivity(summaries) + + c.mu.Lock() + c.resDir = dir + c.resAt = time.Now() + c.resSummaries = summaries + c.resErr = nil + c.mu.Unlock() + return summaries, nil } diff --git a/internal/sessions/cache_test.go b/internal/sessions/cache_test.go index b7a4e309..6a705e7b 100644 --- a/internal/sessions/cache_test.go +++ b/internal/sessions/cache_test.go @@ -8,6 +8,7 @@ import ( ) func TestSessionCacheReusesParsedSessions(t *testing.T) { + root := t.TempDir() writeSessionFile(t, root, "--tmp--project--", "session.jsonl") @@ -24,6 +25,7 @@ func TestSessionCacheReusesParsedSessions(t *testing.T) { t.Fatalf("after first call: parses=%d hits=%d, want 1/0", c.parses, c.hits) } + c.Invalidate() second, err := c.LoadAll(root) if err != nil { t.Fatalf("second loadAll: %v", err) @@ -40,6 +42,7 @@ func TestSessionCacheReusesParsedSessions(t *testing.T) { } func TestSessionCacheReparsesOnModTimeChange(t *testing.T) { + root := t.TempDir() path := writeSessionFile(t, root, "--tmp--project--", "session.jsonl") @@ -54,6 +57,7 @@ func TestSessionCacheReparsesOnModTimeChange(t *testing.T) { t.Fatalf("chtimes: %v", err) } + c.Invalidate() if _, err := c.LoadAll(root); err != nil { t.Fatalf("second loadAll: %v", err) } @@ -66,6 +70,7 @@ func TestSessionCacheReparsesOnModTimeChange(t *testing.T) { } func TestSessionCacheEvictsRemovedFiles(t *testing.T) { + root := t.TempDir() path := writeSessionFile(t, root, "--tmp--project--", "session.jsonl") @@ -81,6 +86,7 @@ func TestSessionCacheEvictsRemovedFiles(t *testing.T) { t.Fatalf("remove: %v", err) } + c.Invalidate() got, err := c.LoadAll(root) if err != nil { t.Fatalf("after remove: %v", err) @@ -94,6 +100,7 @@ func TestSessionCacheEvictsRemovedFiles(t *testing.T) { } func TestSessionCachePicksUpNewFiles(t *testing.T) { + root := t.TempDir() writeSessionFile(t, root, "--tmp--project--", "first.jsonl") @@ -104,6 +111,7 @@ func TestSessionCachePicksUpNewFiles(t *testing.T) { writeSessionFile(t, root, "--tmp--project--", "second.jsonl") + c.Invalidate() got, err := c.LoadAll(root) if err != nil { t.Fatalf("second loadAll: %v", err) diff --git a/internal/sessions/session.go b/internal/sessions/session.go index 935f0629..e45f5eec 100644 --- a/internal/sessions/session.go +++ b/internal/sessions/session.go @@ -32,6 +32,8 @@ type summaryLine struct { Provider string `json:"provider"` ModelID string `json:"modelId"` AutoTitle bool `json:"autoTitle"` + Owner string `json:"owner"` + Source string `json:"source"` Message *summaryMsg `json:"message"` } @@ -66,6 +68,12 @@ type SessionSummary struct { ModelProvider string ChatAvailable bool ChatDisabledReason string + // Owner is the tailnet login that owns the session (multi-user hub). It is + // read from the optional "owner" field of the session header and may be + // overridden by the server's owner registry. Empty means unassigned. + Owner string + // Source tags imported sessions (e.g. "claude-code", "opencode", "pi"). + Source string } type Session struct { @@ -237,6 +245,12 @@ func ParseSummary(path, dirName, fileName string) (SessionSummary, error) { if raw.ID != "" { s.SessionUUID = raw.ID } + if raw.Owner != "" { + s.Owner = raw.Owner + } + if raw.Source != "" { + s.Source = raw.Source + } case "session_info": if raw.Name != "" { sessionInfoName = raw.Name @@ -524,6 +538,12 @@ func ParseFile(path, dirName, fileName string) (Session, error) { if sid, _ := raw["id"].(string); sid != "" { s.SessionUUID = sid } + if o, _ := raw["owner"].(string); o != "" { + s.Owner = o + } + if src, _ := raw["source"].(string); src != "" { + s.Source = src + } case "session_info": if n, _ := raw["name"].(string); n != "" { sessionInfoName = n diff --git a/internal/ui/embedded/assets/apple-touch-icon.png b/internal/ui/embedded/assets/apple-touch-icon.png new file mode 100644 index 00000000..69bff7d1 Binary files /dev/null and b/internal/ui/embedded/assets/apple-touch-icon.png differ diff --git a/internal/ui/embedded/assets/icon-192.png b/internal/ui/embedded/assets/icon-192.png new file mode 100644 index 00000000..6a1bce30 Binary files /dev/null and b/internal/ui/embedded/assets/icon-192.png differ diff --git a/internal/ui/embedded/assets/icon-512.png b/internal/ui/embedded/assets/icon-512.png new file mode 100644 index 00000000..ad5802e3 Binary files /dev/null and b/internal/ui/embedded/assets/icon-512.png differ diff --git a/internal/ui/embedded/assets/icon-maskable-512.png b/internal/ui/embedded/assets/icon-maskable-512.png new file mode 100644 index 00000000..c1d4dbdd Binary files /dev/null and b/internal/ui/embedded/assets/icon-maskable-512.png differ diff --git a/internal/ui/embedded/assets/manifest.webmanifest b/internal/ui/embedded/assets/manifest.webmanifest index 14b032b3..cac9990d 100644 --- a/internal/ui/embedded/assets/manifest.webmanifest +++ b/internal/ui/embedded/assets/manifest.webmanifest @@ -1,14 +1,40 @@ { - "name": "Pi Sessions", - "short_name": "Pi", - "description": "Browse and chat with Pi/Claude Code sessions on your machine.", + "name": "pi", + "short_name": "pi", + "description": "pi — agente de código (sessões, chat, temas)", "start_url": "/", "scope": "/", "display": "standalone", - "display_override": ["window-controls-overlay", "standalone"], + "display_override": [ + "window-controls-overlay", + "standalone" + ], "background_color": "#0e0e13", "theme_color": "#0e0e13", "icons": [ + { + "src": "/icon-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "any" + }, + { + "src": "/icon-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "any" + }, + { + "src": "/icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "/apple-touch-icon.png", + "sizes": "180x180", + "type": "image/png" + }, { "src": "/icon.svg", "sizes": "any", @@ -21,5 +47,6 @@ "type": "image/svg+xml", "purpose": "maskable" } - ] + ], + "id": "/" } diff --git a/internal/ui/embedded/auth.html b/internal/ui/embedded/auth.html index 0dc28efd..f543d274 100644 --- a/internal/ui/embedded/auth.html +++ b/internal/ui/embedded/auth.html @@ -4,10 +4,16 @@ pi-web — Authentication Required + + + + + + {{.ThemeCss}} diff --git a/internal/ui/embedded/styles/index.css b/internal/ui/embedded/styles/index.css index 16a3b978..70681f29 100644 --- a/internal/ui/embedded/styles/index.css +++ b/internal/ui/embedded/styles/index.css @@ -22,7 +22,7 @@ body { line-height: var(--line-height); color: var(--text-soft); background: var(--body-bg); - min-height: 100vh; + min-height: var(--zc-vh, 100vh); overflow-x: hidden; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; @@ -842,7 +842,10 @@ body.modal-sheet-open { overflow: hidden; } right: calc(18px + env(safe-area-inset-right)); bottom: calc(18px + env(safe-area-inset-bottom)); } - .nav-search-btn { min-width: auto; } + .nav-search-btn { min-width: 0; flex: 0 1 auto; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } + .header-top { gap: 8px; min-width: 0; } + .header-top h1 { flex: 0 0 auto; } + .header-actions { min-width: 0; flex: 0 1 auto; } .nav-search-btn kbd { display: none; } .workspace-summary { align-items: flex-start; @@ -868,7 +871,7 @@ body.modal-sheet-open { overflow: hidden; } min-width: 0; max-width: 100vw; overflow-x: hidden; - /* Fill the fixed overlay instead of 100svh; iOS can report svh shorter and leave a top gap. */ + /* Fill the fixed overlay instead of var(--zc-svh, 100svh); iOS can report svh shorter and leave a top gap. */ height: 100%; max-height: none; display: flex; @@ -980,3 +983,7 @@ body.modal-sheet-open { overflow: hidden; } -webkit-backdrop-filter: none; } } + +/* No sideways page growth now that pinch-zoom is allowed (no maximum-scale): + an overflowing child must not widen the layout viewport on phones. */ +html, body { overflow-x: clip; } diff --git a/internal/ui/embedded/styles/menu.css b/internal/ui/embedded/styles/menu.css index f6ce3d4e..7cd64f6d 100644 --- a/internal/ui/embedded/styles/menu.css +++ b/internal/ui/embedded/styles/menu.css @@ -6,7 +6,7 @@ z-index: var(--pi-menu-z, 201); width: var(--pi-menu-width, 248px); max-width: calc(100vw - 32px); - max-height: calc(100vh - 72px); + max-height: calc(var(--zc-vh, 100vh) - 72px); overflow-y: auto; padding: 6px; background: color-mix(in srgb, var(--pi-menu-bg) 82%, transparent); @@ -156,8 +156,8 @@ opacity: 0; transition: opacity 0.25s cubic-bezier(0.4, 0, 0.2, 1); pointer-events: none; - height: 100vh; - height: 100svh; + height: var(--zc-vh, 100vh); + height: var(--zc-svh, 100svh); } .mobile-command-backdrop.open { diff --git a/internal/ui/embedded/styles/palette.css b/internal/ui/embedded/styles/palette.css index 75fde762..b23f330c 100644 --- a/internal/ui/embedded/styles/palette.css +++ b/internal/ui/embedded/styles/palette.css @@ -175,7 +175,7 @@ body.pi-palette-open { overflow: hidden; } } .command-palette { width: 100%; - /* Fill the fixed overlay instead of 100svh; iOS can report svh shorter and leave a top gap. */ + /* Fill the fixed overlay instead of var(--zc-svh, 100svh); iOS can report svh shorter and leave a top gap. */ height: 100%; max-height: none; margin: 0; diff --git a/internal/ui/embedded/styles/session.css b/internal/ui/embedded/styles/session.css index f13e1b03..c4b82092 100644 --- a/internal/ui/embedded/styles/session.css +++ b/internal/ui/embedded/styles/session.css @@ -10,7 +10,7 @@ --palette-surface: var(--surface); --palette-surface-2: var(--surface-2); --palette-text-soft: var(--text-soft); - --viewport-height: 100svh; + --viewport-height: var(--zc-svh, 100svh); } :root, [data-theme="dark"] { @@ -412,7 +412,7 @@ align-items: center; justify-content: center; gap: 14px; - min-height: var(--viewport-height, 100vh); + min-height: var(--viewport-height, var(--zc-vh, 100vh)); padding: 24px; text-align: center; color: var(--text-soft); @@ -479,7 +479,7 @@ line-height: var(--line-height); color: var(--text); background: var(--body-bg); - min-height: 100vh; + min-height: var(--zc-vh, 100vh); } body.pi-sheet-open { @@ -500,7 +500,7 @@ #app { display: flex; align-items: stretch; - height: calc(100vh - 52px); + height: calc(var(--zc-vh, 100vh) - 52px); margin-top: 52px; /* Chrome shell behind the resizer gutters so no body-bg slivers show beside the darker composer / sidebars. The content column re-lights @@ -1372,7 +1372,7 @@ width: min(640px, 90vw) !important; min-width: min(640px, 90vw) !important; max-width: min(640px, 90vw) !important; - height: calc(100vh - 52px); + height: calc(var(--zc-vh, 100vh) - 52px); z-index: 198; border-left: 1px solid var(--dim); box-shadow: -4px 0 24px rgba(0, 0, 0, 0.4); @@ -2720,6 +2720,96 @@ } } + /* Narrow header (phones, and any width once the UI scale zooms the page: + 390px at 150% is only 260 CSS px). A container query — unlike a media + query, which still sees the unzoomed 390px viewport — reacts to the real + layout width, so every action (incl. the + new-session button) shrinks + instead of being pushed off-screen. The title and owner badge give way + first; buttons never shrink below a 26px tap target. */ + .session-header-bar { + container-type: inline-size; + container-name: session-header; + } + + @container session-header (max-width: 560px) { + .session-header-right { + flex: 0 1 auto; + min-width: 0; + } + + .session-header-left { + gap: 4px; + } + + .session-header-back-label { + display: none; + } + + .session-header-back { + min-width: 26px; + height: 28px; + justify-content: center; + } + + /* basis 0: the title only takes space the buttons don't need. */ + .session-header-bar .session-header-title { + flex: 1 1 0; + min-width: 0; + margin: 0 4px; + } + + .session-header-left { + flex-shrink: 0; + } + + .session-header-right > :not(.session-owner-badge) { + flex-shrink: 0; + } + + .session-header-right .session-owner-badge { + flex-shrink: 1; + min-width: 0; + max-width: 96px; + overflow: hidden; + text-overflow: ellipsis; + margin-right: 4px; + } + + .session-header-actions, + .session-header-new, + .session-header-schedules, + .session-header-projects { + width: 28px; + height: 28px; + min-width: 26px; + margin-right: 0; + } + + .session-header-right { + gap: 2px; + } + } + + @container session-header (max-width: 300px) { + .session-header-bar .session-header-title { + display: none; + } + + /* No room left for a readable owner name; the sidebar/People switcher + still shows it. */ + .session-header-right .session-owner-badge { + display: none; + } + + .session-header-actions, + .session-header-new, + .session-header-schedules, + .session-header-projects { + width: 26px; + height: 26px; + } + } + .working-dots::after { content: ''; display: inline-block; @@ -3741,12 +3831,12 @@ @media (min-width: 901px) { html.pi-session-page, body.pi-session-page { - height: 100vh; + height: var(--zc-vh, 100vh); overflow: hidden; } #app { - height: calc(100vh - 52px); + height: calc(var(--zc-vh, 100vh) - 52px); margin-top: 52px; overflow: hidden; } @@ -3783,26 +3873,26 @@ width: 100%; display: flex; flex-direction: column; - height: 100vh; - height: var(--viewport-height, 100svh); - /* The base body rule sets min-height:100vh. On iOS 100vh is the LARGE + height: var(--zc-vh, 100vh); + height: var(--viewport-height, var(--zc-svh, 100svh)); + /* The base body rule sets min-height:var(--zc-vh, 100vh). On iOS var(--zc-vh, 100vh) is the LARGE viewport (full screen, behind the keyboard), and min-height beats height — so without this override the body stays full-height and the bottom-docked composer is buried under the keyboard. Track the visible viewport here too. */ - min-height: var(--viewport-height, 100svh); + min-height: var(--viewport-height, var(--zc-svh, 100svh)); overflow: hidden; } #app { flex: 1; min-height: 0; - /* Track the visible viewport, not 100vh. The base #app rule sizes to - calc(100vh - 52px); on iOS 100vh is the LARGE viewport (keyboard + /* Track the visible viewport, not var(--zc-vh, 100vh). The base #app rule sizes to + calc(var(--zc-vh, 100vh) - 52px); on iOS var(--zc-vh, 100vh) is the LARGE viewport (keyboard excluded), so when the keyboard opens #app stays full-height and its bottom-docked composer is pushed under the keyboard even though the fixed body already shrank to --viewport-height. Mirror the body fix. */ - height: calc(var(--viewport-height, 100svh) - 52px); + height: calc(var(--viewport-height, var(--zc-svh, 100svh)) - 52px); } #sidebar { @@ -3813,8 +3903,8 @@ max-width: min(var(--sidebar-width), 100vw); top: 0; bottom: 0; - height: 100vh; - height: 100svh; + height: var(--zc-vh, 100vh); + height: var(--zc-svh, 100svh); z-index: 99; transform: translateX(-100%); transition: transform 0.3s; @@ -3901,8 +3991,8 @@ width: min(320px, 85vw) !important; min-width: min(320px, 85vw) !important; max-width: min(320px, 85vw) !important; - height: 100vh !important; - height: var(--viewport-height, 100svh) !important; + height: var(--zc-vh, 100vh) !important; + height: var(--viewport-height, var(--zc-svh, 100svh)) !important; z-index: 1200 !important; background: var(--surface) !important; border-left: 1px solid var(--dim) !important; @@ -3946,7 +4036,7 @@ width: 100% !important; min-width: 0 !important; max-width: 100% !important; - height: var(--viewport-height, 100svh) !important; + height: var(--viewport-height, var(--zc-svh, 100svh)) !important; max-height: none !important; border-radius: 0 !important; resize: none !important; @@ -4158,7 +4248,7 @@ max-width: calc(100vw - 24px); height: 420px; min-height: 220px; - max-height: calc(100vh - 24px); + max-height: calc(var(--zc-vh, 100vh) - 24px); background: var(--container-bg, var(--surface)); border: 1px solid var(--dim); border-radius: 8px; @@ -5495,10 +5585,10 @@ .pi-sheet-panel.pi-sheet-mobile { max-width: 100%; width: 100%; - height: 100vh; - height: 100svh; - max-height: 100vh; - max-height: 100svh; + height: var(--zc-vh, 100vh); + height: var(--zc-svh, 100svh); + max-height: var(--zc-vh, 100vh); + max-height: var(--zc-svh, 100svh); border-radius: 0; border: none; transform: translateY(100%); @@ -5527,8 +5617,8 @@ .pi-sheet-panel.diff-sheet-panel { max-width: none; width: 100vw; - height: 100vh; - max-height: 100vh; + height: var(--zc-vh, 100vh); + max-height: var(--zc-vh, 100vh); border-radius: 0; border: none; background: var(--container-bg); @@ -5832,8 +5922,8 @@ display: flex; flex-direction: column; height: min(64vh, 520px); - min-height: min(360px, calc(100vh - 120px)); - max-height: calc(100vh - 120px); + min-height: min(360px, calc(var(--zc-vh, 100vh) - 120px)); + max-height: calc(var(--zc-vh, 100vh) - 120px); } .fork-search-wrap { @@ -6118,8 +6208,8 @@ display: flex; flex-direction: column; height: min(64vh, 520px); - min-height: min(360px, calc(100vh - 120px)); - max-height: calc(100vh - 120px); + min-height: min(360px, calc(var(--zc-vh, 100vh) - 120px)); + max-height: calc(var(--zc-vh, 100vh) - 120px); } .shortcuts-search-wrap { @@ -6553,7 +6643,7 @@ position: absolute; inset: 0; width: 100vw; - height: 100vh; + height: var(--zc-vh, 100vh); line-height: 0; } @@ -6763,3 +6853,378 @@ font-size: 12px; color: var(--text-soft, var(--muted)); } + + /* ── zcode/Codex-style collapsible rows (thinking + tool calls) ── */ + .zc-row { --zc-act: var(--accent); } + .zc-row-head { + all: unset; + box-sizing: border-box; + display: flex; + align-items: center; + gap: 8px; + width: 100%; + min-width: 0; + cursor: pointer; + -webkit-tap-highlight-color: transparent; + user-select: none; + -webkit-user-select: none; + font-size: 12.5px; + line-height: 20px; + } + .zc-row-head:focus-visible { outline: 1px solid var(--zc-act); outline-offset: 2px; border-radius: 4px; } + .zc-chevron { + flex: 0 0 auto; + width: 7px; height: 7px; + border-right: 1.6px solid var(--zc-act); + border-bottom: 1.6px solid var(--zc-act); + transform: rotate(-45deg); + transition: transform .18s ease; + margin: 0 3px 0 1px; + } + .zc-open > .zc-row-head .zc-chevron { transform: rotate(45deg); margin-top: -3px; } + .zc-label { flex: 0 0 auto; font-weight: 650; color: var(--zc-act); } + .zc-arg { + flex: 1 1 auto; min-width: 0; + overflow: hidden; white-space: nowrap; text-overflow: ellipsis; + color: var(--muted); + font-family: var(--font-code); + font-size: 12px; + } + .thinking-block .zc-arg { font-family: inherit; font-style: italic; } + .zc-open > .zc-row-head .zc-arg { opacity: .55; } + .zc-status { flex: 0 0 auto; width: 7px; height: 7px; border-radius: 50%; background: transparent; } + .zc-status-pending { background: var(--warning); animation: zc-pulse 1.2s ease-in-out infinite; } + .zc-status-error { background: var(--error); } + @keyframes zc-pulse { 50% { opacity: .3; } } + .zc-collapsed > .zc-row-body { display: none; } + .zc-open > .zc-row-body { margin-top: 6px; animation: zc-reveal .16s ease-out; } + @keyframes zc-reveal { from { opacity: 0; transform: translateY(-3px); } to { opacity: 1; transform: none; } } + .tool-execution.zc-row.zc-collapsed { padding-top: 6px; padding-bottom: 6px; } + + /* ── zcode theme picker ── */ + html[data-zcode-preset] { background-color: var(--body-bg) !important; } + .zc-picker-backdrop { + position: fixed; inset: 0; z-index: 1200; + background: rgba(0,0,0,.45); + backdrop-filter: blur(2px); -webkit-backdrop-filter: blur(2px); + } + .zc-picker-sheet { + position: fixed; z-index: 1201; + left: 50%; top: 50%; transform: translate(-50%, -50%); + width: min(720px, calc(100vw - 32px)); + max-height: min(80vh, 760px); + display: flex; flex-direction: column; + background: var(--surface); color: var(--text); + border: 1px solid color-mix(in srgb, var(--text) 12%, transparent); + border-radius: 18px; + box-shadow: 0 24px 80px rgba(0,0,0,.45); + font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", system-ui, sans-serif; + animation: zc-sheet-in .18s ease-out; + } + @keyframes zc-sheet-in { from { opacity: 0; transform: translate(-50%, -48%); } } + .zc-picker-head { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px 6px 20px; } + .zc-picker-title { font-size: 17px; font-weight: 650; letter-spacing: -0.01em; } + .zc-picker-close { + width: 34px; height: 34px; display: inline-flex; align-items: center; justify-content: center; + border-radius: 10px; border: 0; background: transparent; color: var(--muted); cursor: pointer; + } + .zc-picker-close:hover { background: color-mix(in srgb, var(--text) 8%, transparent); color: var(--text); } + .zc-picker-body { overflow-y: auto; padding: 4px 16px 16px; -webkit-overflow-scrolling: touch; } + .zc-picker { font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", system-ui, sans-serif; } + .zc-picker-inline { width: 100%; margin-top: 10px; } + .zc-settings-presets { flex-direction: column; align-items: stretch; } + .zc-picker-filters { display: flex; gap: 6px; margin: 4px 0 12px; } + .zc-picker-filter { + border: 1px solid color-mix(in srgb, var(--text) 14%, transparent); + background: transparent; color: var(--muted); + border-radius: 999px; padding: 5px 12px; font-size: 13px; cursor: pointer; font-family: inherit; + } + .zc-picker-filter.active { background: var(--accent); border-color: var(--accent); color: var(--body-bg); font-weight: 600; } + .zc-picker-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; } + .zc-swatch { + all: unset; box-sizing: border-box; cursor: pointer; + display: flex; flex-direction: column; gap: 6px; + padding: 6px; border-radius: 14px; + border: 1.5px solid transparent; + -webkit-tap-highlight-color: transparent; + transition: transform .12s, border-color .12s; + } + .zc-swatch:hover { transform: translateY(-1px); } + .zc-swatch:active { transform: scale(.97); } + .zc-swatch:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } + .zc-swatch.active { border-color: var(--accent); } + .zc-swatch-preview { + position: relative; display: block; height: 78px; border-radius: 10px; overflow: hidden; + background: var(--body-bg); + border: 1px solid color-mix(in srgb, var(--text) 12%, transparent); + } + .zc-swatch-bubble { + position: absolute; right: 8px; top: 8px; width: 46%; height: 14px; border-radius: 8px 8px 3px 8px; + background: var(--surface-2); + border: 1px solid color-mix(in srgb, var(--text) 10%, transparent); + } + .zc-swatch-line { position: absolute; left: 9px; height: 5px; border-radius: 3px; background: var(--text); opacity: .85; } + .zc-l1 { top: 32px; width: 62%; } + .zc-l2 { top: 42px; width: 44%; background: var(--muted); } + .zc-swatch-dots { position: absolute; left: 9px; right: 9px; bottom: 9px; display: flex; gap: 4px; } + .zc-swatch-dots i { flex: 1; height: 7px; border-radius: 4px; } + .zc-swatch-name { + display: flex; align-items: center; gap: 4px; padding: 0 2px; + font-size: 13px; font-weight: 550; color: var(--text); + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; + } + /* names sit outside the preview but inside the swatch, which carries the + preset's own --text; keep them in the surrounding UI colour instead. */ + .zc-picker .zc-swatch-name { color: inherit; } + .zc-swatch-check { display: inline-flex; color: var(--accent); } + .zc-picker-footer { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; margin-top: 14px; } + .zc-picker-reset { + border: 1px solid color-mix(in srgb, var(--text) 14%, transparent); background: transparent; + color: var(--text); border-radius: 10px; padding: 7px 12px; font-size: 13px; cursor: pointer; font-family: inherit; + } + .zc-picker-reset.active { border-color: var(--accent); color: var(--accent); } + .zc-size-row { display: flex; align-items: center; gap: 8px; margin: 6px 0 8px; } + .zc-size-btn { min-width: 52px; height: 40px; border-radius: 10px; border: 1px solid var(--border); background: var(--surface, transparent); color: var(--text); font-weight: 600; cursor: pointer; display: inline-flex; align-items: baseline; justify-content: center; gap: 1px; } + .zc-size-btn:disabled { opacity: .4; cursor: default; } + .zc-size-btn:not(:disabled):hover { border-color: var(--accent); } + .zc-size-val { min-width: 52px; text-align: center; font-variant-numeric: tabular-nums; font-weight: 600; } + .zc-size-reset { margin-left: auto; height: 40px; padding: 0 12px; border-radius: 10px; border: 1px solid var(--border); background: transparent; color: var(--muted); cursor: pointer; } + .zc-size-reset.active { color: var(--accent); border-color: var(--accent); } + .zc-size-steps { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 6px; } + .zc-size-steps button { flex: 1; min-width: 34px; height: 26px; border-radius: 6px; border: 1px solid var(--border); background: transparent; color: var(--muted); font-size: 11px; cursor: pointer; } + .zc-size-steps button.active { background: var(--accent); color: var(--body-bg, #000); border-color: var(--accent); } + .zc-picker-hint { font-size: 12px; color: var(--muted); } + .zc-picker-empty { color: var(--muted); font-size: 13px; } + @media (max-width: 640px) { + .zc-picker-sheet { + left: 0; right: 0; bottom: 0; top: auto; transform: none; + width: 100%; max-height: 82vh; border-radius: 20px 20px 0 0; + padding-bottom: env(safe-area-inset-bottom); + animation: zc-sheet-up .22s ease-out; + } + @keyframes zc-sheet-up { from { transform: translateY(40px); opacity: 0; } } + .zc-picker-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; } + .zc-swatch-preview { height: 70px; } + } + + /* ── zcode v3 fallbacks (sem preset): ícones, badges, tabelas/código ── */ + .zc-icon { flex: 0 0 auto; display: inline-flex; align-items: center; color: var(--zc-act); } + .zc-file { font-family: var(--font-code); font-size: 12px; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 45%; } + .zc-diffstat { display: inline-flex; gap: 6px; font-family: var(--font-code); font-size: 12px; } + .zc-add { color: var(--success); } + .zc-del { color: var(--error); } + .zc-progress { font-family: var(--font-code); font-size: 11.5px; color: var(--zc-act); } + .zc-worked { display: flex; align-items: center; gap: 10px; margin: 4px 0 10px; color: var(--muted); font-size: 12px; } + .zc-worked::before, .zc-worked::after { content: ""; flex: 1; height: 1px; background: color-mix(in srgb, var(--text) 12%, transparent); } + .zc-mdbar { display: flex; justify-content: flex-end; gap: 2px; } + .zc-code { position: relative; } + .zc-mdbar-code { position: absolute; top: 4px; right: 4px; } + .zc-mdbtn { all: unset; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; width: 26px; height: 24px; border-radius: 6px; color: var(--muted); } + .zc-mdbtn:hover { color: var(--text); background: color-mix(in srgb, var(--text) 8%, transparent); } + .zc-table-scroll { overflow-x: auto; } + .zc-table.zc-expanded { position: fixed; inset: 5vh 4vw; z-index: 1300; background: var(--body-bg); overflow: auto; padding: 8px; box-shadow: 0 30px 90px rgba(0,0,0,.55); } + +/* ── Multi-user hub: people switcher + session owner badge ── */ + + .people-switcher { + position: relative; + padding: 6px 8px 4px; + } + .people-switcher-btn { + width: 100%; + display: flex; + align-items: center; + gap: 6px; + padding: 6px 8px; + border-radius: 8px; + cursor: pointer; + background: var(--container-bg, rgba(255, 255, 255, 0.04)); + border: 1px solid var(--border, rgba(255, 255, 255, 0.08)); + color: var(--text, inherit); + font: inherit; + font-size: 0.86em; + text-align: left; + } + .people-switcher.others .people-switcher-btn { + border-color: var(--accent, #fb923c); + background: color-mix(in srgb, var(--accent, #fb923c) 14%, transparent); + } + .people-switcher-label { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-weight: 600; + } + .people-switcher-icon, + .people-switcher-chev, + .people-check { + display: inline-flex; + opacity: 0.85; + } + .people-switcher-menu { + position: absolute; + left: 8px; + right: 8px; + top: calc(100% - 2px); + z-index: 50; + max-height: 60vh; + overflow: auto; + padding: 4px; + border-radius: 10px; + background: var(--body-bg, #111); + border: 1px solid var(--border, rgba(255, 255, 255, 0.12)); + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35); + } + .people-switcher-menu button { + width: 100%; + display: flex; + align-items: center; + gap: 8px; + padding: 7px 8px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--text, inherit); + font: inherit; + font-size: 0.86em; + cursor: pointer; + text-align: left; + } + .people-switcher-menu button:hover, + .people-switcher-menu button[aria-selected='true'] { + background: var(--hover, rgba(255, 255, 255, 0.07)); + } + .people-switcher-section { + padding: 6px 8px 2px; + font-size: 0.72em; + text-transform: uppercase; + letter-spacing: 0.06em; + opacity: 0.55; + } + .people-switcher-sep { + height: 1px; + margin: 4px 6px; + background: var(--border, rgba(255, 255, 255, 0.1)); + } + .people-name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .people-count { + font-size: 0.85em; + opacity: 0.6; + font-variant-numeric: tabular-nums; + } + .people-avatar { + width: 18px; + height: 18px; + border-radius: 50%; + display: inline-flex; + align-items: center; + justify-content: center; + font-size: 0.72em; + font-weight: 700; + text-transform: uppercase; + background: color-mix(in srgb, var(--accent, #fb923c) 30%, transparent); + color: var(--text, inherit); + } + .people-empty { + padding: 6px 8px; + font-size: 0.8em; + opacity: 0.6; + } + + + .session-owner-badge { + display: inline-flex; + align-items: center; + gap: 4px; + margin-right: 6px; + padding: 2px 8px; + border-radius: 999px; + font-size: 0.75em; + white-space: nowrap; + flex-shrink: 0; + border: 1px solid var(--border, rgba(255, 255, 255, 0.12)); + opacity: 0.85; + } + .session-owner-badge.others { + opacity: 1; + font-weight: 600; + border-color: var(--accent, #fb923c); + background: color-mix(in srgb, var(--accent, #fb923c) 16%, transparent); + } + .session-owner-source { + opacity: 0.6; + font-weight: 400; + } + + +/* ── Message footer (copy / rating / link / time) + changed-files cards ── */ +.msg-footer { display: flex; align-items: center; gap: 2px; margin: 6px 0 2px; color: var(--dim); } +.msg-act { + display: inline-flex; align-items: center; gap: 4px; min-width: 30px; height: 28px; padding: 0 6px; + border: 0; border-radius: 6px; background: transparent; color: var(--dim); cursor: pointer; font: inherit; font-size: 11px; +} +.msg-act:hover { color: var(--text); background: var(--hover); } +.msg-act.on { color: var(--accent); } +.msg-act-note { color: var(--success, var(--accent)); } +.msg-time { margin-left: 6px; font-size: 11px; color: var(--dim); font-variant-numeric: tabular-nums; } +.msg-files { margin: 10px 0 4px; border: 1px solid color-mix(in srgb, var(--dim) 28%, transparent); border-radius: 10px; overflow: hidden; } +.msg-files-head { + width: 100%; display: flex; align-items: center; gap: 8px; padding: 8px 10px; border: 0; background: transparent; + color: var(--text); font: inherit; font-size: 12px; cursor: pointer; text-align: left; +} +.msg-files-head:hover { background: var(--hover); } +.msg-files-chev { display: inline-flex; transition: transform 0.15s; color: var(--dim); } +.msg-files.open .msg-files-chev { transform: rotate(90deg); } +.msg-add { color: var(--success, #4ade80); font-variant-numeric: tabular-nums; } +.msg-del { color: var(--error, #f87171); font-variant-numeric: tabular-nums; } +.msg-files-list { display: flex; flex-direction: column; gap: 6px; padding: 0 8px 8px; } +.msg-file-card { + display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; + background: var(--container-bg); border: 1px solid color-mix(in srgb, var(--dim) 28%, transparent); +} +.msg-file-icon { display: inline-flex; color: var(--accent); } +.msg-file-meta { flex: 1; min-width: 0; display: flex; flex-direction: column; } +.msg-file-name { font-size: 12.5px; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.msg-file-type { font-size: 11px; color: var(--dim); } +.msg-file-open { + border: 1px solid color-mix(in srgb, var(--dim) 28%, transparent); background: transparent; color: var(--text); border-radius: 6px; + padding: 4px 10px; font: inherit; font-size: 11.5px; cursor: pointer; +} +.msg-file-open:hover { background: var(--hover); } +@media (max-width: 700px) { .msg-act { min-width: 36px; height: 34px; } } +.msg-file-type .msg-add, .msg-file-type .msg-del { margin-left: 4px; } + +/* ── Voice input mic ── */ +.pi-chat-mic-button.recording { color: var(--error, #f87171); animation: pi-mic-pulse 1.2s ease-in-out infinite; } +@keyframes pi-mic-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.45; } } + +/* ── Subagent (pi subagent extension) cards ── */ +.subagent-runs { display: flex; flex-direction: column; gap: 6px; margin: 4px 0 2px; } +.subagent-run { border: 1px solid color-mix(in srgb, var(--dim) 70%, transparent); border-radius: 8px; padding: 6px 9px; background: color-mix(in srgb, var(--surface) 50%, transparent); min-width: 0; } +.subagent-run[data-status="running"] { border-color: color-mix(in srgb, var(--accent) 55%, transparent); } +.subagent-run[data-status="failed"], .subagent-run[data-status="aborted"] { border-color: color-mix(in srgb, var(--error, #f87171) 60%, transparent); } +.subagent-run-head { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; font-size: 12px; min-width: 0; } +.subagent-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--dim); flex-shrink: 0; } +.subagent-dot-running { background: var(--accent); animation: subagent-pulse 1.1s ease-in-out infinite; } +.subagent-dot-completed { background: var(--success, #4ade80); } +.subagent-dot-failed, .subagent-dot-aborted { background: var(--error, #f87171); } +@keyframes subagent-pulse { 50% { opacity: 0.35; } } +.subagent-step { color: var(--muted); font-variant-numeric: tabular-nums; } +.subagent-agent { font-weight: 600; color: var(--text); } +.subagent-status { color: var(--muted); } +.subagent-model, .subagent-usage { color: var(--muted); opacity: 0.8; font-size: 11px; overflow-wrap: anywhere; } +.subagent-task { color: var(--muted); font-size: 12px; margin-top: 3px; white-space: pre-wrap; overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 3; line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; } +.subagent-items { list-style: none; margin: 4px 0 0; padding: 0; font-size: 11px; color: var(--muted); } +.subagent-item { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.subagent-item-name { color: var(--accent); margin-right: 5px; } +.subagent-error { color: var(--error, #f87171); font-size: 12px; margin-top: 3px; white-space: pre-wrap; } +.subagent-out-toggle { margin-top: 4px; background: none; border: 0; padding: 2px 0; color: var(--accent); font: inherit; font-size: 11px; cursor: pointer; } +.subagent-output { margin: 4px 0 0; max-height: 320px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; } diff --git a/internal/ui/live_page.go b/internal/ui/live_page.go index c56472cf..19332c4a 100644 --- a/internal/ui/live_page.go +++ b/internal/ui/live_page.go @@ -3,6 +3,7 @@ package ui import ( "fmt" "html/template" + "strconv" "strings" ) @@ -18,6 +19,66 @@ type liveDocumentData struct { // to "dark"; app wiring overrides it via SetThemeProvider to read the DB. var themeProvider = func() string { return "dark" } +// presetProvider returns the server-persisted zcode colour preset ("" = none). +var presetProvider = func() string { return "" } + +// SetPresetProvider installs the function used to resolve the zcode preset. +func SetPresetProvider(fn func() string) { + if fn != nil { + presetProvider = fn + } +} + +// actProvider returns the server-persisted action-colour scheme ("" = preset's own). +var actProvider = func() string { return "" } + +// SetActProvider installs the function used to resolve the action-colour scheme. +func SetActProvider(fn func() string) { + if fn != nil { + actProvider = fn + } +} + +// scaleProvider returns the server-persisted whole-UI scale in percent. +var scaleProvider = func() string { return "100" } + +// SetScaleProvider installs the function used to resolve the UI scale. +func SetScaleProvider(fn func() string) { + if fn != nil { + scaleProvider = fn + } +} + +// uiScale returns the clamped scale (80..150, step 10). +func uiScale() int { + n := 0 + for _, r := range scaleProvider() { + if r < '0' || r > '9' { + return 100 + } + n = n*10 + int(r-'0') + if n > 1000 { + return 100 + } + } + n = (n + 5) / 10 * 10 + if n < 80 || n > 150 { + return 100 + } + return n +} + +// safePreset keeps only [a-z0-9-] so the value is safe inside an attribute. +func safePreset(v string) string { + var b strings.Builder + for _, r := range v { + if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' { + b.WriteRune(r) + } + } + return b.String() +} + // SetThemeProvider installs the function used to resolve the current // server-backed theme for server-side injection. func SetThemeProvider(fn func() string) { @@ -53,12 +114,12 @@ func SetFontProvider(fn func() (string, string, string, string, string)) { // /custom-themes.css — so a parser-blocking + + +{#if text} + {#if changes.files.length} +
+ + {#if showFiles} +
+ {#each changes.files as f (f.path)} +
+ {@html icon(FileCode, { size: 16 })} + + {f.name} + {f.ext} · {f.op === 'write' ? 'criado' : 'editado'}{#if f.added} + +{f.added}{/if}{#if f.removed} −{f.removed}{/if} + + {#if f.anchor}{/if} +
+ {/each} +
+ {/if} +
+ {/if} + +{/if} diff --git a/web/src/components/session/MessageFooter.test.js b/web/src/components/session/MessageFooter.test.js new file mode 100644 index 00000000..9e6e9f7f --- /dev/null +++ b/web/src/components/session/MessageFooter.test.js @@ -0,0 +1,79 @@ +import { describe, expect, it, vi } from 'vitest'; +import { render, waitFor } from '@testing-library/svelte'; +import userEvent from '@testing-library/user-event'; +import MessageFooter from './MessageFooter.svelte'; + +const entry = { + type: 'message', + id: 'a2', + timestamp: '2026-11-14T16:00:00.000Z', + message: { + role: 'assistant', + stopReason: 'stop', + content: [ + { type: 'thinking', thinking: 'segredo' }, + { type: 'text', text: '**ok**' }, + ], + }, +}; + +describe('MessageFooter', () => { + it('copies the final markdown and shows Copiado', async () => { + const user = userEvent.setup(); + const copy = vi.fn().mockResolvedValue(true); + const { getByLabelText, findByText } = render(MessageFooter, { props: { entry, copy } }); + await user.click(getByLabelText('Copiar resposta')); + expect(copy).toHaveBeenCalledWith('**ok**'); + expect(await findByText('Copiado')).toBeTruthy(); + }); + + it('rates a message and toggles it off', async () => { + const user = userEvent.setup(); + window.history.replaceState({}, '', '/session?id=s1.jsonl'); + const rate = vi.fn().mockResolvedValue({ ok: true }); + const ratings = vi.fn().mockResolvedValue({}); + const { getByLabelText } = render(MessageFooter, { + props: { entry, live: true, rate, ratings }, + }); + await waitFor(() => expect(ratings).toHaveBeenCalledWith('s1.jsonl')); + const up = getByLabelText('Boa resposta'); + await user.click(up); + expect(rate).toHaveBeenLastCalledWith('s1.jsonl', 'a2', 1); + expect(up.getAttribute('aria-pressed')).toBe('true'); + await user.click(up); + expect(rate).toHaveBeenLastCalledWith('s1.jsonl', 'a2', 0); + }); + + it('is hidden for unfinished or tool-only messages', () => { + const { container } = render(MessageFooter, { + props: { entry: { ...entry, message: { ...entry.message, stopReason: 'toolUse' } } }, + }); + expect(container.querySelector('.msg-footer')).toBeNull(); + }); +}); + +describe('MessageFooter retry', () => { + it('shows Refazer for a live answer with a prompt and calls retry', async () => { + const user = userEvent.setup(); + window.history.replaceState({}, '', '/session?id=s9.jsonl'); + const model = { + entries: [ + { type: 'model_change', id: 'm0', parentId: null }, + { type: 'message', id: 'u1', parentId: 'm0', message: { role: 'user', content: 'oi' } }, + { ...entry, parentId: 'u1' }, + ], + }; + const retry = vi.fn().mockResolvedValue('x'); + const ratings = vi.fn().mockResolvedValue({}); + const { getByLabelText } = render(MessageFooter, { + props: { entry: model.entries[2], model, live: true, retry, ratings }, + }); + await user.click(getByLabelText('Refazer resposta')); + expect(retry).toHaveBeenCalledWith('s9.jsonl', { text: 'oi', forkAt: 'm0' }); + }); + + it('hides Refazer in exports (not live)', () => { + const { queryByLabelText } = render(MessageFooter, { props: { entry } }); + expect(queryByLabelText('Refazer resposta')).toBeNull(); + }); +}); diff --git a/web/src/components/session/SessionEntry.svelte b/web/src/components/session/SessionEntry.svelte index 4fe94746..92b7df8d 100644 --- a/web/src/components/session/SessionEntry.svelte +++ b/web/src/components/session/SessionEntry.svelte @@ -11,6 +11,16 @@ import { formatTimestamp } from '../../session/render/entry-format.js'; import ToolCall from './ToolCall.svelte'; import ToolOutput from './ToolOutput.svelte'; + import MessageFooter from './MessageFooter.svelte'; + import { + isOpen, + toggleOpen, + thinkingPreview, + kindIcon, + turnDuration, + formatDuration, + } from '../../session/ui/collapse-state.js'; + import { enhanceMarkdownHtml } from '../../session/ui/zc-markdown.js'; // `live` (passed from ) gates the fork/label buttons, which // need the chat composer; copy-link is always shown. The static export passes @@ -19,7 +29,12 @@ let { entry, model = null, live = false } = $props(); const ts = $derived(formatTimestamp(entry?.timestamp)); - const md = (text) => safeMarkedParse(text, { marked }); + const md = (text) => enhanceMarkdownHtml(safeMarkedParse(text, { marked })); + const worked = $derived( + msg?.role === 'assistant' && msg.content?.some?.((b) => b.type === 'text' && b.text.trim()) + ? turnDuration(entry, model?.entries) + : null, + ); const msg = $derived(entry?.type === 'message' ? entry.message : null); const userText = $derived.by(() => { @@ -70,20 +85,49 @@ {:else if msg && msg.role === 'assistant'}
{@render actions(entry.id)}{@render timestamp()} + {#if worked}{/if} {#each msg.content as block, blockIndex (blockIndex)} {#if block.type === 'text' && block.text.trim()}
{@html md(block.text)} -
{:else if block.type === 'thinking' && block.thinking.trim()}
{:else if block.type === 'thinking' && block.thinking.trim()}{@const tkey = `think:${entry.id}:${blockIndex}`}{@const topen = + isOpen(tkey, false)} +
-
{block.thinking}
-
Thinking ...
+ +
+
{block.thinking}
+
Thinking ...
+
{/if} {/each} {#each msg.content as block, toolBlockIndex (toolBlockIndex)}{#if block.type === 'toolCall'}{/if}{/each} + {#if msg.stopReason === 'aborted'}
Aborted
{:else if msg.stopReason === 'error'}
@@ -92,6 +136,7 @@
{:else if msg && msg.role === 'bashExecution'}
+ {#if activeTab !== 'outline'}{/if} +