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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import {
  parseSetup,
  createSession,
  exportCheckpoint,
  readCheckpoint,
  sessionFromCheckpoint,
} from "./queue.mjs";
const $ = (id) => document.getElementById(id);
const node = (tag, text) => {
  const e = document.createElement(tag);
  e.textContent = text;
  return e;
};
let session = null,
  setupVersion = 0,
  startTicket = 0,
  fileTicket = 0,
  exportTicket = 0,
  staged = null,
  urls = [],
  initialDone = false,
  startBusy = false;
function syncStart() {
  $("start").disabled =
    startBusy || (!initialDone && !session && setupVersion === 0);
}
function status(message) {
  $("status").textContent = message;
}
function error(message) {
  $("error").textContent = message;
  $("error").hidden = false;
  $("error").focus();
}
function clearError() {
  $("error").hidden = true;
  $("error").textContent = "";
}
function clearExports() {
  exportTicket++;
  urls.forEach(URL.revokeObjectURL);
  urls = [];
  $("downloads").replaceChildren();
  $("prepare").disabled = !session;
}
function clearPreview() {
  fileTicket++;
  staged = null;
  $("restore-preview").hidden = true;
  $("checkpoint-file").value = "";
}
function saveState() {
  if (!session) return;
  $("save-state").textContent = session.dirty
    ? `Revision ${session.revision} has no current checkpoint copy recorded. Prepare and download it.`
    : `Current revision ${session.revision} was restored from a checkpoint or its download was started. Verify the file is actually saved.`;
}
function render() {
  const active = Boolean(session);
  $("initial").hidden = active;
  $("session-pane").hidden = !active;
  $("save-pane").hidden = !active;
  if (!active) return;
  const sum = session.summary();
  $("counts").replaceChildren();
  for (const [label, value] of [
    ["All records", sum.total],
    ["Labelled", sum.labelled],
    ["Abstained", sum.abstained],
    ["Unlabelled", sum.unlabelled],
  ]) {
    const box = node("div", "");
    box.append(node("strong", String(value)), node("span", label));
    $("counts").append(box);
  }
  $("reviewed").textContent =
    `Reviewed ${sum.reviewed}/${sum.total} (${(100 * sum.reviewed_fraction).toFixed(1)}%), including abstentions · unknown group: ${sum.unknown_group_records}`;
  $("progress").value = sum.reviewed_fraction;
  $("inventory-hash").textContent =
    `Inventory SHA-256: ${session.inventoryHash}`;
  $("filter").value = session.filter;
  const ids = session.visibleIds(),
    index = ids.indexOf(session.activeId);
  $("jump").replaceChildren();
  const placeholder = node(
    "option",
    ids.length ? "Choose a visible record" : "No matching records",
  );
  placeholder.value = "";
  placeholder.disabled = true;
  $("jump").append(placeholder);
  for (const id of ids) {
    const option = node("option", id);
    option.value = id;
    $("jump").append(option);
  }
  $("jump").value = session.activeId ?? "";
  $("jump").disabled = ids.length === 0;
  $("previous").disabled = !ids.length || index === 0;
  $("next").disabled = !ids.length || index === ids.length - 1;
  $("position").textContent =
    index >= 0
      ? `${index + 1} / ${ids.length} visible`
      : `No current record · ${ids.length} visible`;
  const item = session.inventory.items.find((r) => r.id === session.activeId);
  $("record").hidden = !item;
  $("empty-record").hidden = Boolean(item);
  $("empty-record").textContent = ids.length
    ? "No current record matches the action. Choose one from the list, or use Next."
    : "No records match this filter. Choose All records to revisit decisions.";
  if (item) {
    const a = session.annotation(item.id);
    $("record-id").textContent = item.id;
    $("record-group").textContent =
      item.group === null
        ? "Group: unknown (not inferred)"
        : `Group: ${item.group}`;
    $("source-text").textContent = item.text;
    $("decision").textContent =
      a.status === "labelled"
        ? `Current decision: labelled · ${a.label}`
        : `Current decision: ${a.status}`;
    $("label-buttons").replaceChildren();
    session.inventory.taxonomy.forEach((label, i) => {
      const button = node("button", `${i + 1}. ${label}`);
      button.setAttribute("aria-label", `Label ${i + 1}: ${label}`);
      button.setAttribute(
        "aria-pressed",
        String(a.status === "labelled" && a.label === label),
      );
      button.addEventListener("click", () => decide("labelled", label));
      $("label-buttons").append(button);
    });
    $("clear").disabled = a.status === "unlabelled";
  }
  $("undo").disabled = session.undoCount === 0;
  $("undo-count").textContent =
    `${session.undoCount} undo steps available (up to 20).`;
  $("label-counts").replaceChildren();
  for (const x of sum.labels) {
    const tr = node("tr", "");
    tr.append(node("td", x.label), node("td", String(x.count)));
    $("label-counts").append(tr);
  }
  saveState();
}
function install(next, message) {
  session = next;
  startTicket++;
  startBusy = false;
  setupVersion++;
  $("items").value =
    next.inventory.items.map((r) => JSON.stringify(r)).join("\n") + "\n";
  $("taxonomy").value = next.inventory.taxonomy.join("\n");
  syncStart();
  clearPreview();
  clearExports();
  clearError();
  render();
  $("setup").open = false;
  status(message);
  $("record-panel").focus();
}
function decide(kind, label = null) {
  if (!session || !session.activeId) return;
  clearError();
  try {
    const changed = session.decide(kind, label);
    if (changed) clearExports();
    render();
    status(
      changed
        ? "Decision applied to one record. Counts still cover the full inventory."
        : "The decision was already the same; no record or revision was added.",
    );
    $("record-panel").focus();
  } catch (e) {
    error(e.message);
  }
}
for (const id of ["items", "taxonomy"])
  $(id).addEventListener("input", () => {
    setupVersion++;
    syncStart();
    status(
      session
        ? "Setup edited. Active work is unchanged until Start new session."
        : "Setup edited. Start when ready.",
    );
  });
$("start").addEventListener("click", async () => {
  clearError();
  const ticket = ++startTicket,
    setupAtStart = setupVersion,
    old = session,
    oldRevision = session?.revision;
  startBusy = true;
  syncStart();
  try {
    const parsed = parseSetup($("items").value, $("taxonomy").value),
      next = await createSession(parsed.inventory);
    if (ticket !== startTicket) return;
    if (
      setupAtStart !== setupVersion ||
      old !== session ||
      oldRevision !== session?.revision
    ) {
      status(
        "Work or setup changed while preparing. Current decisions were kept; start again when ready.",
      );
      return;
    }
    install(
      next,
      `New session: ${next.summary().total} records, ${parsed.blank_lines_ignored} blank lines ignored. Download a checkpoint to retain decisions.`,
    );
  } catch (e) {
    if (ticket === startTicket) error(e.message);
  } finally {
    if (ticket === startTicket) {
      startBusy = false;
      syncStart();
    }
  }
});
$("filter").addEventListener("change", () => {
  if (session) {
    session.setFilter($("filter").value);
    render();
    status(
      "Queue view changed. Decisions and checkpoint revision are unchanged.",
    );
  }
});
$("jump").addEventListener("change", () => {
  if (session && $("jump").value) {
    session.select($("jump").value);
    render();
    $("record-panel").focus();
  }
});
for (const [id, direction] of [
  ["previous", -1],
  ["next", 1],
])
  $(id).addEventListener("click", () => {
    if (session) {
      session.navigate(direction);
      render();
      $("record-panel").focus();
    }
  });
$("abstain").addEventListener("click", () => decide("abstained"));
$("clear").addEventListener("click", () => decide("unlabelled"));
function undo() {
  if (!session) return;
  clearError();
  try {
    const changed = session.undo();
    if (changed) clearExports();
    render();
    status(
      changed
        ? "Prior decision restored. The queue now shows that record."
        : "No undo steps available.",
    );
    $("record-panel").focus();
  } catch (e) {
    error(e.message);
  }
}
$("undo").addEventListener("click", undo);
document.addEventListener("keydown", (e) => {
  if (
    !session ||
    e.repeat ||
    e.isComposing ||
    e.ctrlKey ||
    e.metaKey ||
    e.altKey ||
    e.target.isContentEditable ||
    e.target.closest?.("input,textarea,select")
  )
    return;
  const key = e.key.toLowerCase();
  if (key === "u") {
    e.preventDefault();
    undo();
  } else if (session.activeId && key === "a") {
    e.preventDefault();
    decide("abstained");
  } else if (session.activeId && /^[1-9]$/.test(key)) {
    const label = session.inventory.taxonomy[Number(key) - 1];
    if (label !== undefined) {
      e.preventDefault();
      decide("labelled", label);
    }
  }
});
function link(name, value, label, type) {
  const url = URL.createObjectURL(new Blob([value], { type }));
  urls.push(url);
  const a = node("a", label);
  a.href = url;
  a.download = name;
  $("downloads").append(a);
  return a;
}
$("prepare").addEventListener("click", async () => {
  if (!session) return;
  clearError();
  clearExports();
  const ticket = exportTicket,
    current = session,
    revision = current.revision;
  $("prepare").disabled = true;
  try {
    const checkpoint = await exportCheckpoint(current);
    if (
      ticket !== exportTicket ||
      current !== session ||
      revision !== session.revision
    )
      return;
    const a = link(
      `label-queue-checkpoint-r${revision}.json`,
      JSON.stringify(checkpoint, null, 2) + "\n",
      "Download resumable checkpoint",
      "application/json;charset=utf-8",
    );
    a.addEventListener("click", () => {
      if (current === session && current.markDownloaded(revision)) {
        saveState();
        status(
          `Checkpoint download started for revision ${revision}. Verify it is saved before closing.`,
        );
      }
    });
    link(
      `label-queue-annotations-r${revision}.jsonl`,
      current.annotationJSONL(),
      "Download all annotation records",
      "application/x-ndjson;charset=utf-8",
    );
    status(
      "Current downloads prepared. A checkpoint is retained only when you actually download and keep its file.",
    );
  } catch (e) {
    if (ticket === exportTicket) error(e.message);
  } finally {
    if (ticket === exportTicket) $("prepare").disabled = false;
  }
});
$("checkpoint-file").addEventListener("change", async () => {
  const ticket = ++fileTicket;
  staged = null;
  $("restore-preview").hidden = true;
  clearError();
  const file = $("checkpoint-file").files[0];
  if (!file) return;
  try {
    if (file.size > 4 * 1048576) throw Error("Checkpoint file exceeds 4 MiB.");
    const checkpoint = await readCheckpoint(
      new Uint8Array(await file.arrayBuffer()),
    );
    if (ticket !== fileTicket) return;
    staged = checkpoint;
    const preview = sessionFromCheckpoint(checkpoint).summary();
    $("preview-summary").textContent =
      `Verified preview: ${preview.total} records · ${preview.labelled} labelled · ${preview.abstained} abstained · ${preview.unlabelled} unlabelled. Current work is still unchanged.`;
    $("preview-hash").textContent =
      `Inventory SHA-256: ${checkpoint.inventory_sha256}`;
    $("restore-preview").hidden = false;
    status(
      "Checkpoint checksums and schema verified. Replace explicitly to restore its session.",
    );
  } catch (e) {
    if (ticket === fileTicket) {
      staged = null;
      error(e.message);
      status("Checkpoint rejected. Current work was kept.");
    }
  }
});
$("replace").addEventListener("click", () => {
  if (staged) {
    const next = sessionFromCheckpoint(staged);
    install(
      next,
      "Checkpoint restored. All inventory records and decisions were kept; undo history starts empty.",
    );
  }
});
try {
  const response = await fetch("sample.jsonl", { cache: "no-store" });
  if (!response.ok) throw Error();
  const text = await response.text();
  if (setupVersion === 0 && !session) {
    $("items").value = text;
    status("Synthetic inventory loaded. Choose labels, then start a session.");
  } else if (!session)
    status("Your setup edits were preserved. Start when ready.");
} catch {
  status("Sample could not load. Paste JSONL or restore a checkpoint locally.");
} finally {
  initialDone = true;
  syncStart();
  render();
}