ereniko commited on
Commit
5d3283b
·
unverified ·
1 Parent(s): 338fca4

v0.8.2: Hugging Face sign-in from the embedded Space page, sturdier callback

Browse files
Files changed (7) hide show
  1. README.md +1 -1
  2. css/app.css +2 -0
  3. js/config.js +1 -1
  4. js/hf-auth.js +76 -31
  5. js/model-manager.js +12 -3
  6. js/oauth-callback.js +2 -2
  7. sw.js +1 -1
README.md CHANGED
@@ -69,7 +69,7 @@ To make the local model fit on more devices, the weights are kept on disk and re
69
 
70
  ## API models
71
 
72
- **Fastest start: Sign in with Hugging Face.** In the Model Manager's API tab, press **Sign in with Hugging Face**, approve in the pop-up, and the agent starts using `openai/gpt-oss-120b` through [Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers), billed to your Hugging Face account. There is no key to copy: the sign-in (OAuth with PKCE, entirely in the browser) only grants permission to run inference, and the session refreshes itself. You can pick any other tool-capable model from the list, or use an access token instead.
73
 
74
  Any number of API models can be saved; use **Add API model** in the Model Manager. Pick a provider, paste your key, and choose a model ID. **Load list** fetches the provider's models to choose from, and **Test** sends a tiny request to check everything works.
75
 
 
69
 
70
  ## API models
71
 
72
+ **Fastest start: Sign in with Hugging Face.** In the Model Manager's API tab, press **Sign in with Hugging Face**, approve in the pop-up, and the agent starts using `openai/gpt-oss-120b` through [Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers), billed to your Hugging Face account. There is no key to copy: the sign-in (OAuth with PKCE, entirely in the browser) only grants permission to run inference, and the session refreshes itself. You can pick any other tool-capable model from the list, or use an access token instead. Sign-in works in LocalWebAgent's own tab (`https://<owner>-localwebagent.static.hf.space`); inside the Space page on huggingface.co the browser keeps the app's storage separate, so the app offers to open its own tab for signing in (access tokens work in both).
73
 
74
  Any number of API models can be saved; use **Add API model** in the Model Manager. Pick a provider, paste your key, and choose a model ID. **Load list** fetches the provider's models to choose from, and **Test** sends a tiny request to check everything works.
75
 
css/app.css CHANGED
@@ -639,6 +639,8 @@ button.brand-model { display: inline-flex; align-items: center; gap: 7px; }
639
  .hf-quick-title { font-weight: 650; font-size: 14.5px; }
640
  .hf-quick-sub { font-size: 12.5px; color: var(--text-2); line-height: 1.5; margin-top: 2px; }
641
  .hf-quick-actions { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; }
 
 
642
  .hf-wait { display: inline-flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--text-2); white-space: nowrap; }
643
  .hf-wait.big { height: 42px; }
644
  .hf-wait .linkish { margin-left: 6px; }
 
639
  .hf-quick-title { font-weight: 650; font-size: 14.5px; }
640
  .hf-quick-sub { font-size: 12.5px; color: var(--text-2); line-height: 1.5; margin-top: 2px; }
641
  .hf-quick-actions { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; }
642
+ a.hf-btn { text-decoration: none; }
643
+ .embed-note { margin: 8px 0 0; color: var(--text-2); }
644
  .hf-wait { display: inline-flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--text-2); white-space: nowrap; }
645
  .hf-wait.big { height: 42px; }
646
  .hf-wait .linkish { margin-left: 6px; }
js/config.js CHANGED
@@ -1,5 +1,5 @@
1
  // Central configuration. Everything that pins a version or a location lives here.
2
- export const APP_VERSION = "0.8.1";
3
 
4
  // --- Local language models (loaded from the Hugging Face Hub, cached in Cache Storage) ---
5
  // Each runs on WebGPU through transformers.js. `chunks` is how many external weight files
 
1
  // Central configuration. Everything that pins a version or a location lives here.
2
+ export const APP_VERSION = "0.8.2";
3
 
4
  // --- Local language models (loaded from the Hugging Face Hub, cached in Cache Storage) ---
5
  // Each runs on WebGPU through transformers.js. `chunks` is how many external weight files
js/hf-auth.js CHANGED
@@ -18,6 +18,17 @@ export function hfClientId() {
18
  return HF_OAUTH_CLIENT_ID || globalThis.huggingface?.variables?.OAUTH_CLIENT_ID || "";
19
  }
20
  export const hfSignInAvailable = () => !!hfClientId();
 
 
 
 
 
 
 
 
 
 
 
21
  export const hfRedirectUri = () => new URL("oauth.html", document.baseURI).href;
22
 
23
  const b64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
@@ -55,6 +66,23 @@ const toSession = (t, user, prev = {}) => ({
55
 
56
  let cancelPending = null;
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  /**
59
  * Opens the Hugging Face sign-in popup. Resolves with a session
60
  * { accessToken, refreshToken, expiresAt, user: { name, username, avatarUrl } }.
@@ -64,13 +92,14 @@ export async function signInWithHuggingFace() {
64
  const clientId = hfClientId();
65
  if (!clientId) throw new Error("Sign in with Hugging Face isn't set up for this app yet. Use an access token instead.");
66
  cancelPending?.();
 
67
  const verifier = random(48);
68
  const challenge = b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
69
  const state = random(16);
70
- localStorage.setItem(PENDING, JSON.stringify({ state, verifier, clientId, redirectUri: hfRedirectUri(), at: Date.now() }));
71
  const url = new URL(`${HF}/oauth/authorize`);
72
  for (const [k, v] of Object.entries({
73
- client_id: clientId, redirect_uri: hfRedirectUri(), response_type: "code", scope: HF_SCOPES,
74
  state, code_challenge: challenge, code_challenge_method: "S256",
75
  })) url.searchParams.set(k, v);
76
 
@@ -80,19 +109,37 @@ export async function signInWithHuggingFace() {
80
  if (!popup) throw new Error("Your browser blocked the sign-in window. Allow pop-ups for this site and try again.");
81
 
82
  return new Promise((resolve, reject) => {
83
- const ch = new BroadcastChannel(CHANNEL);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  const timer = setTimeout(() => finish(reject, new Error("Sign-in timed out.")), 10 * 60 * 1000);
85
- function finish(fn, value) {
 
 
 
86
  clearTimeout(timer);
87
- ch.close();
88
  cancelPending = null;
 
89
  fn(value);
90
  }
91
- ch.onmessage = ({ data }) => {
92
- if (data?.state !== state) return;
93
- if (data.error) finish(reject, new Error(data.error));
94
- else finish(resolve, data.session);
95
- };
96
  cancelPending = () => finish(reject, Object.assign(new Error("Sign-in cancelled."), { cancelled: true }));
97
  });
98
  }
@@ -100,30 +147,28 @@ export async function signInWithHuggingFace() {
100
  /** Stops waiting for a sign-in started with signInWithHuggingFace. */
101
  export const cancelSignIn = () => cancelPending?.();
102
 
103
- /** Runs in oauth.html: exchanges the code from the redirect and hands the session to the app. */
104
- export async function completeSignIn() {
 
 
 
105
  const q = new URLSearchParams(location.search);
106
- const ch = new BroadcastChannel(CHANNEL);
107
- let pending = null;
108
- try { pending = JSON.parse(localStorage.getItem(PENDING) || "null"); } catch {}
109
  const state = q.get("state");
110
- try {
111
- if (q.get("error")) throw new Error(q.get("error_description") || q.get("error"));
112
- if (!pending || !state || pending.state !== state) throw new Error("This sign-in link has expired. Start again from LocalWebAgent.");
113
- const t = await tokenRequest({
114
- grant_type: "authorization_code", code: q.get("code"), redirect_uri: pending.redirectUri,
115
- client_id: pending.clientId, code_verifier: pending.verifier,
 
116
  });
117
- const session = toSession(t, await userInfo(t.access_token), { clientId: pending.clientId });
118
- ch.postMessage({ state, session });
119
- return session;
120
- } catch (err) {
121
- ch.postMessage({ state, error: err.message });
122
- throw err;
123
- } finally {
124
- localStorage.removeItem(PENDING);
125
- setTimeout(() => ch.close(), 1000);
126
- }
127
  }
128
 
129
  // ---------- stored sessions (one per saved API model that uses sign-in) ----------
 
18
  return HF_OAUTH_CLIENT_ID || globalThis.huggingface?.variables?.OAUTH_CLIENT_ID || "";
19
  }
20
  export const hfSignInAvailable = () => !!hfClientId();
21
+
22
+ /**
23
+ * True inside an iframe, e.g. the Space page on huggingface.co. There the browser keeps
24
+ * this app's storage separate from the same app in its own tab (storage partitioning),
25
+ * and isolation cuts the popup's link back, so the sign-in popup can't hand its result to
26
+ * the embedded app. Sign-in is then offered in the app's own tab instead.
27
+ */
28
+ export function embedded() {
29
+ try { return window.top !== window.self; } catch { return true; }
30
+ }
31
+ export const standaloneUrl = () => new URL("./", document.baseURI).href;
32
  export const hfRedirectUri = () => new URL("oauth.html", document.baseURI).href;
33
 
34
  const b64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
 
66
 
67
  let cancelPending = null;
68
 
69
+ // Messages between the app and the oauth.html popup go over a BroadcastChannel, with
70
+ // localStorage "storage" events as a backup (both same-origin only). The popup only
71
+ // forwards the code; the app, which holds the PKCE verifier in memory, does the token
72
+ // exchange. So a callback page that loads twice, or late, can't break the sign-in.
73
+ const MSG_KEY = "lwa-hf-oauth-msg";
74
+ function postMsg(msg) {
75
+ try { const ch = new BroadcastChannel(CHANNEL); ch.postMessage(msg); ch.close(); } catch {}
76
+ try { localStorage.setItem(MSG_KEY, JSON.stringify({ ...msg, nonce: Math.random() })); } catch {}
77
+ }
78
+ function onMsg(handler) {
79
+ let ch = null;
80
+ try { ch = new BroadcastChannel(CHANNEL); ch.onmessage = ({ data }) => handler(data); } catch {}
81
+ const onStorage = (e) => { if (e.key === MSG_KEY && e.newValue) { try { handler(JSON.parse(e.newValue)); } catch {} } };
82
+ addEventListener("storage", onStorage);
83
+ return () => { ch?.close(); removeEventListener("storage", onStorage); };
84
+ }
85
+
86
  /**
87
  * Opens the Hugging Face sign-in popup. Resolves with a session
88
  * { accessToken, refreshToken, expiresAt, user: { name, username, avatarUrl } }.
 
92
  const clientId = hfClientId();
93
  if (!clientId) throw new Error("Sign in with Hugging Face isn't set up for this app yet. Use an access token instead.");
94
  cancelPending?.();
95
+ try { localStorage.removeItem(PENDING); } catch {} // from older versions
96
  const verifier = random(48);
97
  const challenge = b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))));
98
  const state = random(16);
99
+ const redirectUri = hfRedirectUri();
100
  const url = new URL(`${HF}/oauth/authorize`);
101
  for (const [k, v] of Object.entries({
102
+ client_id: clientId, redirect_uri: redirectUri, response_type: "code", scope: HF_SCOPES,
103
  state, code_challenge: challenge, code_challenge_method: "S256",
104
  })) url.searchParams.set(k, v);
105
 
 
109
  if (!popup) throw new Error("Your browser blocked the sign-in window. Allow pop-ups for this site and try again.");
110
 
111
  return new Promise((resolve, reject) => {
112
+ let result = null; // the finished session, kept to answer repeated callbacks
113
+ let exchanging = false;
114
+ const stop = onMsg(async (m) => {
115
+ if (m?.type !== "code" || m.state !== state) return;
116
+ if (result) return postMsg({ type: "ack", state, ok: true, name: result.user?.name ?? "" });
117
+ if (exchanging) return; // the same code again while we're already using it
118
+ if (m.error) {
119
+ postMsg({ type: "ack", state, ok: false, error: m.error });
120
+ return finish(reject, new Error(m.error));
121
+ }
122
+ exchanging = true;
123
+ try {
124
+ const t = await tokenRequest({ grant_type: "authorization_code", code: m.code, redirect_uri: redirectUri, client_id: clientId, code_verifier: verifier });
125
+ result = toSession(t, await userInfo(t.access_token), { clientId });
126
+ postMsg({ type: "ack", state, ok: true, name: result.user?.name ?? "" });
127
+ finish(resolve, result, 15_000); // keep answering a reloaded callback for a while
128
+ } catch (err) {
129
+ postMsg({ type: "ack", state, ok: false, error: err.message });
130
+ finish(reject, err);
131
+ }
132
+ });
133
  const timer = setTimeout(() => finish(reject, new Error("Sign-in timed out.")), 10 * 60 * 1000);
134
+ let settled = false;
135
+ function finish(fn, value, linger = 0) {
136
+ if (settled) return;
137
+ settled = true;
138
  clearTimeout(timer);
 
139
  cancelPending = null;
140
+ setTimeout(stop, linger);
141
  fn(value);
142
  }
 
 
 
 
 
143
  cancelPending = () => finish(reject, Object.assign(new Error("Sign-in cancelled."), { cancelled: true }));
144
  });
145
  }
 
147
  /** Stops waiting for a sign-in started with signInWithHuggingFace. */
148
  export const cancelSignIn = () => cancelPending?.();
149
 
150
+ /**
151
+ * Runs in oauth.html: forwards the code (or error) from the redirect to the app and waits
152
+ * for its answer. Resolves with { ok, name } or rejects with the reason.
153
+ */
154
+ export function completeSignIn() {
155
  const q = new URLSearchParams(location.search);
 
 
 
156
  const state = q.get("state");
157
+ const msg = { type: "code", state, code: q.get("code"), error: q.get("error") ? (q.get("error_description") || q.get("error")) : null };
158
+ if (!state || (!msg.code && !msg.error)) return Promise.reject(new Error("This page should be opened by Hugging Face after signing in. Start again from LocalWebAgent."));
159
+ return new Promise((resolve, reject) => {
160
+ const stop = onMsg((m) => {
161
+ if (m?.type !== "ack" || m.state !== state) return;
162
+ clearInterval(resend); clearTimeout(giveUp); stop();
163
+ m.ok ? resolve(m) : reject(new Error(m.error || "Sign-in failed."));
164
  });
165
+ postMsg(msg);
166
+ const resend = setInterval(() => postMsg(msg), 1000);
167
+ const giveUp = setTimeout(() => {
168
+ clearInterval(resend); stop();
169
+ reject(new Error("LocalWebAgent didn't answer. Keep its tab open, then press Sign in with Hugging Face again."));
170
+ }, 20_000);
171
+ });
 
 
 
172
  }
173
 
174
  // ---------- stored sessions (one per saved API model that uses sign-in) ----------
js/model-manager.js CHANGED
@@ -2,7 +2,7 @@
2
  // edit, test and switch between any number of API models.
3
  import { LOCAL_MODELS, effectiveModel, modelRunsHere } from "./config.js";
4
  import { PARTIAL_CACHE } from "./fast-download.js";
5
- import { hfSignInAvailable, signInWithHuggingFace, cancelSignIn, loadSession, saveSession, deleteSession, sessionExpired } from "./hf-auth.js";
6
  import { API_PRESETS, findPreset, RemoteLLM, loadApiKey, saveApiKey, deleteApiKey, apiKeyRemembered } from "./remote-llm.js";
7
 
8
  const AVATAR_BASE = new URL("../vendor/avatars/", import.meta.url).href;
@@ -193,7 +193,8 @@ export function createModelManager(deps) {
193
  avatarTile("huggingface", "lg"),
194
  h("div", { class: "hf-quick-text" },
195
  h("div", { class: "hf-quick-title" }, "Start right away with Hugging Face"),
196
- h("div", { class: "hf-quick-sub" }, `Sign in and LocalWebAgent uses ${p.defaultModel} through Hugging Face Inference Providers. No API key to copy; usage counts against your Hugging Face account.`)),
 
197
  h("div", { class: "hf-quick-actions" },
198
  quickBusy
199
  ? [h("span", { class: "hf-wait" }, h("span", { class: "spinner" }), "Waiting for Hugging Face…"),
@@ -202,8 +203,16 @@ export function createModelManager(deps) {
202
  }
203
 
204
  function hfButton(onclick, label = "Sign in with Hugging Face") {
 
 
 
 
 
205
  return h("button", { class: "hf-btn", type: "button", onclick }, avatarTile("huggingface", "xs"), h("span", {}, label));
206
  }
 
 
 
207
 
208
  async function quickSignIn() {
209
  quickBusy = true;
@@ -436,7 +445,7 @@ export function createModelManager(deps) {
436
  ? h("div", { class: "hf-wait big" }, h("span", { class: "spinner" }), "Waiting for Hugging Face…",
437
  h("button", { class: "linkish plain", type: "button", onclick: () => cancelSignIn() }, "Cancel"))
438
  : hfButton(() => editorSignIn()),
439
- h("p", { class: "field-hint" }, ended ? "Your sign-in has ended. Sign in again to keep using this model." : "No key to copy: LocalWebAgent only gets permission to run inference on your account, billed to your Hugging Face account."),
440
  h("button", { class: "linkish plain", type: "button", onclick: () => { useToken = true; syncPreset(false); $e("ae-key").focus(); } }, "Use an access token instead"));
441
  }
442
 
 
2
  // edit, test and switch between any number of API models.
3
  import { LOCAL_MODELS, effectiveModel, modelRunsHere } from "./config.js";
4
  import { PARTIAL_CACHE } from "./fast-download.js";
5
+ import { hfSignInAvailable, signInWithHuggingFace, cancelSignIn, loadSession, saveSession, deleteSession, sessionExpired, embedded, standaloneUrl } from "./hf-auth.js";
6
  import { API_PRESETS, findPreset, RemoteLLM, loadApiKey, saveApiKey, deleteApiKey, apiKeyRemembered } from "./remote-llm.js";
7
 
8
  const AVATAR_BASE = new URL("../vendor/avatars/", import.meta.url).href;
 
193
  avatarTile("huggingface", "lg"),
194
  h("div", { class: "hf-quick-text" },
195
  h("div", { class: "hf-quick-title" }, "Start right away with Hugging Face"),
196
+ h("div", { class: "hf-quick-sub" }, `Sign in and LocalWebAgent uses ${p.defaultModel} through Hugging Face Inference Providers. No API key to copy; usage counts against your Hugging Face account.`),
197
+ embedNote()),
198
  h("div", { class: "hf-quick-actions" },
199
  quickBusy
200
  ? [h("span", { class: "hf-wait" }, h("span", { class: "spinner" }), "Waiting for Hugging Face…"),
 
203
  }
204
 
205
  function hfButton(onclick, label = "Sign in with Hugging Face") {
206
+ // Embedded in the Space page, the popup can't hand its result back: sign in in the app's own tab.
207
+ if (embedded()) {
208
+ return h("a", { class: "hf-btn", href: standaloneUrl(), target: "_blank", rel: "noopener" },
209
+ avatarTile("huggingface", "xs"), h("span", {}, "Open LocalWebAgent to sign in"));
210
+ }
211
  return h("button", { class: "hf-btn", type: "button", onclick }, avatarTile("huggingface", "xs"), h("span", {}, label));
212
  }
213
+ const embedNote = () => embedded()
214
+ ? h("p", { class: "field-hint embed-note" }, "You're using LocalWebAgent inside the Space page. There, the browser keeps its storage separate, so Hugging Face sign-in has to happen in LocalWebAgent's own tab. Models, keys and Linux files in this embedded view are also separate from that tab. An access token works here too.")
215
+ : null;
216
 
217
  async function quickSignIn() {
218
  quickBusy = true;
 
445
  ? h("div", { class: "hf-wait big" }, h("span", { class: "spinner" }), "Waiting for Hugging Face…",
446
  h("button", { class: "linkish plain", type: "button", onclick: () => cancelSignIn() }, "Cancel"))
447
  : hfButton(() => editorSignIn()),
448
+ embedded() ? embedNote() : h("p", { class: "field-hint" }, ended ? "Your sign-in has ended. Sign in again to keep using this model." : "No key to copy: LocalWebAgent only gets permission to run inference on your account, billed to your Hugging Face account."),
449
  h("button", { class: "linkish plain", type: "button", onclick: () => { useToken = true; syncPreset(false); $e("ae-key").focus(); } }, "Use an access token instead"));
450
  }
451
 
js/oauth-callback.js CHANGED
@@ -4,8 +4,8 @@ import { completeSignIn } from "./hf-auth.js";
4
  const title = document.getElementById("title");
5
  const msg = document.getElementById("msg");
6
  try {
7
- const s = await completeSignIn();
8
- title.textContent = `Signed in${s.user?.name ? ` as ${s.user.name}` : ""}`;
9
  title.className = "ok";
10
  msg.textContent = "You can close this window and go back to LocalWebAgent.";
11
  setTimeout(() => window.close(), 700);
 
4
  const title = document.getElementById("title");
5
  const msg = document.getElementById("msg");
6
  try {
7
+ const r = await completeSignIn();
8
+ title.textContent = `Signed in${r.name ? ` as ${r.name}` : ""}`;
9
  title.className = "ok";
10
  msg.textContent = "You can close this window and go back to LocalWebAgent.";
11
  setTimeout(() => window.close(), 700);
sw.js CHANGED
@@ -6,7 +6,7 @@
6
  // (__vm__/disk.ext2), backed by the chunks the setup screen stored in Cache Storage.
7
  // 4. Adds the cross-origin isolation headers (COOP/COEP) that SharedArrayBuffer,
8
  // CheerpX and multi-threaded WASM need, even when a host forgets to send them.
9
- const SHELL_VERSION = "lwa-shell-0.8.1";
10
  const CX_ORIGIN = "https://cxrtnc.leaningtech.com";
11
  const CX_CACHE_PREFIX = "lwa-cheerpx-";
12
  const DISK_CACHE = "lwa-disk";
 
6
  // (__vm__/disk.ext2), backed by the chunks the setup screen stored in Cache Storage.
7
  // 4. Adds the cross-origin isolation headers (COOP/COEP) that SharedArrayBuffer,
8
  // CheerpX and multi-threaded WASM need, even when a host forgets to send them.
9
+ const SHELL_VERSION = "lwa-shell-0.8.2";
10
  const CX_ORIGIN = "https://cxrtnc.leaningtech.com";
11
  const CX_CACHE_PREFIX = "lwa-cheerpx-";
12
  const DISK_CACHE = "lwa-disk";