dsh-molbio-tools 0.27.0 → 0.28.0

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/lib/client.js CHANGED
@@ -3851,7 +3851,11 @@ window.__ModuleLoader__.load({
3851
3851
  }
3852
3852
  }
3853
3853
  const correction = smallSample && residues > 0 ? (1 / (2 * LN2)) * (4 - 1) / residues : 0;
3854
- const information = Math.max(0, 2 - entropy - correction);
3854
+ // An all-gap column has no base to draw: it reports R_i = 0 (this is what
3855
+ // the module header promises). It used to fall through to 2 - 0 - 0 = 2
3856
+ // bits, so a caller that trusted `bits` saw a full-height column whose
3857
+ // letters were all zero-width.
3858
+ const information = residues === 0 ? 0 : Math.max(0, 2 - entropy - correction);
3855
3859
  const round3 = (x) => Math.round(x * 1000) / 1000;
3856
3860
  out.push({
3857
3861
  column: c + 1,
@@ -9058,6 +9062,7 @@ window.__ModuleLoader__.load({
9058
9062
  exports.parseXml = __molbio_require("snapgene.mjs").parseXml;
9059
9063
  exports.renderPlasmidMap = __molbio_require("plasmid.mjs").renderPlasmidMap;
9060
9064
  exports.normalizeAlignedRow = __molbio_require("msa.mjs").normalizeAlignedRow;
9065
+ exports.normalizeMsaSequence = __molbio_require("msa.mjs").normalizeMsaSequence;
9061
9066
  exports.progressiveAlign = __molbio_require("msa.mjs").progressiveAlign;
9062
9067
  exports.conservationAnalysis = __molbio_require("msa.mjs").conservationAnalysis;
9063
9068
  exports.pairwiseIdentities = __molbio_require("msa.mjs").pairwiseIdentities;
@@ -9111,7 +9116,7 @@ window.__ModuleLoader__.load({
9111
9116
  * All parsing and rendering is the SAME code the Node tools run: this module
9112
9117
  * re-exports through browser-api.mjs, which points at the root .mjs sources.
9113
9118
  */
9114
- const { MolbioInputError, parseGenBank, parseSnapGeneBytes, renderPlasmidMap, columnComposition, renderSequenceLogo, progressiveAlign, parseStructureText, renderStructureImage, DEFAULT_STRUCTURE_VIEW, STRUCTURE_ELEMENT_COLORS, STRUCTURE_EXTENSIONS, STRUCTURE_REPRESENTATIONS } = __molbio_require("build/browser-api.mjs");
9119
+ const { MolbioInputError, parseGenBank, parseSnapGeneBytes, renderPlasmidMap, columnComposition, renderSequenceLogo, progressiveAlign, normalizeAlignedRow, normalizeMsaSequence, parseStructureText, renderStructureImage, DEFAULT_STRUCTURE_VIEW, STRUCTURE_ELEMENT_COLORS, STRUCTURE_EXTENSIONS, STRUCTURE_REPRESENTATIONS } = __molbio_require("build/browser-api.mjs");
9115
9120
  /** Extensions the panel can open, mapped to the parser that handles them. */
9116
9121
  const PLASMID_EXTENSIONS = {
9117
9122
  dna: 'snapgene',
@@ -9136,6 +9141,41 @@ window.__ModuleLoader__.load({
9136
9141
  return match === null ? '' : match[1].toLowerCase();
9137
9142
  }
9138
9143
 
9144
+ /**
9145
+ * The session's workspace root, read the way DSH 0.2.3+ exposes it.
9146
+ *
9147
+ * 0.2.3 moved the directory into a Session projection: the shipped tab bodies
9148
+ * (`dsh-client-ui-sidebar-files` and `dsh-client-ui-workspace`) now call a
9149
+ * shared `selectSessionDirectory(state, sessionId)` that reads
9150
+ * `projectionsBySession[sessionId].values.workingDirectory` first, then the
9151
+ * summary's `projectionValues.workingDirectory`, and only then the summary's
9152
+ * `cwd`. Reading `byId[sessionId].cwd` alone — this package's previous
9153
+ * behaviour — worked only while the store happened to materialise `cwd`; a
9154
+ * session whose directory exists only as a projection produced an empty panel.
9155
+ *
9156
+ * The order is mirrored exactly, because it is the host's contract, not this
9157
+ * package's preference. Every step is optional and every value is type-checked
9158
+ * so the same bundle still runs on the older DSH releases this package
9159
+ * supports (where `projectionsBySession` does not exist and `cwd` is the only
9160
+ * source). An empty string counts as "no root" because the panels key their
9161
+ * loading state on `cwd === undefined`.
9162
+ *
9163
+ * @param {object} state the `useSessions` store snapshot.
9164
+ * @param {string} sessionId the slot's session id.
9165
+ * @returns {string|undefined} the workspace root, when the store has one.
9166
+ */
9167
+ function selectSessionDirectory(state, sessionId) {
9168
+ const projected = (values, key) => {
9169
+ if (values === null || typeof values !== 'object') return undefined;
9170
+ const value = Reflect.get(values, key);
9171
+ return typeof value === 'string' && value !== '' ? value : undefined;
9172
+ };
9173
+ const summary = state?.byId?.[sessionId];
9174
+ return projected(state?.projectionsBySession?.[sessionId]?.values, 'workingDirectory')
9175
+ ?? projected(summary?.projectionValues, 'workingDirectory')
9176
+ ?? (typeof summary?.cwd === 'string' && summary.cwd !== '' ? summary.cwd : undefined);
9177
+ }
9178
+
9139
9179
  /**
9140
9180
  * How the panel should treat one workspace entry.
9141
9181
  * @param {{name?: string, type?: string}} entry a `workspaceFiles.list` row.
@@ -9184,10 +9224,11 @@ window.__ModuleLoader__.load({
9184
9224
  * gateway lifts native bytes into a base64 attachment and reassembles them
9185
9225
  * client-side before the call resolves.
9186
9226
  *
9187
- * Accepting both here is what keeps the panel working across the change: the
9188
- * caller feature-detects the METHOD, and this function normalises the VALUE.
9189
- * A `Uint8Array` is passed through by reference (no copy), so a large plasmid
9190
- * costs nothing extra.
9227
+ * Accepting both here is cheap insurance at one boundary: every supported
9228
+ * harness sends a `Uint8Array` (the panel calls `readBytes` directly), and a
9229
+ * base64 string from an older transport still decodes instead of producing a
9230
+ * wrong picture. A `Uint8Array` is passed through by reference (no copy), so a
9231
+ * large plasmid costs nothing extra.
9191
9232
  *
9192
9233
  * @param {string|Uint8Array} data the `data` field of a successful read.
9193
9234
  * @returns {Uint8Array} the file's raw bytes.
@@ -9298,9 +9339,16 @@ window.__ModuleLoader__.load({
9298
9339
  }
9299
9340
 
9300
9341
  /**
9301
- * Parse an alignment file (FASTA) into the rows the logo needs.
9342
+ * Parse a FASTA file into the rows the panel draws.
9343
+ *
9344
+ * ONE sequence is not an alignment: aligning it would be an identity operation,
9345
+ * and its logo draws one glyph per column — on a long sequence that shrinks to
9346
+ * unreadable noise. Such a record returns `single: true` and the panel prints
9347
+ * the residues instead. Two or more go through the plugin's own aligner, so the
9348
+ * panel shows exactly what `molbio_msa_align` would produce for the same input.
9349
+ *
9302
9350
  * @param {Uint8Array} bytes raw FASTA content.
9303
- * @returns {{ids: string[], rows: string[]}}
9351
+ * @returns {{ids: string[], rows: string[], single: boolean}}
9304
9352
  */
9305
9353
  function parseAlignmentFile(bytes) {
9306
9354
  const text = new TextDecoder('utf-8').decode(bytes).replace(/^\uFEFF/, '');
@@ -9320,11 +9368,70 @@ window.__ModuleLoader__.load({
9320
9368
  current.push(line);
9321
9369
  }
9322
9370
  if (current !== null) rows.push(current.join(''));
9323
- if (rows.length < 2) throw new MolbioInputError(`a sequence logo needs at least 2 sequences (found ${rows.length})`);
9371
+ if (rows.length === 0) throw new MolbioInputError('the FASTA file contains no sequences');
9372
+ // A FASTA can carry PROTEIN. The aligner and the logo are nucleotide-only
9373
+ // (IUPAC DNA/RNA): handing protein rows over used to produce a meaningless
9374
+ // alignment whose logo silently dropped every non-IUPAC letter and then
9375
+ // counted those columns as gaps. Such a file is shown as plain text instead.
9376
+ const nucleotide = rows.every(isNucleotideRow);
9377
+ if (!nucleotide) return { ids, rows, single: rows.length === 1, protein: true };
9378
+ // A pre-aligned FASTA (dashes in the rows) is already an alignment: normalize
9379
+ // the gap spelling and never run the aligner on it again.
9380
+ if (rows.some((sequence) => /[-.]/.test(sequence))) {
9381
+ const normalized = rows.map((sequence, index) => normalizeAlignedRow(sequence, `sequence ${ids[index] ?? index + 1}`));
9382
+ const width = normalized[0].length;
9383
+ if (!normalized.every((sequence) => sequence.length === width)) {
9384
+ throw new MolbioInputError('a pre-aligned FASTA needs equal-length rows');
9385
+ }
9386
+ return { ids, rows: normalized, single: normalized.length === 1, protein: false };
9387
+ }
9388
+ // Normalize (uppercase, U→T) before aligning: this module used to pass raw
9389
+ // rows to the aligner, whose symbol table only knows uppercase IUPAC — a
9390
+ // lowercase FASTA was silently treated like an unknown alphabet.
9391
+ const sequences = rows.map((sequence, index) => normalizeMsaSequence(sequence, `sequence ${ids[index] ?? index + 1}`));
9392
+ if (sequences.length === 1) return { ids, rows: sequences, single: true, protein: false };
9324
9393
  // Reuse the plugin's own aligner so the panel shows exactly what
9325
9394
  // molbio_msa_align would produce for the same input.
9326
- const aligned = progressiveAlign(rows.map((sequence, index) => ({ id: ids[index], sequence })));
9327
- return { ids, rows: aligned.alignment.map((row) => row.sequence) };
9395
+ const aligned = progressiveAlign(sequences.map((sequence, index) => ({ id: ids[index], sequence })));
9396
+ return { ids, rows: aligned.alignment.map((row) => row.sequence), single: false, protein: false };
9397
+ }
9398
+
9399
+ /** The IUPAC nucleotide letters the aligner and the logo understand. */
9400
+ const NUCLEOTIDE_LETTERS = new Set('ACGTURYSWKMBDHVN');
9401
+
9402
+ /**
9403
+ * Whether one FASTA row is nucleotide text (gaps allowed).
9404
+ * @param {string} sequence one row as read from the file.
9405
+ * @returns {boolean} false when it carries an amino-acid letter such as E/F/L/P/Q.
9406
+ */
9407
+ function isNucleotideRow(sequence) {
9408
+ for (const char of sequence.toUpperCase()) {
9409
+ if (char === '-' || char === '.') continue;
9410
+ if (!NUCLEOTIDE_LETTERS.has(char)) return false;
9411
+ }
9412
+ return true;
9413
+ }
9414
+
9415
+ /**
9416
+ * One parsed record as FASTA text, wrapped for a `<pre>`.
9417
+ *
9418
+ * A single-sequence file is read as sequence data, and a raw line of 20 000
9419
+ * residues is not readable either: the residues are wrapped at `width` with
9420
+ * the header line kept so the id travels with them.
9421
+ *
9422
+ * @param {{ids?: string[], rows: string[]}} record the parsed record.
9423
+ * @param {number} [width] residues per line.
9424
+ * @returns {string} FASTA text without a trailing newline.
9425
+ */
9426
+ function sequenceText(record, width = 60) {
9427
+ const step = Math.max(10, Math.floor(Number(width) || 60));
9428
+ const blocks = record.rows.map((sequence, index) => {
9429
+ const id = record.ids?.[index] ?? `seq${index + 1}`;
9430
+ const lines = [`>${id}`];
9431
+ for (let at = 0; at < sequence.length; at += step) lines.push(sequence.slice(at, at + step));
9432
+ return lines.join('\n');
9433
+ });
9434
+ return blocks.join('\n\n');
9328
9435
  }
9329
9436
 
9330
9437
  /**
@@ -9510,12 +9617,29 @@ window.__ModuleLoader__.load({
9510
9617
  async function readWorkspaceText(remote, sessionId, path, signal) {
9511
9618
  let result;
9512
9619
  try {
9513
- result = await remote.workspaceFiles.read({ sessionId }, path, undefined, signal);
9620
+ // First argument: the SessionId lookup (a string), not `{ sessionId }`.
9621
+ // The gateway decodes it with a strict string codec before resolving the
9622
+ // Session's workspace root, so an object fails the call outright.
9623
+ // Third argument: the line window. It is REQUIRED to be an object — the
9624
+ // host's `read()` destructures `range.offset`, so `undefined` threw
9625
+ // "Cannot read properties of undefined (reading 'offset')" and the Papers
9626
+ // tab could never load a library. `{}` takes the page defaults.
9627
+ result = await remote.workspaceFiles.read(sessionId, path, {}, signal);
9514
9628
  } catch (error) {
9515
9629
  return { kind: 'error', message: String(error?.message ?? error) };
9516
9630
  }
9517
9631
  if (result === null || typeof result !== 'object') return { kind: 'error', message: 'the workspace read returned nothing' };
9518
- if (result.ok) return { kind: 'text', text: result.value?.text ?? '' };
9632
+ if (result.ok) {
9633
+ // A page stops at the deployment's line cap; a truncated JSON document
9634
+ // would otherwise surface as "not valid JSON" and hide the real cause.
9635
+ if (result.value?.eof === false) {
9636
+ return {
9637
+ kind: 'error',
9638
+ message: `${path} is longer than one preview page (${result.value?.lines ?? 0} lines); open it directly to read the whole library`,
9639
+ };
9640
+ }
9641
+ return { kind: 'text', text: result.value?.text ?? '' };
9642
+ }
9519
9643
  const failure = result.error;
9520
9644
  // The wire carries typed codes; not-found is the one that means "empty".
9521
9645
  if (failure?.code === 'workspace-file/not-found' || /not-found|does not exist/i.test(String(failure?.message ?? ''))) {
@@ -9650,6 +9774,7 @@ window.__ModuleLoader__.load({
9650
9774
  exports.PLASMID_EXTENSIONS = PLASMID_EXTENSIONS;
9651
9775
  exports.ALIGNMENT_EXTENSIONS = ALIGNMENT_EXTENSIONS;
9652
9776
  exports.extensionOf = extensionOf;
9777
+ exports.selectSessionDirectory = selectSessionDirectory;
9653
9778
  exports.classifyEntry = classifyEntry;
9654
9779
  exports.isOpenable = isOpenable;
9655
9780
  exports.sortEntries = sortEntries;
@@ -9661,6 +9786,8 @@ window.__ModuleLoader__.load({
9661
9786
  exports.parseStructureFile = parseStructureFile;
9662
9787
  exports.structureImage = structureImage;
9663
9788
  exports.parseAlignmentFile = parseAlignmentFile;
9789
+ exports.isNucleotideRow = isNucleotideRow;
9790
+ exports.sequenceText = sequenceText;
9664
9791
  exports.logoSvg = logoSvg;
9665
9792
  exports.MAP_CARD_KIND = MAP_CARD_KIND;
9666
9793
  exports.mapCardView = mapCardView;
@@ -9712,15 +9839,18 @@ window.__ModuleLoader__.load({
9712
9839
  * The body receives the slot framework's `sessionId`/`actions` injection plus
9713
9840
  * the `useSessions` selector hook the runtime synthesises from the root hook
9714
9841
  * sources (every root hook becomes a `use<Name>` prop for session-scope slots),
9715
- * so the workspace root is `useSessions((state) => state.byId[sessionId]?.cwd)`.
9716
- * This package's own `inject` factory only has to hand over the Remote face.
9842
+ * so the workspace root comes from `useSessions` through
9843
+ * `selectSessionDirectory` (panel-core.mjs): the session's `workingDirectory`
9844
+ * projection first, the summary's projection values next, `cwd` last — the
9845
+ * order DSH 0.2.3's own tab bodies use. This package's own `inject` factory only
9846
+ * has to hand over the Remote face.
9717
9847
  *
9718
9848
  * No JSX and no CSS files on purpose: the bundler lowers plain ESM only, and
9719
9849
  * inline styles keep the artifact a single self-contained file — styles injected
9720
9850
  * inside the factory would also have to be torn down by hand on unload.
9721
9851
  */
9722
9852
  const { createElement: h, useEffect, useMemo, useRef, useState } = __ext0;
9723
- const { LIBRARY_FILE, NCBI_KEY_REF, childPath, classifyEntry, credentialInfo, figureCardSummary, figureCardView, isMolbioDetailSubject, remoteFailure, decodeWorkspaceBytes, filterPapers, isOpenable, libraryTags, logoSvg, mapCardSummary, mapCardView, paperFields, paperLink, paperSummary, parseAlignmentFile, parseLibrary, parsePlasmidFile, parseStructureFile, plasmidSvg, readWorkspaceText, sortEntries, structureImage, DEFAULT_STRUCTURE_VIEW, STRUCTURE_ELEMENT_COLORS, STRUCTURE_REPRESENTATIONS } = __molbio_require("build/panel-core.mjs");
9853
+ const { LIBRARY_FILE, NCBI_KEY_REF, childPath, classifyEntry, credentialInfo, figureCardSummary, figureCardView, isMolbioDetailSubject, remoteFailure, decodeWorkspaceBytes, filterPapers, isOpenable, libraryTags, logoSvg, mapCardSummary, mapCardView, paperFields, paperLink, paperSummary, parseAlignmentFile, parseLibrary, parsePlasmidFile, parseStructureFile, plasmidSvg, readWorkspaceText, selectSessionDirectory, sequenceText, sortEntries, structureImage, DEFAULT_STRUCTURE_VIEW, STRUCTURE_ELEMENT_COLORS, STRUCTURE_REPRESENTATIONS } = __molbio_require("build/panel-core.mjs");
9724
9854
  /** This implementation's identity, and the key its body/title register under. */
9725
9855
  const PANEL_ID = 'dsh-molbio-tools';
9726
9856
  /** Type discriminator the tab is opened by. */
@@ -9729,17 +9859,19 @@ window.__ModuleLoader__.load({
9729
9859
  const PAPERS_ID = 'dsh-molbio-tools/papers';
9730
9860
  const PAPERS_KIND = 'molbio-papers';
9731
9861
 
9732
- /** Read one file's raw bytes through the workspace Remote. */
9862
+ /**
9863
+ * Read one file's raw bytes through the workspace Remote.
9864
+ *
9865
+ * The FIRST argument is the SessionId `lookup` (`workspaceFileScopeId`), not a
9866
+ * scope object: the host declares it with a strict string codec and resolves it
9867
+ * to the Session's workspace root on its own — exactly how
9868
+ * `ui-sidebar-documentpreview` calls `readBytes(file.sessionId, …)`. Passing
9869
+ * `{ sessionId }` here (the shape this panel used until 0.27.1) is rejected by
9870
+ * the gateway's argument codec, so EVERY listing and read failed and the panel
9871
+ * showed an empty workspace no matter which extensions the files had.
9872
+ */
9733
9873
  async function readBytes(remote, sessionId, path, signal) {
9734
- const scope = { sessionId };
9735
- // Feature-detect the METHOD, normalise the VALUE (see decodeWorkspaceBytes).
9736
- // DSH 0.1.7-alpha.1 dropped `readAll` and answers `readBytes` with a
9737
- // Uint8Array, so this fallback is the live path on every current install —
9738
- // and the bug it hides (feeding the raw bytes to a base64 decoder) is exactly
9739
- // why test/panel-render.mjs now drives a Remote that has no `readAll` at all.
9740
- const result = typeof remote.workspaceFiles.readAll === 'function'
9741
- ? await remote.workspaceFiles.readAll(scope, path, signal)
9742
- : await remote.workspaceFiles.readBytes(scope, path, { offset: 0, length: 8 * 1024 * 1024 }, signal);
9874
+ const result = await remote.workspaceFiles.readBytes(sessionId, path, { offset: 0, length: 8 * 1024 * 1024 }, signal);
9743
9875
  if (result === null || typeof result !== 'object' || !result.ok) {
9744
9876
  const failure = result !== null && typeof result === 'object' ? result.error : undefined;
9745
9877
  throw new Error(failure?.message ?? `the workspace read of ${path} failed`);
@@ -9749,7 +9881,7 @@ window.__ModuleLoader__.load({
9749
9881
 
9750
9882
  /** List one directory, newest-first ordering rules applied by the caller. */
9751
9883
  async function listDirectory(remote, sessionId, path, signal) {
9752
- const result = await remote.workspaceFiles.list({ sessionId }, path, signal);
9884
+ const result = await remote.workspaceFiles.list(sessionId, path, signal);
9753
9885
  if (result === null || typeof result !== 'object' || !result.ok) {
9754
9886
  const failure = result !== null && typeof result === 'object' ? result.error : undefined;
9755
9887
  throw new Error(failure?.message ?? `the workspace listing of ${path} failed`);
@@ -9798,6 +9930,27 @@ window.__ModuleLoader__.load({
9798
9930
  error: { color: 'var(--dsh-danger, #c0392b)', padding: '10px 12px', whiteSpace: 'pre-wrap' },
9799
9931
  muted: { opacity: 0.6, padding: '10px 12px' },
9800
9932
  svg: { maxWidth: '100%', height: 'auto' },
9933
+ svgScroll: {
9934
+ overflow: 'auto',
9935
+ maxHeight: '68vh',
9936
+ padding: '8px',
9937
+ border: '1px solid var(--dsh-border, #e3e6ea)',
9938
+ borderRadius: '6px',
9939
+ background: '#ffffff',
9940
+ },
9941
+ sequence: {
9942
+ margin: 0,
9943
+ padding: '10px',
9944
+ maxHeight: '68vh',
9945
+ overflow: 'auto',
9946
+ fontFamily: 'ui-monospace, SFMono-Regular, Consolas, monospace',
9947
+ fontSize: '12px',
9948
+ lineHeight: 1.45,
9949
+ whiteSpace: 'pre-wrap',
9950
+ wordBreak: 'break-all',
9951
+ background: 'var(--dsh-soft, #f6f7f9)',
9952
+ borderRadius: '6px',
9953
+ },
9801
9954
  canvas: { maxWidth: '100%', height: 'auto', display: 'block', border: '1px solid var(--dsh-border, #e3e6ea)', borderRadius: '6px', cursor: 'grab', touchAction: 'none', background: '#f7f9fb' },
9802
9955
  button: (active) => ({
9803
9956
  fontSize: '11px',
@@ -9819,12 +9972,24 @@ window.__ModuleLoader__.load({
9819
9972
 
9820
9973
  /** The panel body: a file list on the left, the rendered record on the right. */
9821
9974
  function MolbioPanel({ sessionId, remote, useSessions }) {
9822
- const cwd = useSessions((sessions) => sessions.byId[sessionId]?.cwd);
9975
+ const cwd = useSessions((state) => selectSessionDirectory(state, sessionId));
9976
+ // The listing never blocks on the store: `'.'` is the Session's workspace
9977
+ // root as the HOST resolves it, so a session whose `cwd` is missing from the
9978
+ // list snapshot (or arrives after first render) still lists its files. Reads
9979
+ // use the same base as the listing so an absent `cwd` cannot mix the two.
9980
+ const root = cwd ?? '.';
9981
+ const base = cwd ?? '';
9823
9982
  const [entries, setEntries] = useState([]);
9824
9983
  const [selected, setSelected] = useState(null);
9825
9984
  const [record, setRecord] = useState(null);
9826
- const [status, setStatus] = useState({ kind: cwd === undefined ? 'waiting' : 'loading' });
9985
+ const [status, setStatus] = useState({ kind: 'loading' });
9827
9986
  const [view, setView] = useState({ ...DEFAULT_STRUCTURE_VIEW });
9987
+ // Multi-sequence alignments are drawn at their NATURAL pixel width and the
9988
+ // pane scrolls; zoom scales that width. Fitting a 2 000-column logo into the
9989
+ // pane is what made long alignments unreadable in the first place.
9990
+ const [logoZoom, setLogoZoom] = useState(1);
9991
+ const svgNode = useRef(null);
9992
+ const svgNatural = useRef({ width: 0, height: 0 });
9828
9993
  const [dragging, setDragging] = useState(false);
9829
9994
  const svgHost = useRef(null);
9830
9995
  const canvasHost = useRef(null);
@@ -9832,10 +9997,9 @@ window.__ModuleLoader__.load({
9832
9997
 
9833
9998
  // Directory listing, re-read when the session's workspace root changes.
9834
9999
  useEffect(() => {
9835
- if (cwd === undefined) return undefined;
9836
10000
  const controller = new AbortController();
9837
10001
  setStatus({ kind: 'loading' });
9838
- listDirectory(remote, sessionId, cwd, controller.signal)
10002
+ listDirectory(remote, sessionId, root, controller.signal)
9839
10003
  .then((rows) => {
9840
10004
  if (controller.signal.aborted) return;
9841
10005
  setEntries(rows);
@@ -9845,14 +10009,14 @@ window.__ModuleLoader__.load({
9845
10009
  if (!controller.signal.aborted) setStatus({ kind: 'error', message: String(error?.message ?? error) });
9846
10010
  });
9847
10011
  return () => controller.abort();
9848
- }, [cwd, remote, sessionId]);
10012
+ }, [root, remote, sessionId]);
9849
10013
 
9850
10014
  // The selected file, parsed with the plugin's own parsers.
9851
10015
  useEffect(() => {
9852
- if (selected === null || cwd === undefined) return undefined;
10016
+ if (selected === null) return undefined;
9853
10017
  const controller = new AbortController();
9854
10018
  setStatus({ kind: 'loading' });
9855
- readBytes(remote, sessionId, childPath(cwd, selected.name), controller.signal)
10019
+ readBytes(remote, sessionId, childPath(base, selected.name), controller.signal)
9856
10020
  .then((bytes) => {
9857
10021
  if (controller.signal.aborted) return;
9858
10022
  const kind = classifyEntry(selected);
@@ -9865,6 +10029,7 @@ window.__ModuleLoader__.load({
9865
10029
  // A new structure starts from the same deterministic camera; the
9866
10030
  // previous file's yaw/pitch would be meaningless on a different molecule.
9867
10031
  if (parsed.kind === 'structure') setView({ ...DEFAULT_STRUCTURE_VIEW });
10032
+ if (parsed.kind === 'alignment') setLogoZoom(1);
9868
10033
  setStatus({ kind: 'ready' });
9869
10034
  })
9870
10035
  .catch((error) => {
@@ -9884,7 +10049,11 @@ window.__ModuleLoader__.load({
9884
10049
  const host = svgHost.current;
9885
10050
  if (host === null) return;
9886
10051
  host.replaceChildren();
9887
- if (record === null || status.kind !== 'ready' || record.kind === 'structure') return;
10052
+ svgNode.current = null;
10053
+ // A single-sequence FASTA is printed as text (no logo, no SVG host), and a
10054
+ // structure owns the canvas instead.
10055
+ if (record === null || status.kind !== 'ready' || record.kind === 'structure'
10056
+ || (record.kind === 'alignment' && (record.single === true || record.protein === true))) return;
9888
10057
  // The renderer refuses what it cannot draw (renderPlasmidMap caps a map at
9889
10058
  // 200 features). Letting that throw out of the effect leaves the pane empty
9890
10059
  // with no explanation, so it becomes the pane's error state instead.
@@ -9901,10 +10070,32 @@ window.__ModuleLoader__.load({
9901
10070
  return;
9902
10071
  }
9903
10072
  const svg = parsed.documentElement;
9904
- svg.setAttribute('style', 'max-width:100%;height:auto');
10073
+ if (record.kind === 'alignment') {
10074
+ // Natural size + a scrolling pane: the zoom effect below scales this.
10075
+ svgNatural.current = {
10076
+ width: Number(svg.getAttribute('width')) || 0,
10077
+ height: Number(svg.getAttribute('height')) || 0,
10078
+ };
10079
+ svg.setAttribute('style', 'display:block');
10080
+ } else {
10081
+ svgNatural.current = { width: 0, height: 0 };
10082
+ svg.setAttribute('style', 'max-width:100%;height:auto');
10083
+ }
10084
+ svgNode.current = svg;
9905
10085
  host.append(document.importNode(svg, true));
9906
10086
  }, [record, status.kind]);
9907
10087
 
10088
+ // Scale the appended alignment SVG in place: regenerating the markup on every
10089
+ // zoom step would re-run the alignment's composition for no reason.
10090
+ useEffect(() => {
10091
+ const svg = svgNode.current;
10092
+ const natural = svgNatural.current;
10093
+ if (svg === null || natural.width === 0) return;
10094
+ if (record === null || record.kind !== 'alignment' || record.single === true) return;
10095
+ svg.setAttribute('width', String(Math.max(1, Math.round(natural.width * logoZoom))));
10096
+ svg.setAttribute('height', String(Math.max(1, Math.round(natural.height * logoZoom))));
10097
+ }, [logoZoom, record, status.kind]);
10098
+
9908
10099
  // Structures are rasterized into an RGB buffer and painted into a canvas.
9909
10100
  // The renderer is deterministic and shared with the Node tests; only the
9910
10101
  // canvas plumbing lives here. During a drag the frame drops to 1x
@@ -9982,7 +10173,13 @@ window.__ModuleLoader__.load({
9982
10173
 
9983
10174
  const openable = useMemo(() => entries.filter(isOpenable), [entries]);
9984
10175
 
9985
- const head = h('div', { style: styles.listHead }, 'Sequence & structure files');
10176
+ // The header names the directory being listed. Without it a wrong/empty
10177
+ // workspace is indistinguishable from "the panel is broken", which is how a
10178
+ // missing `cwd` stayed invisible through a restart.
10179
+ const head = h('div', { style: styles.listHead },
10180
+ h('div', null, 'Sequence & structure files'),
10181
+ h('div', { style: styles.listSub, title: root }, cwd ?? 'session workspace'),
10182
+ h('div', { style: styles.listSub }, openable.length === 0 ? 'no openable files' : `${openable.length} file(s)`));
9986
10183
  const list = h(
9987
10184
  'div',
9988
10185
  { style: styles.list },
@@ -10005,7 +10202,6 @@ window.__ModuleLoader__.load({
10005
10202
  );
10006
10203
 
10007
10204
  const body = [];
10008
- if (status.kind === 'waiting') body.push(h('div', { key: 'wait', style: styles.muted }, 'Waiting for the session workspace…'));
10009
10205
  if (status.kind === 'error') body.push(h('div', { key: 'err', style: styles.error }, status.message));
10010
10206
  if (status.kind === 'loading') body.push(h('div', { key: 'load', style: styles.muted }, 'Reading…'));
10011
10207
  if (status.kind === 'ready' && record === null) {
@@ -10038,10 +10234,47 @@ window.__ModuleLoader__.load({
10038
10234
  }
10039
10235
  }
10040
10236
  if (status.kind === 'ready' && record !== null && record.kind === 'alignment') {
10041
- body.push(h('div', { key: 'meta', style: styles.meta },
10042
- h('span', null, `${record.rows.length} sequences`),
10043
- h('span', null, `${record.rows[0]?.length ?? 0} aligned columns`)));
10044
- body.push(h('div', { key: 'svg', ref: svgHost, style: styles.svg }));
10237
+ if (record.protein === true) {
10238
+ // Protein FASTA: the aligner and the logo are nucleotide-only. Saying so
10239
+ // beats the old behaviour, which aligned amino acids as if they were DNA
10240
+ // ambiguity codes and drew a logo with most letters dropped.
10241
+ body.push(h('div', { key: 'meta', style: styles.meta },
10242
+ h('span', null, `${record.rows.length} sequence(s)`),
10243
+ h('span', null, 'not nucleotide')));
10244
+ body.push(h('div', { key: 'notice', style: styles.note },
10245
+ 'This FASTA is not a nucleotide (IUPAC DNA) file. The sequence logo aligns nucleotide sequences only, '
10246
+ + 'so these sequences are shown as plain text and are NOT aligned.'));
10247
+ body.push(h('pre', { key: 'sequence', style: styles.sequence }, sequenceText(record)));
10248
+ } else if (record.single === true) {
10249
+ // One sequence is DATA, not an alignment: print it (wrapped) instead of
10250
+ // drawing a one-glyph-per-column logo that shrinks to noise on a long
10251
+ // sequence. No zoom controls are needed for text.
10252
+ body.push(h('div', { key: 'meta', style: styles.meta },
10253
+ h('span', null, '1 sequence'),
10254
+ h('span', null, `${record.rows[0]?.length ?? 0} residues`)));
10255
+ body.push(h('pre', { key: 'sequence', style: styles.sequence }, sequenceText(record)));
10256
+ } else {
10257
+ body.push(h('div', { key: 'meta', style: styles.meta },
10258
+ h('span', null, `${record.rows.length} sequences`),
10259
+ h('span', null, `${record.rows[0]?.length ?? 0} aligned columns`)));
10260
+ body.push(h('div', { key: 'zoom', style: styles.meta },
10261
+ h('button', {
10262
+ key: 'out',
10263
+ style: styles.button(false),
10264
+ title: 'Zoom out',
10265
+ onClick: () => setLogoZoom((value) => Math.max(0.1, value / 1.25)),
10266
+ }, '−'),
10267
+ h('span', { key: 'level', style: { minWidth: '48px', textAlign: 'center' } }, `${Math.round(logoZoom * 100)}%`),
10268
+ h('button', {
10269
+ key: 'in',
10270
+ style: styles.button(false),
10271
+ title: 'Zoom in',
10272
+ onClick: () => setLogoZoom((value) => Math.min(8, value * 1.25)),
10273
+ }, '+'),
10274
+ h('button', { key: 'reset', style: styles.button(false), title: 'Actual size', onClick: () => setLogoZoom(1) }, 'Reset')));
10275
+ body.push(h('div', { key: 'svg-scroll', style: styles.svgScroll },
10276
+ h('div', { key: 'svg', ref: svgHost, style: { lineHeight: 0 } })));
10277
+ }
10045
10278
  }
10046
10279
  if (status.kind === 'ready' && record !== null && record.kind === 'structure') {
10047
10280
  body.push(h('div', { key: 'meta', style: styles.meta },
@@ -10240,9 +10473,15 @@ window.__ModuleLoader__.load({
10240
10473
  * tools instead (see EMPTY_HINT).
10241
10474
  */
10242
10475
  function PapersPanel({ sessionId, remote, useSessions }) {
10243
- const cwd = useSessions((sessions) => sessions.byId[sessionId]?.cwd);
10476
+ // The library path is WORKSPACE-RELATIVE, matching how the tools resolve it
10477
+ // (papers.mjs `workspaceFilePath` joins `workspaceRoot`, the sandbox root,
10478
+ // not the session cwd). Building it from `cwd` read the wrong file whenever
10479
+ // those two differ. `useSessions` stays in the signature because the slot
10480
+ // runtime provides it (and the contract pins that); this panel needs no path
10481
+ // from the store — a useless `cwd` is what the property is for.
10482
+ const libraryPath = LIBRARY_FILE;
10244
10483
  const [papers, setPapers] = useState([]);
10245
- const [status, setStatus] = useState({ kind: 'waiting' });
10484
+ const [status, setStatus] = useState({ kind: 'loading' });
10246
10485
  const [query, setQuery] = useState('');
10247
10486
  const [tag, setTag] = useState('');
10248
10487
  const [selectedId, setSelectedId] = useState(null);
@@ -10250,13 +10489,9 @@ window.__ModuleLoader__.load({
10250
10489
  const keyView = ncbiKeyView(keyState);
10251
10490
 
10252
10491
  useEffect(() => {
10253
- if (cwd === undefined) {
10254
- setStatus({ kind: 'waiting' });
10255
- return undefined;
10256
- }
10257
10492
  const controller = new AbortController();
10258
10493
  setStatus({ kind: 'loading' });
10259
- readWorkspaceText(remote, sessionId, childPath(cwd, LIBRARY_FILE), controller.signal)
10494
+ readWorkspaceText(remote, sessionId, libraryPath, controller.signal)
10260
10495
  .then((result) => {
10261
10496
  if (controller.signal.aborted) return;
10262
10497
  if (result.kind === 'missing') {
@@ -10279,7 +10514,7 @@ window.__ModuleLoader__.load({
10279
10514
  if (!controller.signal.aborted) setStatus({ kind: 'error', message: String(error?.message ?? error) });
10280
10515
  });
10281
10516
  return () => controller.abort();
10282
- }, [cwd, remote, sessionId]);
10517
+ }, [libraryPath, remote, sessionId]);
10283
10518
 
10284
10519
  const tags = useMemo(() => libraryTags(papers), [papers]);
10285
10520
  const visible = useMemo(() => filterPapers(papers, { query, tag }), [papers, query, tag]);
@@ -10325,7 +10560,6 @@ window.__ModuleLoader__.load({
10325
10560
  h('div', { style: styles.listSub }, paperSummary(paper))))));
10326
10561
 
10327
10562
  const detail = [];
10328
- if (status.kind === 'waiting') detail.push(h('div', { key: 'wait', style: styles.muted }, 'Waiting for the session workspace…'));
10329
10563
  if (status.kind === 'loading') detail.push(h('div', { key: 'load', style: styles.muted }, 'Reading papers.json…'));
10330
10564
  if (status.kind === 'error') detail.push(h('div', { key: 'err', style: styles.error }, status.message));
10331
10565
  if (status.kind === 'empty') {
@@ -10608,7 +10842,13 @@ window.__ModuleLoader__.load({
10608
10842
  }
10609
10843
 
10610
10844
  /** Required browser services. */
10611
- const inject = ['slots', 'sidebarRightTabs', 'remote'];
10845
+ // `remote.workspaceFiles` is a namespace sub-service, not a plain property:
10846
+ // every shipped consumer (ui-sidebar-files, ui-sidebar-documentpreview,
10847
+ // ui-reference, ui-open-in-app) injects it beside `remote`, and this package
10848
+ // used to declare only `remote`. Waiting for the namespace is what makes
10849
+ // `ctx.remote.workspaceFiles` usable the moment `apply()` runs and the panels
10850
+ // render; without it the lookup is a race the panel cannot report.
10851
+ const inject = ['slots', 'sidebarRightTabs', 'remote', 'remote.workspaceFiles'];
10612
10852
 
10613
10853
  /**
10614
10854
  * Claim seats through `ctx.slots.inject`, never a bare `ctx.slots.register` —
package/logo.mjs CHANGED
@@ -98,7 +98,11 @@ export function columnComposition(rows, options = {}) {
98
98
  }
99
99
  }
100
100
  const correction = smallSample && residues > 0 ? (1 / (2 * LN2)) * (4 - 1) / residues : 0;
101
- const information = Math.max(0, 2 - entropy - correction);
101
+ // An all-gap column has no base to draw: it reports R_i = 0 (this is what
102
+ // the module header promises). It used to fall through to 2 - 0 - 0 = 2
103
+ // bits, so a caller that trusted `bits` saw a full-height column whose
104
+ // letters were all zero-width.
105
+ const information = residues === 0 ? 0 : Math.max(0, 2 - entropy - correction);
102
106
  const round3 = (x) => Math.round(x * 1000) / 1000;
103
107
  out.push({
104
108
  column: c + 1,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-molbio-tools",
3
- "version": "0.27.0",
3
+ "version": "0.28.0",
4
4
  "description": "Zero-dependency molecular-biology plugin bundle for the DeepSeek Harness: sequence analysis, primer design (incl. cross-intron qPCR primers, TaqMan hydrolysis/MGB probes with ordering CSV and multiplex compatibility, duplex thermodynamics (ΔH/ΔS/ΔG37/Tm with hairpin and dimer checks)), in-silico PCR, cloning simulation, SnapGene .dna parsing and plasmid maps, Sanger verification, protein tools (incl. helical wheel, hydropathy and charge-pH plots), methylation-aware restriction analysis with double-digest buffer checks, qPCR analysis and plotting, multiple sequence alignment that conserves every input residue, conservation analysis, sequence logos, codon-usage analysis, phylogenetic trees with bootstrap support, Newick I/O and long-name label wrapping, CpG-island/GC-skew composition analysis, k-mer dotplots, read-level FASTQ QC, vector/adapter contamination screening, FASTQ trimming/filtering, batch file analysis with CSV export, silent restriction-site mutagenesis, family-aware CRISPR gRNA design (SpCas9/SaCas9/Cas12a/Cas13) with off-target search, an opt-in hand-off that shows a generated plot to the model as an attached image, plus a browser-side right-sidebar panel (plasmid maps, sequence logos, and a rotatable realistic 3D ball-and-stick/space-filling preview of PDB/mmCIF/SDF structures drawn in the Web GUI) and a literature/protocol/experiment record system.",
5
5
  "type": "module",
6
6
  "main": "index.mjs",
@@ -96,7 +96,10 @@
96
96
  "test",
97
97
  "docs",
98
98
  "CHANGELOG.md",
99
- "README.md"
99
+ "README.md",
100
+ "protein-annotate.mjs",
101
+ "sequence-ops.mjs",
102
+ "sequencing.mjs"
100
103
  ],
101
104
  "dsh": {
102
105
  "compatibility": {
@@ -110,7 +113,8 @@
110
113
  "0.2.2-rc.2": "compatible",
111
114
  "0.2.2-rc.3": "compatible",
112
115
  "0.2.2-rc.4": "unknown",
113
- "0.2.2-rc.5": "compatible"
116
+ "0.2.2-rc.5": "compatible",
117
+ "0.2.3-alpha.2": "compatible"
114
118
  }
115
119
  },
116
120
  "bundle": {