pi-remote-web 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0] - 2026-12-04
4
+
5
+ - First version: start, resume and chat with Pi sessions from a phone browser; answer standard Pi dialogs; username and password sign-in.
6
+ - Scope cut to one user on their own computer and phone: no terminal attach, no rename, no exactly-once delivery lock.
package/DESIGN.md ADDED
@@ -0,0 +1,128 @@
1
+ # Design
2
+
3
+ ## Goal
4
+
5
+ One person uses Pi from their own phone over their own Tailscale network: start a Pi conversation in a project with a chosen model and thinking level, or resume one, send prompts, answer Pi's dialogs, and stop work. After Tailscale Serve is set up, one command starts it. The code stays small enough to read in one sitting.
6
+
7
+ ## Threat model
8
+
9
+ Trusted:
10
+
11
+ - The computer and the user account that runs the service. Other local processes are not attackers.
12
+ - The user's own devices on the tailnet.
13
+ - The project root and its folders. Only the user can change them.
14
+
15
+ Defended against:
16
+
17
+ - Anyone who reaches the address without the password: another device on the tailnet, or an address made public by mistake.
18
+ - Web pages on other sites: cross-site requests (CSRF) and DNS rebinding.
19
+ - Untrusted text from Pi or the browser: script injection in the page, and local paths or transcript text in error messages.
20
+
21
+ Accepted risks:
22
+
23
+ - A hostile process or a second user on the same computer.
24
+ - A folder under the project root replaced between the app's check and Pi's start.
25
+ - A prompt sent twice or lost after a timeout or network drop. The page says the outcome is unknown; the user checks the chat and decides. Nothing retries automatically.
26
+ - Browsers send the `127.0.0.1` cookie to every local port, so other local web servers see the local sign-in cookie.
27
+ - A conversation resumed from the phone while it is still open in a terminal. The page asks the user to confirm first.
28
+ - After an extension command switches a Pi process to a conversation from another project, the page still shows the first project's name. The chat shows the new conversation.
29
+
30
+ ## Non-goals
31
+
32
+ Sharing a session that is open in a terminal, more than one user, exactly-once delivery, renaming conversations, push notifications, reliable background use, images, Markdown, changing the model during a conversation, file or shell routes, saved transcripts, public exposure, tunnels and service install.
33
+
34
+ ## Architecture
35
+
36
+ ```
37
+ Phone ──HTTPS (Tailscale Serve)──▶ 127.0.0.1:<port> Node service ──stdio RPC──▶ pi --mode rpc
38
+ (one per conversation)
39
+ ```
40
+
41
+ No npm dependencies. No build step.
42
+
43
+ | File | Job |
44
+ | --- | --- |
45
+ | `src/cli.mjs` | Options, first-run setup, start and stop |
46
+ | `src/config.mjs` | Load, validate and save the config; hash and check the password |
47
+ | `src/projects.mjs` | Find project folders at startup |
48
+ | `src/server.mjs` | HTTP, sign-in, Host and Origin checks, routes |
49
+ | `src/sessions.mjs` | Start Pi processes, RPC, transcript, dialogs |
50
+ | `src/list-sessions.mjs`, `src/list-child.mjs` | Previous conversations and models, read in a child process |
51
+ | `src/pi-install.mjs` | Find the Pi CLI and SDK |
52
+ | `public/` | Browser app |
53
+
54
+ ## Configuration
55
+
56
+ One file, `~/.config/pi-remote-web/config.json` (or `PI_REMOTE_WEB_CONFIG`), mode 0600:
57
+
58
+ | Field | Meaning |
59
+ | --- | --- |
60
+ | `port` | Loopback port |
61
+ | `remoteOrigin` | Optional exact HTTPS origin, host name only |
62
+ | `credentials` | `{username, algorithm: 'scrypt', salt, hash}`; password 12+ characters |
63
+ | `root` | Absolute project root |
64
+ | `pi` | `{cliPath, sdkPath}` of the Pi install |
65
+
66
+ Unknown fields are refused, except the retired `agentToken` and `maxProcesses`, which are dropped on the next save. Passwords come only from a hidden terminal prompt, never from arguments.
67
+
68
+ ## Projects
69
+
70
+ At startup the root and its direct, non-hidden, non-symlink subfolders become projects, with IDs derived from their paths. The browser sends only these IDs, never paths. Previous conversations get random IDs that map to session files on the server. Restart to see new folders.
71
+
72
+ ## Sign-in and requests
73
+
74
+ - Every request needs an exact `Host`. Every POST needs the matching `Origin`. No CORS.
75
+ - CSP allows only same-origin scripts, styles and connections, and forbids framing. Authenticated responses are `no-store`.
76
+ - Sign-in checks a salted scrypt hash. At most 10 attempts a minute for all clients together, because forwarded client addresses cannot be trusted.
77
+ - The cookie is a random 32-byte value: HttpOnly, SameSite=Strict, Secure on HTTPS, 8 hours, valid only on the origin that issued it. Cookies live in memory, so a restart signs everyone out.
78
+
79
+ | Route | Purpose |
80
+ | --- | --- |
81
+ | `POST /api/login`, `POST /api/logout` | Sign in, sign out |
82
+ | `GET /api/state` | `{projects, sessions}`. Each session: `id, projectId, name, model, busy, status, messages, live, dialogs, queued`; `name` is Pi's session name, else the first prompt, else "New conversation"; `model` is a read-only label from `get_state`, such as "Claude Sonnet 4.5 · Thinking: medium" |
83
+ | `GET /api/archives?projectId=` | Previous conversations of one project. Each: `archiveId, name, firstMessage, modified`; `firstMessage` is the first prompt, shown when there is no name |
84
+ | `GET /api/models?projectId=` | `{models, defaults}`. Each model: `provider, id, name, levels`; `levels` are the thinking levels Pi offers for it, empty without reasoning. `defaults` is `{provider, id, thinking}` from Pi's settings for the project |
85
+ | `POST /api/sessions` | `{projectId, provider?, model?, thinking?}` starts, `{projectId, archiveId}` resumes; returns `{sessionId}` |
86
+ | `POST /api/command` | `{sessionId, action, ...}`: `prompt {text, mode}`, `abort`, `stop`, `answer {dialogId, value \| confirmed \| cancelled}` |
87
+
88
+ The browser polls `/api/state` every second while visible. It sends one change at a time and disables the controls while it waits. A timeout or network error shows "This may have reached Pi. Check the chat before you send it again." Nothing locks and nothing retries.
89
+
90
+ Error messages reach the browser only when the code made them safe (`OperationError`). Other errors become "Request failed".
91
+
92
+ ## Model choice
93
+
94
+ The project screen lists the models with usable auth, the set Pi's `/model` picker shows, and preselects Pi's default model and thinking level. The choice stays in page memory for new conversations and resets on reload. If the list fails, a new conversation uses Pi's defaults.
95
+
96
+ The server accepts a model and thinking level only if they are in the project's last model listing: the model by exact provider and ID, and a thinking level exactly when the model offers levels. Anything else is refused with 400 before Pi starts. A resumed conversation keeps the model and thinking level its session recorded, so it takes no choice. The model cannot change during a conversation.
97
+
98
+ ## Running Pi
99
+
100
+ - Each conversation is `node <pi cli> --mode rpc [--session <file>] [--provider <provider> --model <id> [--thinking <level>]]` in the project folder, with the user's normal environment minus `PI_SESSION_*`. Providers, extensions and project trust apply as usual.
101
+ - At most 4 Pi processes at once. The service does not open one session file twice.
102
+ - Each RPC request has a random ID and, except for prompts, a 15-second timeout.
103
+ - When Pi starts, and after each prompt reply and each `agent_settled`, the service reads the name, model label and the last 100 messages with `get_state` and `get_messages`. The chat shows whatever conversation Pi holds now, including after an extension command switches session.
104
+ - A prompt succeeds when it is written to Pi. Pi replies to an extension command only when it finishes, so the browser does not wait for the reply. If Pi rejects the prompt later, the session `status` says so.
105
+ - A failed reply from `message_end` is held until `agent_end` and shown only if its `willRetry` is false. Pi drops a retried reply from its history.
106
+ - `live` holds the text Pi is streaming. `queued` lists steering and follow-up messages Pi has not delivered yet, from `queue_update`.
107
+ - Select, confirm, input and editor dialogs are shown in the browser. Pi's other extension UI requests (notices, status, widgets, title) need no answer and are ignored. A dialog stays until it is answered, its own timeout passes or Pi exits. An answer succeeds when it is written to Pi; Pi sends no confirmation. An answer to a dialog that is gone fails with a clear message.
108
+ - Abort sends `clear_queue`, then `abort`, so no queued message starts after it. Stop ends the process: close stdin, then SIGKILL after one second.
109
+ - An RPC line over 8 MiB is dropped and leaves a note in the chat. A request that waited for it times out. If `get_messages` is too large, the chat shows "Earlier history unavailable", keeps working, and adds new messages from `message_end`. No paging.
110
+ - Pi's stderr is drained and never logged.
111
+
112
+ ## Limits
113
+
114
+ 100 messages of 8,000 characters per session, a 300-character summary of each tool call's arguments, 16,000-character prompts, 64 KiB request bodies, 8 MiB RPC lines, 4 Pi processes, 10 sign-ins a minute. Previous conversations: the newest 500 per project, each first prompt cut to one line of 100 characters (also the label of a live conversation without a name), read in a child process with a 256 MiB heap and a 30-second limit. Models: at most 500, read the same way; the child loads Pi's extensions, which can add providers. Model fields are at most 200 characters.
115
+
116
+ ## Testing
117
+
118
+ Node's built-in test runner, a loopback server and a fake Pi. Cover sign-in and cookies, Host and Origin checks, unknown session IDs, Pi exit during a request, dialog answers, model and thinking-level checks and malformed input. Test on a real phone over Tailscale by hand.
119
+
120
+ ## Review boundary
121
+
122
+ Review against this document. A finding counts only when it shows a realistic failure for one user on their own computer and phone, inside the threat model. These are out of scope:
123
+
124
+ - Anything under accepted risks or non-goals.
125
+ - Rare races whose result the user can see and fix: reload, check the chat, press Stop.
126
+ - Hardening against the local machine.
127
+
128
+ Prefer deleting code to adding it. A fix that adds new state, a new protocol step or a new limit needs a line in this document first.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tboon0
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,78 @@
1
- # Temporary Holding Version
1
+ # pi-remote-web
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Use [Pi](https://pi.dev) from your phone. A small web app runs on your computer, listens only on `127.0.0.1`, and starts Pi for you. You reach it from your phone over Tailscale.
4
+
5
+ > **Prompts from the browser run with all of Pi's tool permissions.** This is not a sandbox. Anyone who signs in can do anything your Pi can do.
6
+
7
+ ## Features
8
+
9
+ - Start or resume Pi conversations in your project folders. Pick the model and thinking level before you start; a resumed conversation keeps its own.
10
+ - Send prompts, steer or queue follow-ups, stop work, close conversations.
11
+ - Answer Pi's dialogs (select, confirm, input, editor).
12
+ - Username and password sign-in. Dark, mobile-first UI. No build step, no dependencies.
13
+
14
+ ## Quick start
15
+
16
+ Requires Node 22.19+ and Pi. Tested with Pi 1.8.0 on macOS, from an Android phone. Not tested: iPhone, Linux and Windows.
17
+
18
+ ```sh
19
+ npm install -g pi-remote-web
20
+ pi-remote-web
21
+ ```
22
+
23
+ The first run asks for:
24
+
25
+ 1. A project root (default: the current folder). The root and its direct subfolders become projects. Hidden folders and symlinks are skipped.
26
+ 2. A username and a password of at least 12 characters.
27
+
28
+ Open the printed address, sign in, pick a project and start a conversation. Keep the command running. Ctrl+C stops it and every conversation it started.
29
+
30
+ | Option | Effect |
31
+ | --- | --- |
32
+ | `--root <dir>` | Use a different project root |
33
+ | `--remote-origin <url>` | Allow an exact HTTPS address, such as `https://mac.tailnet.ts.net` |
34
+ | `--local-only` | Remove the remote address |
35
+ | `--port <n>` | Listen on another port (default 8787) |
36
+ | `--change-password` | Replace the username and password |
37
+ | `--pi-dir <dir>` | Use this Pi install if it is not found automatically |
38
+
39
+ Settings are saved in `~/.config/pi-remote-web/config.json` (mode 0600). Stop the service before you change settings. Restart to see new project folders.
40
+
41
+ ## Use it from your phone
42
+
43
+ 1. Install Tailscale on the computer and the phone. Limit access to your own devices.
44
+ 2. On the computer, run `tailscale serve --bg 8787`. Use **Serve, not Funnel**: Funnel makes the app public.
45
+ 3. Stop the service if it is running (Ctrl+C), then run `pi-remote-web --remote-origin https://<machine>.<tailnet>.ts.net`. The address is saved, so later starts need no options.
46
+ 4. Open that address on the phone and sign in. You can add it to the home screen.
47
+
48
+ Keep the computer awake.
49
+
50
+ ## Security and limits
51
+
52
+ - **Full permissions.** A prompt from the browser can do anything your Pi can.
53
+ - **Built for one person** on their own computer and their own devices. It protects against people who reach the address without the password and against other web sites. It does not protect against other users or programs on the same computer.
54
+ - **Local only.** The server listens on `127.0.0.1`. Never bind it to `0.0.0.0`, and never use Funnel or a public tunnel.
55
+ - **Project root is not a sandbox.** It limits which folders you can pick, not what Pi can do.
56
+ - **"Sent" means written to Pi**, not finished. After a timeout or a network drop, the page says the outcome is unknown. Check the chat before you send again. Nothing retries automatically.
57
+ - **No saved transcripts.** The app keeps the last 100 messages of each conversation in memory. Pi still saves its own history. Tool calls and output are shown and can contain secrets.
58
+ - **Other local web servers see the local sign-in cookie**, because browsers send `127.0.0.1` cookies to every port. Use the Tailscale address, or sign out of the local one.
59
+ - **Sign-in allows 10 attempts a minute for all devices together.** A device on your tailnet that guesses passwords can block your sign-in for a minute.
60
+ - Don't resume a conversation that is still open in a terminal. The app asks you to confirm.
61
+ - Pi's custom extension UI (`ctx.ui.custom()`) does not work in conversations started from the browser.
62
+
63
+ Not supported: sharing a session open in a terminal, renaming, push notifications, background use on Android, images, Markdown, changing the model during a conversation.
64
+
65
+ ## Development
66
+
67
+ ```sh
68
+ git clone https://github.com/tboon0/pi-remote-web.git && cd pi-remote-web
69
+ node bin/pi-remote-web.mjs
70
+ npm test # loopback server and a fake Pi, no model calls
71
+ npm run check # syntax check
72
+ ```
73
+
74
+ See [DESIGN.md](DESIGN.md) for the threat model, protocol and review boundary. To report a security problem, see [SECURITY.md](SECURITY.md).
75
+
76
+ ## License
77
+
78
+ MIT
package/SECURITY.md ADDED
@@ -0,0 +1,5 @@
1
+ # Security
2
+
3
+ Report a vulnerability privately with GitHub's **Report a vulnerability** button on the Security tab. Don't open a public issue.
4
+
5
+ In scope: anything that breaks the threat model in [DESIGN.md](DESIGN.md), such as sign-in bypass, cross-site requests, DNS rebinding or script injection. Out of scope: its accepted risks and non-goals.
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.mjs';
3
+
4
+ main().catch(error => {
5
+ console.error(`pi-remote-web: ${error.code === 'EEXIST' ? 'Config already exists; refusing to overwrite it.' : error.message}`);
6
+ process.exitCode = 1;
7
+ });
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "pi-remote-web",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Use your Pi coding sessions from a phone browser over a private network",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/tboon0/pi-remote-web.git"
10
+ },
11
+ "keywords": ["pi", "pi-package", "remote", "mobile", "tailscale"],
12
+ "engines": {
13
+ "node": ">=22.19"
14
+ },
15
+ "bin": {
16
+ "pi-remote-web": "bin/pi-remote-web.mjs"
17
+ },
18
+ "files": ["bin", "src", "public", "README.md", "DESIGN.md", "CHANGELOG.md", "SECURITY.md", "LICENSE"],
19
+ "scripts": {
20
+ "start": "node bin/pi-remote-web.mjs",
21
+ "test": "node --test test/*.test.mjs",
22
+ "check": "node scripts/check.mjs"
23
+ }
24
+ }
package/public/app.js ADDED
@@ -0,0 +1,286 @@
1
+ 'use strict';
2
+
3
+ const $ = id => document.getElementById(id);
4
+ const unknown = 'This may have reached Pi. Check the chat before you send it again.';
5
+ let view = 'login', projectId, sessionId, changing = false, polling = false, atEnd = true;
6
+ let state = { projects: [], sessions: [] };
7
+ // The model list of the open project, and the model and thinking level chosen for new
8
+ // conversations. Kept in memory only: a reload goes back to Pi's defaults.
9
+ let catalog = null, pick = null;
10
+
11
+ function node(tag, text) {
12
+ const el = document.createElement(tag);
13
+ if (text !== undefined) el.textContent = text;
14
+ return el;
15
+ }
16
+ function button(label, click, className = '') {
17
+ const b = node('button', label); b.type = 'button'; b.onclick = click; b.className = className; return b;
18
+ }
19
+ // Text for screen readers only, so roles stay clear without visible headings.
20
+ function hidden(text) { const s = node('span', text); s.className = 'sr'; return s; }
21
+ function error(text = '') { $('error').textContent = text; $('error').hidden = !text; }
22
+ function show(next, title = 'Pi Remote') {
23
+ view = next;
24
+ for (const id of ['login', 'home', 'project', 'chat']) $(id).hidden = id !== view;
25
+ $('back').hidden = view !== 'project' && view !== 'chat';
26
+ $('logout').hidden = view !== 'home';
27
+ $('close').hidden = view !== 'chat';
28
+ $('subtitle').hidden = true;
29
+ $('title').textContent = title;
30
+ }
31
+ function controls() {
32
+ // The draft stays editable: a phone closes the keyboard when a focused field turns disabled or read-only.
33
+ for (const el of document.querySelectorAll('button,input,textarea:not(#draft),select')) el.disabled = changing;
34
+ const session = state.sessions.find(s => s.id === sessionId);
35
+ $('abort').disabled = changing || !session?.busy;
36
+ $('send').disabled = changing || !session || !$('draft').value.trim();
37
+ }
38
+
39
+ async function request(path, body) {
40
+ const response = await fetch(path, {
41
+ method: body === undefined ? 'GET' : 'POST', signal: AbortSignal.timeout(45000),
42
+ headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
43
+ });
44
+ const data = await response.json();
45
+ if (!response.ok) throw Object.assign(new Error(data.error), { status: response.status });
46
+ return data;
47
+ }
48
+ async function change(path, body, success = () => {}) {
49
+ if (changing) return;
50
+ changing = true; controls(); error();
51
+ try { success(await request(path, body)); }
52
+ catch (e) { error(!e.status || e.status === 504 ? unknown : e.message); }
53
+ finally { changing = false; controls(); }
54
+ }
55
+ function command(action, fields = {}, success) {
56
+ return change('/api/command', { sessionId, action, ...fields }, success);
57
+ }
58
+
59
+ // A button with a label line and a smaller detail line, such as a date or state.
60
+ function card(label, detail, click, className = '', detailClass = '') {
61
+ const b = button(undefined, click, `card ${className}`);
62
+ const meta = node('span', detail); meta.className = `meta ${detailClass}`;
63
+ b.append(node('span', label), meta);
64
+ return b;
65
+ }
66
+ function activity(s) {
67
+ return s.dialogs?.length ? 'Needs your answer' : s.status !== 'ready' ? s.status : s.busy ? 'Working' : 'Idle';
68
+ }
69
+ function home() {
70
+ show('home');
71
+ $('sessions').replaceChildren(...state.sessions.map(s =>
72
+ card(s.name, `${state.projects.find(p => p.id === s.projectId)?.name ?? ''} · ${activity(s)}`, () => chat(s.id), 'live',
73
+ s.dialogs?.length ? 'attention' : s.busy ? 'busy' : '')));
74
+ if (!state.sessions.length) $('sessions').textContent = 'No live conversations. Choose a project below.';
75
+ $('projects').replaceChildren(...state.projects.map(p => button(p.name, () => project(p))));
76
+ }
77
+ const key = m => m ? `${m.provider}\n${m.id}` : '';
78
+ // A model name and its thinking level as two spans, so a line breaks between them.
79
+ function modelLabel(el, name, thinking) {
80
+ const level = node('span', thinking && `Thinking: ${thinking}`); level.className = 'thinking';
81
+ el.replaceChildren(node('span', name), ' ', ...(thinking ? [level] : []));
82
+ }
83
+ const modelOf = p => catalog?.models?.find(m => key(m) === key(p));
84
+ // A button in a radio group, such as a model row or a thinking-level pill.
85
+ function radio(el, value, click) {
86
+ el.setAttribute('role', 'radio'); el.dataset.value = value; el.onclick = click; return el;
87
+ }
88
+ // Keep the thinking level if the model offers it, else Pi's default, else the model's first.
89
+ function choose(m, thinking) {
90
+ const levels = m.levels, fallback = catalog.defaults?.thinking;
91
+ pick = { provider: m.provider, id: m.id,
92
+ thinking: levels.includes(thinking) ? thinking : levels.includes(fallback) ? fallback : levels[0] };
93
+ renderSetup();
94
+ }
95
+ function openSetup(open) {
96
+ $('setup-panel').hidden = !open; $('setup-toggle').setAttribute('aria-expanded', String(open));
97
+ // Centre the chosen model in the list without scrolling the page.
98
+ const list = $('model-list'), row = list.querySelector('[aria-checked="true"]');
99
+ if (open && row) {
100
+ const l = list.getBoundingClientRect(), r = row.getBoundingClientRect();
101
+ list.scrollTop += r.top - l.top - (l.height - r.height) / 2;
102
+ }
103
+ }
104
+ function renderSetup() {
105
+ const m = modelOf(pick);
106
+ if (m) modelLabel($('setup-summary'), m.name, pick.thinking);
107
+ else $('setup-summary').textContent = catalog ? "Pi's default model" : 'Loading models…';
108
+ $('setup-note').textContent = catalog?.error ? `${catalog.error}. New conversations use Pi's defaults.` : 'Model for new conversations';
109
+ $('setup-toggle').querySelector('.change').hidden = !catalog?.models;
110
+ for (const row of $('model-list').children) row.setAttribute('aria-checked', String(row.dataset.value === key(m)));
111
+ if ($('thinking').dataset.model !== key(m)) {
112
+ $('thinking').replaceChildren(...(m?.levels ?? []).map(level =>
113
+ radio(button(level, undefined, 'pill'), level, () => choose(m, level))));
114
+ $('thinking').dataset.model = key(m);
115
+ }
116
+ for (const pill of $('thinking').children) pill.setAttribute('aria-checked', String(pill.dataset.value === pick?.thinking));
117
+ $('thinking-group').hidden = !m?.levels.length;
118
+ }
119
+ async function loadModels(p) {
120
+ catalog = null; openSetup(false); $('model-list').replaceChildren(); renderSetup();
121
+ try {
122
+ const list = await request(`/api/models?projectId=${encodeURIComponent(p.id)}`);
123
+ if (view !== 'project' || projectId !== p.id) return;
124
+ catalog = { projectId: p.id, models: list.models, defaults: list.defaults };
125
+ $('model-list').replaceChildren(...list.models.map(m => radio(card(m.name, m.provider, undefined, 'choice'), key(m), () => choose(m, pick?.thinking))));
126
+ const current = modelOf(pick) ? pick : list.defaults, m = modelOf(current);
127
+ pick = null;
128
+ if (m) choose(m, current.thinking);
129
+ controls();
130
+ } catch (e) {
131
+ if (view !== 'project' || projectId !== p.id) return;
132
+ catalog = { projectId: p.id, error: e.status ? e.message : 'Could not load models' };
133
+ }
134
+ renderSetup();
135
+ }
136
+ async function project(p) {
137
+ projectId = p.id; show('project', p.name);
138
+ void loadModels(p);
139
+ $('archives').textContent = 'Loading…';
140
+ try {
141
+ const { archives } = await request(`/api/archives?projectId=${encodeURIComponent(p.id)}`);
142
+ if (view !== 'project' || projectId !== p.id) return;
143
+ $('archives').replaceChildren(...archives.map(a => {
144
+ const date = new Date(a.modified);
145
+ const when = isNaN(date) ? '' : date.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
146
+ const label = a.name || a.firstMessage || 'Untitled session';
147
+ return card(label, when, () => {
148
+ if (confirm(`Resume "${label}"${when ? ` from ${when}` : ''}? Confirm this conversation is not open in another terminal.`)) start(a.archiveId);
149
+ });
150
+ }));
151
+ if (!archives.length) $('archives').textContent = 'No previous conversations.';
152
+ controls();
153
+ } catch (e) { error(e.status ? e.message : 'Could not load previous conversations'); }
154
+ }
155
+ // A new conversation starts with the chosen model; a resumed one keeps its own.
156
+ function start(archiveId) {
157
+ const m = !archiveId && catalog?.projectId === projectId && modelOf(pick);
158
+ const choice = m ? { provider: m.provider, model: m.id, thinking: pick.thinking } : {};
159
+ return change('/api/sessions', { projectId, archiveId, ...choice }, data => { chat(data.sessionId); void poll(); });
160
+ }
161
+ function chat(id) {
162
+ sessionId = id; $('draft').value = ''; atEnd = true; show('chat', 'Conversation');
163
+ renderChat(); controls();
164
+ }
165
+ function dialogForm(d) {
166
+ const form = node('div'); form.className = 'dialog';
167
+ form.append(node('h3', d.title || 'Pi needs your answer'));
168
+ if (d.message) form.append(node('p', d.message));
169
+ const buttons = node('div'); buttons.className = 'actions';
170
+ const answer = fields => command('answer', { dialogId: d.id, ...fields }, () => form.remove());
171
+ if (d.method === 'confirm') {
172
+ buttons.append(button('Yes', () => answer({ confirmed: true })), button('No', () => answer({ confirmed: false }), 'secondary'));
173
+ } else {
174
+ const input = node(d.method === 'select' ? 'select' : 'textarea');
175
+ if (d.method === 'select') for (const option of d.options) input.append(node('option', option));
176
+ else { input.value = d.prefill || ''; input.placeholder = d.placeholder || ''; }
177
+ input.setAttribute('aria-label', d.title || 'Your answer');
178
+ form.append(input);
179
+ buttons.append(button('Send answer', () => answer({ value: input.value })));
180
+ }
181
+ buttons.append(button('Cancel', () => answer({ cancelled: true }), 'secondary'));
182
+ form.append(buttons);
183
+ return form;
184
+ }
185
+ // Monospace block for a tool call or result, with a small visible tag such as "bash".
186
+ function toolBlock(role, tag, text) {
187
+ const pre = node('pre'); pre.className = 'tool';
188
+ const label = node('span', tag); label.className = 'tag';
189
+ pre.append(hidden(role), label, text);
190
+ return pre;
191
+ }
192
+ // Each user prompt is its own card. Pi's replies, tool calls and tool results up to the
193
+ // next prompt share one card. The server writes each tool call as a line: `[Tool: name] summary`.
194
+ function messageCards(messages) {
195
+ const cards = [];
196
+ let pi;
197
+ for (const m of messages) {
198
+ if (m.role === 'user') {
199
+ const article = node('article'); article.className = 'user';
200
+ article.append(hidden('You: '), node('p', m.text));
201
+ cards.push(article); pi = undefined; continue;
202
+ }
203
+ if (!pi) { pi = node('article'); pi.className = 'pi'; pi.append(hidden('Pi: ')); cards.push(pi); }
204
+ if (m.role === 'toolResult') { pi.append(toolBlock('Tool result: ', 'result', m.text)); continue; }
205
+ let text = [];
206
+ const flush = () => { if (text.length) pi.append(node('p', text.join('\n'))); text = []; };
207
+ for (const line of m.text.split('\n')) {
208
+ const tool = /^\[Tool: (.*?)\](?: (.*))?$/.exec(line);
209
+ if (!tool) { text.push(line); continue; }
210
+ flush(); pi.append(toolBlock('Tool call: ', tool[1] || 'tool', tool[2] || ''));
211
+ }
212
+ flush();
213
+ }
214
+ return cards;
215
+ }
216
+ function renderChat() {
217
+ const s = state.sessions.find(item => item.id === sessionId);
218
+ $('title').textContent = s?.name || 'Conversation';
219
+ // The server label is "name · Thinking: level", or just the name.
220
+ const [name, thinking] = (s?.model || '').split(' · Thinking: ');
221
+ modelLabel($('subtitle'), name, thinking); $('subtitle').hidden = !s?.model;
222
+ $('status').textContent = s ? activity(s) : 'Conversation unavailable';
223
+ $('status').className = s?.dialogs?.length ? 'attention' : s?.busy ? 'busy' : '';
224
+ $('messages').replaceChildren(...messageCards(s?.messages || []));
225
+ $('live').textContent = s?.live || '';
226
+ $('queued').replaceChildren(...(s?.queued || []).map(q => node('p', `${q.mode === 'steer' ? 'Steer' : 'Follow-up'} queued: ${q.text}`)));
227
+ // Leave inputs alone across polls so an answer in progress is not lost.
228
+ const signature = JSON.stringify([sessionId, s?.dialogs]);
229
+ if ($('dialogs').dataset.signature !== signature) {
230
+ $('dialogs').replaceChildren(...(s?.dialogs || []).map(dialogForm));
231
+ $('dialogs').dataset.signature = signature;
232
+ if (s?.dialogs?.length) atEnd = true;
233
+ }
234
+ if (atEnd) $('scroll').scrollTop = $('scroll').scrollHeight;
235
+ }
236
+ async function poll() {
237
+ if (document.hidden || polling) return;
238
+ polling = true;
239
+ try {
240
+ state = await request('/api/state');
241
+ if (view === 'login' || view === 'home') home();
242
+ if (view === 'chat') renderChat();
243
+ controls();
244
+ } catch (e) {
245
+ if (e.status === 401) {
246
+ if (view !== 'login') location.reload();
247
+ else show('login');
248
+ } else if (!$('error').textContent) error('Could not update the chat');
249
+ } finally { polling = false; }
250
+ }
251
+ $('login').onsubmit = async event => {
252
+ event.preventDefault(); error();
253
+ const credentials = { username: $('username').value, password: $('password').value };
254
+ $('password').value = '';
255
+ try { await request('/api/login', credentials); await poll(); }
256
+ catch (e) { error(e.status ? e.message : 'Could not sign in'); }
257
+ };
258
+ $('logout').onclick = async () => {
259
+ try { await request('/api/logout', {}); location.reload(); }
260
+ catch (e) { error(e.status ? e.message : 'Could not confirm sign-out'); }
261
+ };
262
+ $('back').onclick = home;
263
+ $('start').onclick = () => start();
264
+ $('setup-toggle').onclick = () => { if (catalog?.models) openSetup($('setup-panel').hidden); };
265
+ $('setup-done').onclick = () => { openSetup(false); $('setup-toggle').focus(); };
266
+ $('draft').oninput = controls;
267
+ // Tapping Send must not move focus off the draft, or the phone keyboard closes.
268
+ $('send').onmousedown = event => event.preventDefault();
269
+ $('composer').onsubmit = event => {
270
+ event.preventDefault();
271
+ const text = $('draft').value;
272
+ // Keep anything typed while the prompt was being sent, then show the end of the chat.
273
+ if (!$('send').disabled) command('prompt', { text, mode: $('mode').value }, () => {
274
+ const draft = $('draft').value;
275
+ if (draft.startsWith(text)) $('draft').value = draft.slice(text.length).trimStart();
276
+ atEnd = true; $('scroll').scrollTop = $('scroll').scrollHeight;
277
+ });
278
+ };
279
+ // Stay at the latest message when the chat area shrinks, such as when the keyboard opens.
280
+ $('scroll').onscroll = () => { const s = $('scroll'); atEnd = s.scrollHeight - s.scrollTop - s.clientHeight < 80; };
281
+ new ResizeObserver(() => { if (atEnd) $('scroll').scrollTop = $('scroll').scrollHeight; }).observe($('scroll'));
282
+ $('abort').onclick = () => command('abort');
283
+ $('close').onclick = () => { if (confirm('Close this conversation and stop its work?')) command('stop', {}, home); };
284
+ setInterval(poll, 1000);
285
+ document.addEventListener('visibilitychange', poll);
286
+ void poll();
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 192"><rect width="192" height="192" rx="40" fill="#11151c"/><path d="M44 58h104v18h-20v61c0 8 3 12 10 12h10v18h-14c-17 0-26-10-26-29V76H80v46c0 22-7 37-21 45l-12-15c10-7 13-17 13-33V76H44z" fill="#b0ccff"/></svg>
@@ -0,0 +1,63 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content">
6
+ <meta name="theme-color" content="#11151c">
7
+ <meta name="color-scheme" content="dark">
8
+ <title>Pi Remote</title>
9
+ <link rel="manifest" href="/manifest.webmanifest">
10
+ <link rel="icon" href="/icon.svg" type="image/svg+xml">
11
+ <link rel="stylesheet" href="/style.css">
12
+ <script src="/app.js" defer></script>
13
+ </head>
14
+ <body>
15
+ <header class="appbar">
16
+ <button id="back" class="secondary icon" aria-label="Back" hidden><svg viewBox="0 0 24 24" width="24" height="24" aria-hidden="true"><path d="M15 5l-7 7 7 7" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg></button>
17
+ <div class="titles"><h1 id="title">Pi Remote</h1><p id="subtitle" hidden></p></div>
18
+ <button id="logout" class="secondary" hidden>Sign out</button>
19
+ <button id="close" class="danger" aria-label="Close conversation" hidden>Close</button>
20
+ </header>
21
+ <p id="error" role="alert" hidden></p>
22
+ <main>
23
+ <form id="login" hidden>
24
+ <h2>Sign in</h2>
25
+ <label>Username<input id="username" autocomplete="username" autocapitalize="none" required></label>
26
+ <label>Password<input id="password" type="password" autocomplete="current-password" required></label>
27
+ <button>Sign in</button>
28
+ </form>
29
+ <section id="home" hidden>
30
+ <p class="notice">Remote prompts have your full Pi tool permissions.</p>
31
+ <h2>Live conversations</h2><div id="sessions"></div>
32
+ <h2>Projects</h2><div id="projects"></div>
33
+ </section>
34
+ <section id="project" hidden>
35
+ <div id="setup">
36
+ <button id="setup-toggle" type="button" class="card" aria-expanded="false" aria-controls="setup-panel">
37
+ <span class="setup-text"><span id="setup-note" class="meta">Model for new conversations</span><span id="setup-summary"></span></span>
38
+ <span class="change" aria-hidden="true">Change</span>
39
+ </button>
40
+ <div id="setup-panel" hidden>
41
+ <h3 id="model-heading">Model</h3><div id="model-list" role="radiogroup" aria-labelledby="model-heading"></div>
42
+ <div id="thinking-group"><h3 id="thinking-heading">Thinking</h3><div id="thinking" role="radiogroup" aria-labelledby="thinking-heading"></div></div>
43
+ <button id="setup-done" type="button">Done</button>
44
+ </div>
45
+ </div>
46
+ <button id="start">New conversation</button>
47
+ <h2>Previous conversations</h2><div id="archives"></div>
48
+ </section>
49
+ <section id="chat" hidden>
50
+ <div id="scroll">
51
+ <div id="messages"></div><div id="live"></div>
52
+ <div id="queued"></div><div id="dialogs"></div>
53
+ </div>
54
+ <form id="composer">
55
+ <div class="composer-head"><label for="draft">Message Pi</label><p id="status" role="status"></p></div>
56
+ <textarea id="draft" maxlength="16000" rows="2"></textarea>
57
+ <div class="actions"><select id="mode" aria-label="When Pi is busy"><option value="steer">If busy: steer</option><option value="followUp">If busy: follow-up</option></select>
58
+ <button id="abort" type="button" class="secondary">Stop</button><button id="send">Send</button></div>
59
+ </form>
60
+ </section>
61
+ </main>
62
+ </body>
63
+ </html>