pinokiod 8.3.9 → 8.3.11

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.
@@ -3,6 +3,7 @@ const path = require('path')
3
3
  const { glob, sync, hasMagic } = require('glob-gitignore')
4
4
  const marked = require('marked')
5
5
  const matter = require('gray-matter');
6
+ const RequestFile = require('./request_file')
6
7
  class Proto {
7
8
  constructor(kernel) {
8
9
  this.kernel = kernel
@@ -124,6 +125,12 @@ class Proto {
124
125
  let mod_path = this.kernel.path("prototype/system", projectType, startType)
125
126
  let mod = await this.kernel.require(mod_path)
126
127
  let response = await mod(payload, ondata, this.kernel)
128
+ // A new app whose agent is started with the user's words: the words are in
129
+ // SPEC.md, and the address carries the line that points to it instead
130
+ // (kernel/request_file.js, spec/requirements/request-files.md).
131
+ if (response && typeof response.success === "string") {
132
+ response.success = await RequestFile.pointAddressToSpec(response.success, payload.cwd)
133
+ }
127
134
 
128
135
  if (projectType === 'dns') {
129
136
  try {
@@ -0,0 +1,53 @@
1
+ "use strict"
2
+
3
+ // How the text of a request reaches an agent: the request is in a file inside
4
+ // the folder the agent starts in, and the plugin is started with one line that
5
+ // points to the file. spec/requirements/request-files.md
6
+
7
+ const fs = require("fs")
8
+ const path = require("path")
9
+
10
+ const FOLDER = [".pinokio-temp", "requests"]
11
+ const SPEC = "SPEC.md"
12
+
13
+ // The request line. `file` is relative to the folder the agent starts in, with
14
+ // `/` on every system.
15
+ const line = (file) => `My message is in ${file}. Read it and respond as if I had typed it here.`
16
+
17
+ // An Ask: writes the request into `cwd` and gives back the request line.
18
+ const save = async (cwd, id, text) => {
19
+ const dir = path.resolve(cwd, ...FOLDER)
20
+ await fs.promises.mkdir(dir, { recursive: true })
21
+ await fs.promises.writeFile(path.resolve(dir, `${id}.md`), `${text}\n`, "utf8")
22
+ return line([...FOLDER, `${id}.md`].join("/"))
23
+ }
24
+
25
+ // Create app and Create plugin: the new folder already holds the user's words as
26
+ // SPEC.md. Gives back the request line for it, or null when SPEC.md is not there
27
+ // or holds something else.
28
+ const forSpec = async (cwd, words) => {
29
+ const asked = typeof words === "string" ? words.trim() : ""
30
+ if (!asked) return null
31
+ const saved = await fs.promises.readFile(path.resolve(cwd, SPEC), "utf8").catch(() => null)
32
+ return saved !== null && saved.trim() === asked ? line(SPEC) : null
33
+ }
34
+
35
+ // The same for a start address that carries the words as `prompt`
36
+ // (`/p/<app>/dev?plugin=...&prompt=...`): the address with the request line in
37
+ // their place. An address without words, or without a matching SPEC.md, is
38
+ // given back as it is.
39
+ const pointAddressToSpec = async (address, cwd) => {
40
+ if (typeof address !== "string" || !address) return address
41
+ let url
42
+ try {
43
+ url = new URL(address, "http://localhost")
44
+ } catch (_) {
45
+ return address
46
+ }
47
+ const requestLine = await forSpec(cwd, url.searchParams.get("prompt"))
48
+ if (!requestLine) return address
49
+ url.searchParams.set("prompt", requestLine)
50
+ return `${url.pathname}${url.search}${url.hash}`
51
+ }
52
+
53
+ module.exports = { line, save, forSpec, pointAddressToSpec }
@@ -58,6 +58,22 @@ class ShellStateSync {
58
58
  const line = this.tail.replaceAll(/[\r\n]/g, "")
59
59
  return terminationPromptRe.test(line)
60
60
  }
61
+ // The serialized state restores which mouse events a program asked for
62
+ // (?1000h / ?1002h / ?1003h) but not how it asked for them to be written
63
+ // (?1006h SGR, ?1016h SGR pixels). A page that attaches to a running program
64
+ // from this state would then report the mouse in the old byte format, which
65
+ // the program is not reading, so the wheel and a finger drag would do nothing
66
+ // in a full-screen program such as an agent's TUI. The format the program
67
+ // chose is added back here. It is read from the terminal's mouse service,
68
+ // which is not public API: test/terminal-mouse-input.test.js fails if a
69
+ // library upgrade moves it.
70
+ mouseEncodingMode() {
71
+ const service = this.shell.vt._core.coreMouseService
72
+ const encoding = service ? service.activeEncoding : ""
73
+ if (encoding === "SGR") return "\x1b[?1006h"
74
+ if (encoding === "SGR_PIXELS") return "\x1b[?1016h"
75
+ return ""
76
+ }
61
77
  refresh(force = false) {
62
78
  const now = Date.now()
63
79
  const shouldRefresh = force ||
@@ -65,7 +81,7 @@ class ShellStateSync {
65
81
  !this.cachedBuf ||
66
82
  (now - this.lastStateSyncAt >= this.stateInterval)
67
83
  if (shouldRefresh) {
68
- this.cachedBuf = this.shell.vts.serialize()
84
+ this.cachedBuf = this.shell.vts.serialize() + this.mouseEncodingMode()
69
85
  this.cachedCleaned = this.shell.stripAnsi(this.cachedBuf)
70
86
  this.shell.state = this.cachedCleaned
71
87
  this.lastStateSyncAt = now
package/kernel/shells.js CHANGED
@@ -771,6 +771,11 @@ class Shells {
771
771
  } else {
772
772
  session.emit(payload)
773
773
  }
774
+ } else if (params.binary) {
775
+ // From the terminal's binary channel: one character per byte (old-format
776
+ // mouse reports). Written as bytes, because as text a value above 127
777
+ // would reach the program as two bytes.
778
+ session.emit(Buffer.from(String(params.emit), "binary"))
774
779
  } else {
775
780
  session.emit(params.emit)
776
781
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pinokiod",
3
- "version": "8.3.9",
3
+ "version": "8.3.11",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/server/index.js CHANGED
@@ -85,6 +85,7 @@ const Setup = require("../kernel/bin/setup")
85
85
  const { createTerminalSessionHelpers } = require("./lib/terminal_session_helpers")
86
86
  const { createLauncherInstructionBootstrap } = require("./lib/launcher_instruction_bootstrap")
87
87
  const { createBrain } = require("./lib/brain")
88
+ const RequestFile = require("../kernel/request_file")
88
89
  const { createTerminalGitResetHandler } = require("./lib/terminal_git_reset")
89
90
  const { createDesktopEventRouter } = require("./lib/desktop_event_router")
90
91
  const { deletePluginFolder } = require("./lib/plugin_delete")
@@ -9606,7 +9607,10 @@ class Server {
9606
9607
  params.set("cwd", targetPath)
9607
9608
  params.set("chrome", "full")
9608
9609
  if (prompt) {
9609
- params.set("prompt", prompt)
9610
+ // Create plugin: the words are in SPEC.md, and the agent is started with
9611
+ // the line that points to it (spec/requirements/request-files.md).
9612
+ const requestLine = normalizedType === "create_plugin" ? await RequestFile.forSpec(targetPath, prompt) : null
9613
+ params.set("prompt", requestLine || prompt)
9610
9614
  }
9611
9615
 
9612
9616
  return {
@@ -7,6 +7,7 @@
7
7
  // me/preferences.md which app the user wants for which kind of task
8
8
  // me/log.md one line per Ask
9
9
  // me/files/<id>/ the files given to, or made by, one Ask
10
+ // .pinokio-temp/requests/<id>.md one Ask's request (kernel/request_file.js)
10
11
  //
11
12
  // What agents learn about an app is not kept here but in the app's own folder:
12
13
  //
@@ -17,13 +18,15 @@
17
18
  // app's skill is, writes the instruction files and adds a log line. It only
18
19
  // rewrites instruction files it wrote itself, and none of this bookkeeping can
19
20
  // stop an Ask. An Ask from an app's page runs in the app's own folder, so there
20
- // the place of the app's skill and the output folder are added to the request.
21
+ // the place of the app's skill and the output folder are added to the request,
22
+ // which is written into that folder's .pinokio-temp/requests.
21
23
 
22
24
  const fs = require("fs")
23
25
  const path = require("path")
24
26
  const crypto = require("crypto")
25
27
  const git = require("isomorphic-git")
26
28
  const ManagedSkills = require("../../kernel/managed_skills")
29
+ const RequestFile = require("../../kernel/request_file")
27
30
 
28
31
  const LOG_PROMPT_LENGTH = 200
29
32
  const BRAIN_HEADING = "# Pinokio Brain"
@@ -202,8 +205,12 @@ const createBrain = ({ kernel, copyUploads, pluginHref }) => {
202
205
  request.push(`Attached files:\n${copied.map((name) => `- me/files/${id}/${name}`).join("\n")}`)
203
206
  }
204
207
  }
208
+ // The agent is started with one line that points to the request, which is
209
+ // in a file in this folder (spec/requirements/request-files.md).
210
+ let requestLine = ""
205
211
  if (request.length > 0) {
206
212
  request.push(`Output folder: me/files/${id}/`)
213
+ requestLine = await RequestFile.save(dir, id, request.join("\n\n"))
207
214
  }
208
215
 
209
216
  await attempt("instructions", () => writeInstructions(dir))
@@ -213,8 +220,8 @@ const createBrain = ({ kernel, copyUploads, pluginHref }) => {
213
220
  params.set("cwd", dir)
214
221
  params.set("chrome", "full")
215
222
  params.set("session", id)
216
- if (request.length > 0) {
217
- params.set("prompt", request.join("\n\n"))
223
+ if (requestLine) {
224
+ params.set("prompt", requestLine)
218
225
  }
219
226
  return {
220
227
  ok: true,
@@ -224,30 +231,48 @@ const createBrain = ({ kernel, copyUploads, pluginHref }) => {
224
231
  }
225
232
 
226
233
  // An Ask from an app's page. The agent runs in the app's folder, which the
227
- // page starts itself; this hands back what the page adds to the request.
228
- const prepareForApp = async ({ app, prompt, tool }) => {
229
- const appStat = /^[^/\\:]+$/.test(app) && app !== "." && app !== ".."
230
- ? await fs.promises.stat(kernel.path("api", app)).catch(() => null)
231
- : null
234
+ // page starts itself; this writes the request into that folder and hands back
235
+ // the line the page starts the agent with (spec/requirements/request-files.md).
236
+ const prepareForApp = async ({ app, prompt, tool, files }) => {
237
+ const appDir = /^[^/\\:]+$/.test(app) && app !== "." && app !== ".." ? kernel.path("api", app) : ""
238
+ const appStat = appDir ? await fs.promises.stat(appDir).catch(() => null) : null
232
239
  if (!appStat || !appStat.isDirectory()) {
233
240
  const error = new Error("App not found.")
234
241
  error.status = 404
235
242
  throw error
236
243
  }
244
+ // only files the page uploaded for this app
245
+ const uploads = path.resolve(appDir, ".pinokio-temp", "uploads")
246
+ const attached = files.map((file) => (typeof file === "string" ? path.resolve(file) : ""))
247
+ const outside = attached.some((file) => {
248
+ const inside = file ? path.relative(uploads, file) : ""
249
+ return !inside || inside.startsWith("..") || path.isAbsolute(inside)
250
+ })
251
+ if (outside || (!prompt && attached.length === 0)) {
252
+ const error = new Error(outside ? "Attached files must be this app's uploads." : "The request is empty.")
253
+ error.status = 400
254
+ throw error
255
+ }
237
256
  const dir = brainRoot(kernel)
238
257
  const now = new Date()
239
258
  const id = newId(now)
240
259
  await makeFolders(dir)
241
260
 
242
261
  const { skill_dir, skill_state, app_version } = await describeApp(kernel, app)
262
+ const request = prompt ? [prompt] : []
263
+ if (attached.length > 0) {
264
+ request.push(`Attached files:\n${attached.map((file) => `- ${file}`).join("\n")}`)
265
+ }
266
+ request.push([
267
+ "Pinokio brain:",
268
+ `- This app's skill (skill_dir): ${skill_dir} (skill_state: ${skill_state}${app_version ? `, app_version: ${app_version}` : ""})`,
269
+ `- Output folder: ${path.resolve(dir, "me", "files", id)}`
270
+ ].join("\n"))
271
+ const requestLine = await RequestFile.save(appDir, id, request.join("\n\n"))
243
272
  await attempt("log", () => appendLog(dir, { id, now, tool, app, prompt }))
244
273
  return {
245
274
  ok: true,
246
- append: [
247
- "Pinokio brain:",
248
- `- This app's skill (skill_dir): ${skill_dir} (skill_state: ${skill_state}${app_version ? `, app_version: ${app_version}` : ""})`,
249
- `- Output folder: ${path.resolve(dir, "me", "files", id)}`
250
- ].join("\n")
275
+ prompt: requestLine
251
276
  }
252
277
  }
253
278
 
@@ -258,7 +283,8 @@ const createBrain = ({ kernel, copyUploads, pluginHref }) => {
258
283
  prompt: typeof body.prompt === "string" ? body.prompt.trim() : "",
259
284
  tool: typeof body.tool === "string" ? body.tool : "",
260
285
  uploadToken: typeof body.uploadToken === "string" ? body.uploadToken.trim() : "",
261
- app: typeof body.app === "string" ? body.app : ""
286
+ app: typeof body.app === "string" ? body.app : "",
287
+ files: Array.isArray(body.files) ? body.files : []
262
288
  }
263
289
  res.json(await (ask.app ? prepareForApp(ask) : prepare(ask)))
264
290
  } catch (error) {
@@ -677,7 +677,11 @@
677
677
  // One send at a time: a second Enter while the agents are still being read
678
678
  // must not start a second agent.
679
679
  let sending = false;
680
- async function submit() {
680
+ // `given` is text another part of the page sends for the user (Get Help's
681
+ // Ask AI). It goes out exactly as if it had been typed here; what is in the
682
+ // box, and any files attached to it, are left as they are.
683
+ async function submit(given) {
684
+ const asked = typeof given === 'string' ? given.trim() : null;
681
685
  if (state.busy || sending) return;
682
686
  sending = true;
683
687
  state.menu = null;
@@ -695,7 +699,7 @@
695
699
  return;
696
700
  }
697
701
  setMsg('');
698
- const prompt = input.value.trim();
702
+ const prompt = asked === null ? input.value.trim() : asked;
699
703
  state.busy = true;
700
704
  render();
701
705
  try {
@@ -706,30 +710,39 @@
706
710
  return;
707
711
  }
708
712
  // Attached files go into the app's own temp folder first (see
709
- // agent-bar-attach.js); the end of the prompt tells the agent where they are.
710
- const attached = await shared.attachments.paths(appId);
711
- let text = attached.length
712
- ? `${prompt}${prompt ? '\n\n' : ''}Attached files:\n${attached.map((file) => `- ${file}`).join('\n')}`
713
- : prompt;
714
- // Pinokio adds where this app's skill is and where to save output
715
- // (server/lib/brain.js). If that fails the Ask still goes out without it.
716
- const brain = !appId || !text ? null : await fetch('/brain/ask', {
717
- method: 'POST',
718
- headers: { 'Content-Type': 'application/json' },
719
- body: JSON.stringify({ app: appId, prompt, tool: tool.value }),
720
- }).then((response) => (response.ok ? response.json() : null)).catch(() => null);
721
- if (brain && typeof brain.append === 'string') text += `\n\n${brain.append}`;
713
+ // agent-bar-attach.js).
714
+ const attached = asked === null ? await shared.attachments.paths(appId) : [];
715
+ // Pinokio writes the request into a file in the app's folder: the words,
716
+ // where the attached files are, where this app's skill is and where to
717
+ // save output (server/lib/brain.js). The agent is started with the one
718
+ // line that points to that file, never with the request itself
719
+ // (spec/requirements/request-files.md). Nothing is sent if that fails.
720
+ let text = '';
721
+ if (prompt || attached.length) {
722
+ if (!appId) throw new Error('This page does not know which app it is on.');
723
+ const response = await fetch('/brain/ask', {
724
+ method: 'POST',
725
+ headers: { 'Content-Type': 'application/json' },
726
+ body: JSON.stringify({ app: appId, prompt, tool: tool.value, files: attached }),
727
+ });
728
+ const brain = await response.json().catch(() => null);
729
+ if (!response.ok || !brain || typeof brain.prompt !== 'string' || !brain.prompt) {
730
+ throw new Error(brain && typeof brain.error === 'string' && brain.error ? brain.error : 'Failed to prepare the Ask.');
731
+ }
732
+ text = brain.prompt;
733
+ }
722
734
  if (drawer) {
723
735
  // its own session, so a session that is already running is left alone
724
736
  const opened = drawer.openWithAgent({
725
737
  agentHref: withParam(tool.href, 'session', newSession()),
726
738
  prompt: text,
739
+ said: prompt, // what the dock lists the session by: the user's words
727
740
  workspaceCwd,
728
741
  });
729
742
  if (opened === false) throw new Error('Could not launch this plugin.');
730
- shared.attachments.clear();
743
+ if (asked === null) shared.attachments.clear();
731
744
  state.busy = false;
732
- input.value = '';
745
+ if (asked === null) input.value = '';
733
746
  leave();
734
747
  render();
735
748
  window.setTimeout(loadSessions, 1500);
@@ -749,6 +762,9 @@
749
762
  }
750
763
  }
751
764
 
765
+ // Get Help's Ask AI (logs.js, in a frame of this page) sends its question here.
766
+ window.PinokioAgentBarApp.ask = (text) => submit(String(text == null ? '' : text));
767
+
752
768
  running.addEventListener('click', () => toggleMenu('running'));
753
769
  agentButton.addEventListener('click', () => toggleMenu('agent'));
754
770
  input.addEventListener('focus', engage);
@@ -500,11 +500,18 @@ html.agent-bar-panel-open .agent-dock {
500
500
  .agent-bar .agent-dock__liststop i {
501
501
  font-size: 8px;
502
502
  }
503
- .agent-dock__listrow:hover .agent-dock__liststop,
504
503
  .agent-bar .agent-dock__liststop:focus-visible,
505
504
  .agent-bar .agent-dock__liststop[data-armed="true"] {
506
505
  display: inline-flex;
507
506
  }
507
+ /* Only where there is a pointer that can hover. On a touch screen a rule that
508
+ reveals something on :hover makes the first tap count as the hover, so the
509
+ row would need a second tap to open. Stop is in the session's own header. */
510
+ @media (hover: hover) {
511
+ .agent-dock__listrow:hover .agent-dock__liststop {
512
+ display: inline-flex;
513
+ }
514
+ }
508
515
 
509
516
  /* ---- a short message (something could not be done) ---- */
510
517
  .agent-dock__toast {
@@ -1231,8 +1231,11 @@
1231
1231
  const session = url ? sessionAt(url, settings.label) : null;
1232
1232
  if (!session) return false;
1233
1233
  const address = `${url.pathname}${url.search}`;
1234
- if (prompt) {
1235
- asked[session.key] = prompt;
1234
+ // What the session is listed by is the user's words (`said`), not the line
1235
+ // the agent is started with (spec/requirements/request-files.md).
1236
+ const said = typeof settings.said === 'string' ? settings.said.trim() : prompt;
1237
+ if (said) {
1238
+ asked[session.key] = said;
1236
1239
  write(STORE_ASKED, asked);
1237
1240
  }
1238
1241
  if (settings.launch) {
@@ -1253,7 +1256,7 @@
1253
1256
  // a send: starts the agent with the prompt
1254
1257
  openWithAgent: (payload) => {
1255
1258
  if (!payload || typeof payload.agentHref !== 'string' || !payload.agentHref) return false;
1256
- return openFromUrl(payload.agentHref, { prompt: payload.prompt || '', launch: true });
1259
+ return openFromUrl(payload.agentHref, { prompt: payload.prompt || '', said: payload.said, launch: true });
1257
1260
  },
1258
1261
  // a new shell, with a session of its own
1259
1262
  openShellTool: (shell) => {
@@ -1203,11 +1203,33 @@
1203
1203
  const index = launcher.selectedToolIndex
1204
1204
  return Number.isFinite(index) && index >= 0 ? this.askAiTools[index] || null : null
1205
1205
  }
1206
+ // The bar of the app page this report is shown in ("Ask Pinokio about
1207
+ // <app>", agent-bar-app.js), if there is one.
1208
+ appPageBar() {
1209
+ try {
1210
+ let frame = window
1211
+ while (frame.parent && frame.parent !== frame) {
1212
+ frame = frame.parent
1213
+ if (frame.PinokioAgentBarApp && typeof frame.PinokioAgentBarApp.ask === 'function') {
1214
+ return frame.PinokioAgentBarApp
1215
+ }
1216
+ }
1217
+ } catch (_) {}
1218
+ return null
1219
+ }
1206
1220
  async openAskAiModal() {
1207
1221
  if (!this.currentMarkdown && !this.reviewMarkdown) {
1208
1222
  this.updateDraftSizeReview()
1209
1223
  return
1210
1224
  }
1225
+ // On an app page the question goes out through the page's own bar, exactly
1226
+ // as if it had been typed there, and the session opens in the page's agent
1227
+ // window. The dialog below is what a Logs page without that bar still uses.
1228
+ const appBar = this.appPageBar()
1229
+ if (appBar) {
1230
+ appBar.ask(ASK_AI_DEFAULT_PROMPT)
1231
+ return
1232
+ }
1211
1233
  this.setAskAiBusy(true)
1212
1234
  let tools = []
1213
1235
  try {
@@ -0,0 +1,220 @@
1
+ // Storage sweep: removes what closed windows left behind in localStorage.
2
+ //
3
+ // Every Pinokio window has an id (the `?session=` in its address). Its layout
4
+ // and its selected tabs are saved under that id so a reload brings them back:
5
+ // pinokio:layout:<id> the panes of the window (layout.js)
6
+ // pinokio:session:<id>:... selected tabs, split sizes (window_storage.js)
7
+ // Nothing removed these when a window was closed for good, so they piled up
8
+ // until the browser's limit for the site was reached and new saves failed.
9
+ //
10
+ // How a window's age is known:
11
+ // pinokio:seen:<id> when the window was last used, written here on
12
+ // load and refreshed while the window stays open
13
+ // the id itself ids made by layout.js end in their creation
14
+ // time; used for windows that have no stamp yet
15
+ // neither stamped as used now, so it gets the full period
16
+ //
17
+ // When it runs:
18
+ // - a moment after a page loads, at most once a day
19
+ // - when a save fails because storage is full: it sweeps at once and the
20
+ // save is tried again
21
+ //
22
+ // Only the three kinds of entries above are ever removed.
23
+ (() => {
24
+ if (window.PinokioStorageSweep) return;
25
+
26
+ let store;
27
+ try {
28
+ store = window.localStorage;
29
+ if (!store) return;
30
+ } catch (_) {
31
+ return;
32
+ }
33
+
34
+ const HOUR = 60 * 60 * 1000;
35
+ const DAY = 24 * HOUR;
36
+ const KEEP_MS = 30 * DAY; // a window unused for this long is removed
37
+ const SWEEP_EVERY_MS = DAY;
38
+ const STAMP_EVERY_MS = 12 * HOUR;
39
+
40
+ const LAYOUT = 'pinokio:layout:';
41
+ const SESSION = 'pinokio:session:';
42
+ const SEEN = 'pinokio:seen:';
43
+ const LAST_SWEEP = 'pinokio:sweep:last';
44
+
45
+ const rawSetItem = Storage.prototype.setItem;
46
+
47
+ function read(key) {
48
+ try {
49
+ return store.getItem(key);
50
+ } catch (_) {
51
+ return null;
52
+ }
53
+ }
54
+
55
+ // Writes made by the sweep itself never trigger another sweep.
56
+ function write(key, value) {
57
+ try {
58
+ rawSetItem.call(store, key, String(value));
59
+ return true;
60
+ } catch (_) {
61
+ return false;
62
+ }
63
+ }
64
+
65
+ function windowIdOf(key) {
66
+ if (typeof key !== 'string') return null;
67
+ if (key.startsWith(LAYOUT)) return key.slice(LAYOUT.length) || null;
68
+ if (key.startsWith(SEEN)) return key.slice(SEEN.length) || null;
69
+ if (key.startsWith(SESSION)) return key.slice(SESSION.length).split(':')[0] || null;
70
+ return null;
71
+ }
72
+
73
+ // The id of the window this page is shown in: its own address, or the
74
+ // address of the page it is a pane of.
75
+ function currentWindowId() {
76
+ const frames = [window];
77
+ try { if (window.parent && window.parent !== window) frames.push(window.parent); } catch (_) {}
78
+ try { if (window.top && frames.indexOf(window.top) < 0) frames.push(window.top); } catch (_) {}
79
+ for (const frame of frames) {
80
+ try {
81
+ const fromUrl = new URL(frame.location.href).searchParams.get('session');
82
+ if (fromUrl) return fromUrl;
83
+ const layout = frame.PinokioLayout;
84
+ const fromLayout = layout && typeof layout.getSessionId === 'function' ? layout.getSessionId() : null;
85
+ if (fromLayout) return fromLayout;
86
+ } catch (_) {}
87
+ }
88
+ return null;
89
+ }
90
+
91
+ // layout.js makes ids as 'f_' + random letters + the time in base 36.
92
+ function createdAt(id, now) {
93
+ const match = /^f_[a-z0-9]*([a-z0-9]{8})$/.exec(id);
94
+ if (!match) return 0;
95
+ const time = parseInt(match[1], 36);
96
+ return time > Date.UTC(2020, 0, 1) && time < now + DAY ? time : 0;
97
+ }
98
+
99
+ // Every window that has entries: its keys and when it was last used
100
+ // (0 when that cannot be told).
101
+ function collect(now) {
102
+ const windows = new Map();
103
+ for (let i = 0; i < store.length; i += 1) {
104
+ const key = store.key(i);
105
+ const id = windowIdOf(key);
106
+ if (!id) continue;
107
+ let entry = windows.get(id);
108
+ if (!entry) {
109
+ entry = { id, keys: [], seen: 0 };
110
+ windows.set(id, entry);
111
+ }
112
+ entry.keys.push(key);
113
+ if (key.startsWith(SEEN)) entry.seen = Number(store.getItem(key)) || 0;
114
+ }
115
+ windows.forEach((entry) => {
116
+ entry.used = entry.seen || createdAt(entry.id, now);
117
+ });
118
+ return windows;
119
+ }
120
+
121
+ function removeWindow(entry) {
122
+ entry.keys.forEach((key) => {
123
+ try { store.removeItem(key); } catch (_) {}
124
+ });
125
+ return entry.keys.length;
126
+ }
127
+
128
+ // Marks this window as used now.
129
+ function touch() {
130
+ const id = currentWindowId();
131
+ if (!id) return;
132
+ const now = Date.now();
133
+ if (now - (Number(read(SEEN + id)) || 0) < STAMP_EVERY_MS) return;
134
+ write(SEEN + id, now);
135
+ }
136
+
137
+ // Removes the entries of every window unused for longer than the period.
138
+ // Returns how many entries were removed.
139
+ function sweep(options) {
140
+ const force = !!(options && options.force);
141
+ const now = Date.now();
142
+ if (!force && now - (Number(read(LAST_SWEEP)) || 0) < SWEEP_EVERY_MS) return 0;
143
+ let removed = 0;
144
+ try {
145
+ const current = currentWindowId();
146
+ const undated = [];
147
+ collect(now).forEach((entry) => {
148
+ if (entry.id === current) return;
149
+ if (!entry.used) undated.push(entry.id);
150
+ else if (now - entry.used > KEEP_MS) removed += removeWindow(entry);
151
+ });
152
+ // after the removals, so there is room to write the stamps
153
+ undated.forEach((id) => write(SEEN + id, now));
154
+ touch();
155
+ write(LAST_SWEEP, now);
156
+ } catch (_) {}
157
+ return removed;
158
+ }
159
+
160
+ // Storage is full: sweep now. If that frees nothing, remove the quarter of
161
+ // the other windows that were used longest ago.
162
+ function makeRoom() {
163
+ const removed = sweep({ force: true });
164
+ if (removed) return removed;
165
+ let dropped = 0;
166
+ try {
167
+ const current = currentWindowId();
168
+ const others = Array.from(collect(Date.now()).values())
169
+ .filter((entry) => entry.id !== current)
170
+ .sort((a, b) => a.used - b.used);
171
+ others.slice(0, Math.ceil(others.length / 4)).forEach((entry) => {
172
+ dropped += removeWindow(entry);
173
+ });
174
+ } catch (_) {}
175
+ return dropped;
176
+ }
177
+
178
+ function isFull(error) {
179
+ return !!error && (error.name === 'QuotaExceededError' || error.name === 'NS_ERROR_DOM_QUOTA_REACHED' || error.code === 22);
180
+ }
181
+
182
+ // A save that fails because storage is full makes room and is tried again.
183
+ let makingRoom = false;
184
+ Storage.prototype.setItem = function setItem(key, value) {
185
+ try {
186
+ return rawSetItem.call(this, key, value);
187
+ } catch (error) {
188
+ if (this !== store || makingRoom || !isFull(error)) throw error;
189
+ makingRoom = true;
190
+ try {
191
+ for (let attempt = 0; attempt < 3; attempt += 1) {
192
+ if (!makeRoom()) break;
193
+ try {
194
+ return rawSetItem.call(this, key, value);
195
+ } catch (again) {
196
+ if (!isFull(again)) throw again;
197
+ }
198
+ }
199
+ } finally {
200
+ makingRoom = false;
201
+ }
202
+ throw error;
203
+ }
204
+ };
205
+
206
+ function tick() {
207
+ touch();
208
+ sweep();
209
+ }
210
+
211
+ window.PinokioStorageSweep = { sweep, makeRoom, touch };
212
+
213
+ const start = () => {
214
+ if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(tick, { timeout: 5000 });
215
+ else window.setTimeout(tick, 2000);
216
+ window.setInterval(tick, HOUR);
217
+ };
218
+ if (document.readyState === 'complete') start();
219
+ else window.addEventListener('load', start, { once: true });
220
+ })();