@datagrok/hit-triage 1.10.8 → 1.11.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.
Files changed (129) hide show
  1. package/.grokignore +2 -0
  2. package/.turbo/turbo-build.log +24 -6
  3. package/.vscode/settings.json +16 -0
  4. package/CHANGELOG.md +80 -1
  5. package/CLAUDE.md +87 -10
  6. package/README_HD.md +14 -14
  7. package/README_HT.md +6 -6
  8. package/README_PH.md +110 -0
  9. package/bdd/bdd.config.json +3 -0
  10. package/bdd/bindings/campaign.ts +626 -0
  11. package/bdd/bindings/hit-design.ts +93 -0
  12. package/bdd/bindings/landing.ts +839 -0
  13. package/bdd/bindings/pepti-hit.ts +35 -0
  14. package/bdd/features/campaign/crumbs.feature +22 -0
  15. package/bdd/features/campaign/grid.feature +56 -0
  16. package/bdd/features/campaign/merge.feature +105 -0
  17. package/bdd/features/campaign/molecule-vid.feature +40 -0
  18. package/bdd/features/campaign/permissions.feature +46 -0
  19. package/bdd/features/campaign/progress-tracker.feature +89 -0
  20. package/bdd/features/campaign/refresh-hint.feature +33 -0
  21. package/bdd/features/campaign/ribbon.feature +49 -0
  22. package/bdd/features/campaign/stage-choices.feature +39 -0
  23. package/bdd/features/campaign/submit.feature +135 -0
  24. package/bdd/features/campaign/tracker-cards.feature +46 -0
  25. package/bdd/features/campaign/view-only.feature +37 -0
  26. package/bdd/features/hit-design/campaign-column-metadata.feature +61 -0
  27. package/bdd/features/landing/campaign-deep-links.feature +61 -0
  28. package/bdd/features/landing/hit-design-campaigns-fixes.feature +116 -0
  29. package/bdd/features/landing/hit-design-campaigns.feature +153 -0
  30. package/bdd/features/landing/hit-triage-campaigns.feature +99 -0
  31. package/bdd/features/landing/new-campaign.feature +69 -0
  32. package/bdd/features/landing/pep-triage-campaigns.feature +41 -0
  33. package/bdd/features/landing/pepti-hit-landing.feature +132 -0
  34. package/bdd/features/pepti-hit/helm-edit.feature +47 -0
  35. package/bdd/features/templates/template-editor.feature +130 -0
  36. package/bdd/features/templates/template-picker.feature +112 -0
  37. package/bdd/features/templates/triage-forms.feature +59 -0
  38. package/bdd/fixtures/bar-chart.layout +1 -0
  39. package/bdd/fixtures/merge-local.csv +2 -0
  40. package/bdd/generated/campaign/crumbs.test.ts +33 -0
  41. package/bdd/generated/campaign/grid.test.ts +79 -0
  42. package/bdd/generated/campaign/merge.test.ts +134 -0
  43. package/bdd/generated/campaign/molecule-vid.test.ts +52 -0
  44. package/bdd/generated/campaign/permissions.test.ts +58 -0
  45. package/bdd/generated/campaign/progress-tracker.test.ts +129 -0
  46. package/bdd/generated/campaign/refresh-hint.test.ts +44 -0
  47. package/bdd/generated/campaign/ribbon.test.ts +65 -0
  48. package/bdd/generated/campaign/stage-choices.test.ts +55 -0
  49. package/bdd/generated/campaign/submit.test.ts +167 -0
  50. package/bdd/generated/campaign/tracker-cards.test.ts +49 -0
  51. package/bdd/generated/campaign/view-only.test.ts +51 -0
  52. package/bdd/generated/hit-design/campaign-column-metadata.test.ts +76 -0
  53. package/bdd/generated/landing/campaign-deep-links.test.ts +68 -0
  54. package/bdd/generated/landing/hit-design-campaigns-fixes.test.ts +99 -0
  55. package/bdd/generated/landing/hit-design-campaigns.test.ts +160 -0
  56. package/bdd/generated/landing/hit-triage-campaigns.test.ts +107 -0
  57. package/bdd/generated/landing/new-campaign.test.ts +78 -0
  58. package/bdd/generated/landing/pep-triage-campaigns.test.ts +52 -0
  59. package/bdd/generated/landing/pepti-hit-landing.test.ts +130 -0
  60. package/bdd/generated/pepti-hit/helm-edit.test.ts +64 -0
  61. package/bdd/generated/templates/template-editor.test.ts +137 -0
  62. package/bdd/generated/templates/template-picker.test.ts +119 -0
  63. package/bdd/generated/templates/triage-forms.test.ts +68 -0
  64. package/bdd/package.json +1 -0
  65. package/bdd/tsconfig.json +13 -0
  66. package/css/hit-triage.css +27 -23
  67. package/dist/package-test.js +690 -4
  68. package/dist/package-test.js.map +1 -1
  69. package/dist/package.js +318 -73
  70. package/dist/package.js.map +1 -1
  71. package/package.json +15 -8
  72. package/queries/locks.sql +37 -0
  73. package/src/app/accordeons/layout-input.ts +52 -44
  74. package/src/app/accordeons/new-campaign-accordeon.ts +91 -54
  75. package/src/app/accordeons/new-hit-design-campaign-accordeon.ts +3 -67
  76. package/src/app/accordeons/new-pep-triage-template-accordeon.ts +39 -41
  77. package/src/app/accordeons/new-template-accordeon.ts +41 -24
  78. package/src/app/ai/view-functions.ts +22 -19
  79. package/src/app/base-view.ts +99 -8
  80. package/src/app/consts.ts +8 -5
  81. package/src/app/dialogs/functions-dialog.ts +14 -9
  82. package/src/app/dialogs/merge-table-dialog.ts +181 -325
  83. package/src/app/hit-app-base.ts +61 -90
  84. package/src/app/hit-design-app.ts +492 -882
  85. package/src/app/hit-design-views/info-view.ts +57 -407
  86. package/src/app/hit-design-views/submit-view.ts +216 -111
  87. package/src/app/hit-design-views/tiles-view.ts +168 -123
  88. package/src/app/hit-design-views/utils.css +0 -8
  89. package/src/app/hit-triage-app.ts +69 -38
  90. package/src/app/hit-triage-views/info-view.ts +70 -371
  91. package/src/app/pep-triage-app.ts +2 -2
  92. package/src/app/pep-triage-views/info-view.ts +42 -83
  93. package/src/app/pepti-hit-app.ts +32 -183
  94. package/src/app/pepti-hits-views/info-view.ts +15 -37
  95. package/src/app/shared/campaign-catalog.ts +408 -0
  96. package/src/app/shared/campaign-session.ts +557 -0
  97. package/src/app/shared/compute-editor.ts +274 -0
  98. package/src/app/shared/hit-home.ts +45 -0
  99. package/src/app/shared/new-campaign-form.ts +90 -0
  100. package/src/app/shared/permissions-editor.ts +93 -0
  101. package/src/app/shared/template-editor.ts +331 -0
  102. package/src/app/shared/template-picker.ts +154 -0
  103. package/src/app/types.ts +2 -0
  104. package/src/app/utils/merge-table.ts +183 -78
  105. package/src/app/utils.ts +34 -325
  106. package/src/package-api.ts +29 -8
  107. package/src/package-test.ts +17 -2
  108. package/src/package.g.ts +12 -8
  109. package/src/package.ts +19 -7
  110. package/src/tests/ai.ts +244 -0
  111. package/src/tests/campaign-layout.ts +82 -0
  112. package/src/tests/campaign-session.ts +168 -0
  113. package/src/tests/campaigns.ts +23 -0
  114. package/src/tests/catalog.ts +156 -0
  115. package/src/tests/compat.ts +482 -0
  116. package/src/tests/compute.ts +165 -0
  117. package/src/tests/fixtures.ts +359 -0
  118. package/src/tests/merge.ts +149 -0
  119. package/src/tests/owners.ts +11 -0
  120. package/src/tests/save-lock.ts +932 -0
  121. package/src/tests/storage.ts +106 -0
  122. package/src/tests/template-editor.ts +538 -0
  123. package/src/tests/templates.ts +143 -0
  124. package/src/tests/triage-start.ts +81 -0
  125. package/src/tests/u2-guards.ts +384 -0
  126. package/src/tests/vid.ts +77 -0
  127. package/tsconfig.json +3 -0
  128. package/src/app/accordeons/new-hit-design-template-accordeon.ts +0 -238
  129. package/src/app/dialogs/permissions-dialog.ts +0 -66
@@ -0,0 +1,932 @@
1
+ /* eslint-disable max-len */
2
+ import * as grok from 'datagrok-api/grok';
3
+ import * as DG from 'datagrok-api/dg';
4
+ import {category, expect, test, waitUntil} from '@datagrok-libraries/test/src/test';
5
+ import {_package} from '../package';
6
+ import * as api from '../package-api';
7
+ import {HitDesignApp} from '../app/hit-design-app';
8
+ import {HitDesignTemplate} from '../app/types';
9
+ import {obfuscateSmiles} from '../app/utils/molreg';
10
+ import {mergeIntoCampaign} from '../app/utils/merge-table';
11
+ import {addRows, allUsers, countQueryCalls, designCampaign, designColumns, designCsv, expectSame, hasBalloon, hitdesignSql,
12
+ noComputeTemplate, otherUserId, Sandbox, sqlText, startDesignCampaign, startTriageCampaign, triageTemplate,
13
+ unknownGroupId} from './fixtures';
14
+
15
+ const acquire = (sb: Sandbox, id: string, lockedBy: string) => api.queries.acquireCampaignLock(sb.appName, id, lockedBy);
16
+ const release = (sb: Sandbox, id: string) => api.queries.releaseCampaignLock(sb.appName, id);
17
+
18
+ async function lockRow(sb: Sandbox, id: string): Promise<{ttl: number, lockedBy: string} | null> {
19
+ const df = await hitdesignSql('SELECT EXTRACT(EPOCH FROM expires_at - NOW()) AS ttl, locked_by FROM hitdesign.campaign_locks ' +
20
+ `WHERE app_name = ${sqlText(sb.appName)} AND campaign_id = ${sqlText(id)}`);
21
+ return df.rowCount ? {ttl: df.get('ttl', 0), lockedBy: df.get('locked_by', 0)} : null;
22
+ }
23
+
24
+ /** A campaign on {@link designCsv} at version 1, open in [sessions] separate app instances. */
25
+ async function openShared(sb: Sandbox, sessions: number, extra: {[key: string]: unknown} = {}): Promise<HitDesignApp[]> {
26
+ const t = noComputeTemplate('ZZB3 Shared', 'ZZB3');
27
+ await sb.writeTemplate(t);
28
+ await sb.writeCampaign(designCampaign(sb, 'ZZB3-1', t, {version: 1, ...extra}), designCsv);
29
+ const apps: HitDesignApp[] = [];
30
+ for (let i = 0; i < sessions; i++) {
31
+ const app = await sb.hitDesign();
32
+ await sb.openDesign(app, 'ZZB3-1');
33
+ apps.push(app);
34
+ }
35
+ return apps;
36
+ }
37
+
38
+ /** The server table of the shared campaign, keyed by canonical SMILES; a molecule held twice fails. */
39
+ async function serverRows(sb: Sandbox): Promise<Map<string, {[col: string]: unknown}>> {
40
+ const df = await grok.dapi.files.readCsv(sb.savePath('ZZB3-1'));
41
+ const rows = new Map<string, {[col: string]: unknown}>();
42
+ for (let i = 0; i < df.rowCount; i++) {
43
+ const smiles = _package.convertToSmiles(df.get('Molecule', i));
44
+ if (rows.has(smiles))
45
+ throw new Error(`the server table holds ${smiles} twice`);
46
+ rows.set(smiles, Object.fromEntries(df.columns.names().map((c) => [c, df.get(c, i)])));
47
+ }
48
+ return rows;
49
+ }
50
+
51
+ const otherCsv = 'Molecule,Stage,V-iD,Note\nCCCC,Idea,,other\n';
52
+
53
+ /** A second campaign of the shared template, as files: what a test checks no save of the first one touched. */
54
+ async function writeOther(sb: Sandbox): Promise<() => Promise<void>> {
55
+ await sb.writeCampaign(designCampaign(sb, 'ZZB3-2', noComputeTemplate('ZZB3 Shared', 'ZZB3'),
56
+ {friendlyName: 'Other campaign', version: 1}), otherCsv);
57
+ const json = await sb.readCampaignText('ZZB3-2');
58
+ const csv = await grok.dapi.files.readAsText(sb.savePath('ZZB3-2'));
59
+ return async () => {
60
+ expect(await sb.readCampaignText('ZZB3-2'), json, 'ZZB3-2\'s campaign.json untouched');
61
+ expect(await grok.dapi.files.readAsText(sb.savePath('ZZB3-2')), csv, 'ZZB3-2\'s table untouched');
62
+ };
63
+ }
64
+
65
+ /** The view state of a table view over [csv] with a scatter plot of [column], after [edit] (say, closing its grid). */
66
+ function layoutOf(csv: string, column: string, edit: (tv: DG.TableView) => void = () => {}): string {
67
+ const tv = grok.shell.addTableView(DG.DataFrame.fromCsv(csv));
68
+ try {
69
+ tv.addViewer(DG.VIEWER.SCATTER_PLOT, {xColumnName: column, yColumnName: column});
70
+ edit(tv);
71
+ return tv.saveLayout().viewState;
72
+ } finally {
73
+ const df = tv.dataFrame;
74
+ tv.close();
75
+ grok.shell.closeTable(df);
76
+ }
77
+ }
78
+
79
+ type SessionInternals = {_session?: {openTracker(): {getButton(text: string): HTMLButtonElement | undefined}}};
80
+
81
+ function u2Button(name: string, text: string): HTMLButtonElement | undefined {
82
+ return Array.from(document.querySelectorAll<HTMLButtonElement>(`[data-u2-name="${name}"] button`))
83
+ .find((b) => b.textContent?.trim() === text);
84
+ }
85
+
86
+ /** A molfile as a sketcher draws it: a chain at angles no layout picks, so a save that redrew it would show. */
87
+ function drawn(atoms: [string, number, number][]): string {
88
+ const n = (v: number, width: number) => String(v).padStart(width);
89
+ return ['', ' ZZB3 drawn', '', `${n(atoms.length, 3)}${n(atoms.length - 1, 3)} 0 0 0 0 0 0 0 0999 V2000`,
90
+ ...atoms.map(([el, x, y]) => `${x.toFixed(4).padStart(10)}${y.toFixed(4).padStart(10)} 0.0000 ${el.padEnd(3)} 0 0 0 0 0 0 0 0 0 0 0 0`),
91
+ ...atoms.slice(1).map((_, i) => `${n(i + 1, 3)}${n(i + 2, 3)} 1 0 0 0 0`), 'M END', ''].join('\n');
92
+ }
93
+
94
+ const drawnEthanol = drawn([['C', 0.5, 1.25], ['C', 1.75, 0.4], ['O', 1.9, -1.1]]);
95
+ const drawnPropylamine = drawn([['C', 0, 0], ['C', 1.2, 0.9], ['C', 1.5, -0.6], ['N', 2.9, -0.3]]);
96
+ /** What OpenChemLib's sketcher gives on OK with nothing drawn. */
97
+ const emptySketch = '\nActelion Java MolfileCreator 1.0\n\n 0 0 0 0 0 0 0 0 0 0999 V2000\nM END\n';
98
+
99
+ const units = (app: HitDesignApp) => app.dataFrame!.col('Molecule')!.meta.units;
100
+
101
+ /** The template with the JS-only Chemical Properties compute, MW alone. */
102
+ const withMolWeight = (t: HitDesignTemplate): HitDesignTemplate => ({...t, compute: {...t.compute, functions: [
103
+ {name: 'addChemPropertiesColumns', package: 'Chem', args: {MW: true, HBA: false, HBD: false, logP: false, logS: false,
104
+ PSA: false, rotatableBonds: false, stereoCenters: false, moleculeCharge: false, molecularFormula: false}}]}});
105
+
106
+ /** The sketcher a campaign opens on its empty first row, closed once it is up. */
107
+ async function closeSketcher(): Promise<void> {
108
+ await waitUntil(() => DG.Dialog.getOpenDialogs().length > 0, 'the sketcher never opened on the empty row', 30000);
109
+ for (const d of DG.Dialog.getOpenDialogs())
110
+ d.close();
111
+ }
112
+
113
+ category('Save and lock', () => {
114
+ test('the campaign lock is exclusive and lasts 30 s', async () => {
115
+ const sb = await Sandbox.create('lock');
116
+ try {
117
+ const first = await acquire(sb, 'ZZB3-1', 'session A');
118
+ expect(first.rowCount, 1, 'the first acquire takes the lock');
119
+ const second = await acquire(sb, 'ZZB3-1', 'session B');
120
+ expect(second.rowCount, 0, 'a second acquire is refused while the lock is held');
121
+ const row = await lockRow(sb, 'ZZB3-1');
122
+ expect(row?.lockedBy, 'session A', 'locked_by');
123
+ expect(row!.ttl > 25 && row!.ttl <= 30.5, true, `the lock expires in 30 s, it has ${row!.ttl} s left`);
124
+ } finally {
125
+ await sb.dispose();
126
+ }
127
+ });
128
+
129
+ // The query's DELETE of the expired row and its INSERT share one snapshot, so the first call only clears the row and
130
+ // the save's retry 200 ms later takes the lock; the outcome pinned here holds with or without that extra round.
131
+ test('an expired lock is taken over by the next attempt at the latest', async () => {
132
+ const sb = await Sandbox.create('lock');
133
+ try {
134
+ await acquire(sb, 'ZZB3-1', 'session A');
135
+ await hitdesignSql(`WITH u AS (UPDATE hitdesign.campaign_locks SET expires_at = NOW() - INTERVAL '1 second' ` +
136
+ `WHERE app_name = ${sqlText(sb.appName)} RETURNING 1) SELECT COUNT(*) AS n FROM u`);
137
+ let taken = await acquire(sb, 'ZZB3-1', 'session B');
138
+ if (taken.rowCount === 0)
139
+ taken = await acquire(sb, 'ZZB3-1', 'session B');
140
+ expect(taken.rowCount, 1, 'the expired lock is replaced');
141
+ expect((await lockRow(sb, 'ZZB3-1'))?.lockedBy, 'session B', 'the new holder');
142
+ } finally {
143
+ await sb.dispose();
144
+ }
145
+ });
146
+
147
+ test('releasing the lock logs the save time that GetLastModified returns', async () => {
148
+ const sb = await Sandbox.create('lock');
149
+ try {
150
+ expect(await sb.lastModified('ZZB3-1'), null, 'no save logged yet');
151
+ await acquire(sb, 'ZZB3-1', 'session A');
152
+ const released = (await release(sb, 'ZZB3-1')).col('updated_at')!.getString(0);
153
+ expect(await sb.lastModified('ZZB3-1'), released, 'GetLastModified');
154
+ expect(await lockRow(sb, 'ZZB3-1'), null, 'the lock row is gone');
155
+ const again = await release(sb, 'ZZB3-1');
156
+ expect(again.rowCount, 0, 'releasing a lock nobody holds logs nothing');
157
+ expect(await sb.lastModified('ZZB3-1'), released, 'GetLastModified after the empty release');
158
+ } finally {
159
+ await sb.dispose();
160
+ }
161
+ });
162
+
163
+ test('two saves in sequence raise the version by one each and log each save', async () => {
164
+ const sb = await Sandbox.create('save');
165
+ try {
166
+ const [app] = await openShared(sb, 1);
167
+ await app.saveCampaign(false);
168
+ expect((await sb.readCampaign('ZZB3-1')).version, 2, 'version after the first save');
169
+ const t1 = await sb.lastModified('ZZB3-1');
170
+ await app.saveCampaign(false);
171
+ expect((await sb.readCampaign('ZZB3-1')).version, 3, 'version after the second save');
172
+ const t2 = await sb.lastModified('ZZB3-1');
173
+ expect(t1 != null && t2 != null && Date.parse(t2) > Date.parse(t1), true, `the save time moves on: ${t1} → ${t2}`);
174
+ expect(await lockRow(sb, 'ZZB3-1'), null, 'no lock left behind');
175
+ } finally {
176
+ await sb.dispose();
177
+ }
178
+ }, {timeout: 120000});
179
+
180
+ test('a save waits while another session holds the lock', async () => {
181
+ const sb = await Sandbox.create('save');
182
+ try {
183
+ const [app] = await openShared(sb, 1);
184
+ await acquire(sb, 'ZZB3-1', 'another session');
185
+ await countQueryCalls('AcquireCampaignLock', null, async (attempts) => {
186
+ const save = app.saveCampaign(false);
187
+ await waitUntil(() => attempts.length >= 3, `the save asked for the lock ${attempts.length} times`, 15000);
188
+ expect((await sb.readCampaign('ZZB3-1')).version, 1, 'nothing is written while the lock is held');
189
+ await release(sb, 'ZZB3-1');
190
+ await save;
191
+ });
192
+ expect((await sb.readCampaign('ZZB3-1')).version, 2, 'the save went through after the release');
193
+ } finally {
194
+ await sb.dispose();
195
+ }
196
+ }, {timeout: 120000});
197
+
198
+ test('a stale save adds the other session\'s new rows by canonical SMILES', async () => {
199
+ const sb = await Sandbox.create('save');
200
+ try {
201
+ const [a, b] = await openShared(sb, 2);
202
+ const score = a.dataFrame!.columns.addNewInt('Score');
203
+ score.set(0, 1);
204
+ score.set(1, 2);
205
+ addRows(a.dataFrame!, [{'Molecule': 'CCN', 'Stage': 'Idea', 'Score': 3}, {'Molecule': 'OCC', 'Stage': 'Idea', 'Score': 9}]);
206
+ await a.saveCampaign(false);
207
+ addRows(b.dataFrame!, [{Molecule: 'CCCl', Stage: 'Idea'}]);
208
+ await b.saveCampaign(false);
209
+
210
+ expect((await sb.readCampaign('ZZB3-1')).version, 3, 'the stale save goes past the other one');
211
+ const rows = await serverRows(sb);
212
+ expect(Array.from(rows.keys()).sort().join(' '), ['CCCl', 'CCN', 'CCO', 'c1ccccc1'].sort().join(' '),
213
+ 'rows: ours, plus the other session\'s new CCN; its OCC is our CCO');
214
+ expect(rows.get('CCO')!['Score'], 9, 'a new column is copied into the rows we share; of two rows of one molecule the later wins');
215
+ expect(rows.get('c1ccccc1')!['Score'], 2, 'Score of benzene');
216
+ expect(rows.get('CCN')!['Score'], 3, 'Score of the added row');
217
+ } finally {
218
+ await sb.dispose();
219
+ }
220
+ }, {timeout: 150000});
221
+
222
+ test('a view-only save is refused and writes nothing', async () => {
223
+ const sb = await Sandbox.create('save');
224
+ try {
225
+ const [app] = await openShared(sb, 1, {authorUserId: otherUserId, authorUserFriendlyName: 'Someone Else',
226
+ permissions: {view: [allUsers], edit: [unknownGroupId]}});
227
+ expect(app.canEdit, false, 'the campaign is view-only');
228
+ const json = await sb.readCampaignText('ZZB3-1');
229
+ const csv = await grok.dapi.files.readAsText(sb.savePath('ZZB3-1'));
230
+ app.dataFrame!.set('Note', 0, 'a local edit');
231
+ await app.saveCampaign(false);
232
+ expect(await sb.readCampaignText('ZZB3-1'), json, 'campaign.json unchanged');
233
+ expect(await grok.dapi.files.readAsText(sb.savePath('ZZB3-1')), csv, 'the table unchanged');
234
+ expect(hasBalloon('You do not have permission to modify this campaign'), true, 'the refusal is shown');
235
+ expect(await lockRow(sb, 'ZZB3-1'), null, 'no lock was taken');
236
+ expect(app.dataFrame!.get('Note', 0), 'a local edit', 'the local edit stays');
237
+ } finally {
238
+ await sb.dispose();
239
+ }
240
+ }, {timeout: 120000});
241
+
242
+ test('a new campaign takes the next free number of its template key', async () => {
243
+ const sb = await Sandbox.create('save');
244
+ try {
245
+ const t = noComputeTemplate('ZZB3 Codes', 'ZZB3');
246
+ await sb.writeTemplate(t);
247
+ const app = await sb.hitDesign();
248
+ const folder = `${sb.appName}/campaigns`;
249
+ expect(await app.getNewCampaignName(folder, 'ZZB3'), 'ZZB3-1', 'with no campaigns of the key');
250
+ for (const id of ['ZZB3-1', 'ZZB3-7', 'ZZB3-x', 'OTHER-9', 'ZZB3X-12'])
251
+ await sb.writeCampaign(designCampaign(sb, id, t), designCsv);
252
+ expect(await app.getNewCampaignName(folder, 'ZZB3'), 'ZZB3-8', 'the highest number + 1');
253
+ } finally {
254
+ await sb.dispose();
255
+ }
256
+ }, {timeout: 120000});
257
+
258
+ test('two sessions creating from one template get distinct codes', async () => {
259
+ const sb = await Sandbox.create('save');
260
+ try {
261
+ const t = noComputeTemplate('ZZB3 Race', 'ZZB3');
262
+ await sb.writeTemplate(t);
263
+ const a = await sb.hitDesign();
264
+ const b = await sb.hitDesign();
265
+ const ids = await Promise.all([startDesignCampaign(a, t, {Chemist: 'A'}, 'Race A', 'CCO'),
266
+ startDesignCampaign(b, t, {Chemist: 'B'}, 'Race B', 'CCN')]);
267
+ expectSame([...ids].sort(), ['ZZB3-1', 'ZZB3-2'], 'two codes of the key');
268
+ expect(await lockRow(sb, ids[0]) === null && await lockRow(sb, ids[1]) === null, true, 'no lock is left');
269
+ for (const [i, id] of ids.entries()) {
270
+ const saved = await sb.readCampaign(id);
271
+ expect(saved.friendlyName, i === 0 ? 'Race A' : 'Race B', `${id} name`);
272
+ const df = await grok.dapi.files.readCsv(saved.savePath);
273
+ expect(df.rowCount, 1, `${id} holds only its own row`);
274
+ expect(_package.convertToSmiles(df.get('Molecule', 0)), i === 0 ? 'CCO' : 'CCN', `${id} molecule`);
275
+ }
276
+ } finally {
277
+ await sb.dispose();
278
+ }
279
+ }, {timeout: 150000});
280
+
281
+ test('two Hit Triage sessions starting from one template get distinct codes', async () => {
282
+ const sb = await Sandbox.create('save');
283
+ try {
284
+ const t = {...triageTemplate('ZZB3 Triage Race', 'ZZB3'), dataSourceType: 'File' as const};
285
+ await sb.writeTemplate(t);
286
+ const [a, b] = [await sb.hitTriage(), await sb.hitTriage()];
287
+ const ids = await Promise.all([startTriageCampaign(a, t, 'CCO', 'Race A'), startTriageCampaign(b, t, 'CCN', 'Race B')]);
288
+ expectSame([...ids].sort(), ['ZZB3-1', 'ZZB3-2'], 'two codes of the key');
289
+ expect(await lockRow(sb, ids[0]) === null && await lockRow(sb, ids[1]) === null, true, 'no lock is left');
290
+ for (const [i, id] of ids.entries()) {
291
+ const saved = await sb.readCampaign(id);
292
+ expect(saved.friendlyName, i === 0 ? 'Race A' : 'Race B', `${id} name`);
293
+ const df = await grok.dapi.files.readCsv(saved.ingest.query);
294
+ expect(df.rowCount, 1, `${id} holds only its own row`);
295
+ expect(_package.convertToSmiles(df.get('smiles', 0)), i === 0 ? 'CCO' : 'CCN', `${id} molecule`);
296
+ }
297
+ } finally {
298
+ await sb.dispose();
299
+ }
300
+ }, {timeout: 150000});
301
+
302
+ test('a campaign that fails to open leaves the open one in place: its next save writes itself', async () => {
303
+ const sb = await Sandbox.create('save');
304
+ try {
305
+ const [app] = await openShared(sb, 1);
306
+ const t = noComputeTemplate('ZZB3 Shared', 'ZZB3');
307
+ await sb.writeCampaign(designCampaign(sb, 'ZZB3-2', t, {status: 'Broken', savePath: sb.savePath('ZZB3-2', 'elsewhere')}),
308
+ designCsv);
309
+ await app.infoView.setCampaign('ZZB3-2');
310
+ expect(hasBalloon('Campaign ZZB3-2 could not be opened'), true, 'the failed open says so');
311
+ expect(app.campaign?.name, 'ZZB3-1', 'the app still holds the open campaign');
312
+ app.dataFrame!.set('Note', 0, 'after the failed open');
313
+ await app.saveCampaign(false);
314
+ expect((await serverRows(sb)).get('CCO')!['Note'], 'after the failed open', 'the open campaign\'s table took the edit');
315
+ const own = await sb.readCampaign('ZZB3-1');
316
+ expect(own.savePath, sb.savePath('ZZB3-1'), 'its campaign.json keeps its own table');
317
+ expect(own.status, 'In Progress', 'and its own status');
318
+ expect(await grok.dapi.files.exists(sb.savePath('ZZB3-2', 'elsewhere')), false, 'nothing written where the broken one points');
319
+ } finally {
320
+ await sb.dispose();
321
+ }
322
+ }, {timeout: 120000});
323
+
324
+ test('Hit Triage: a campaign that fails to open leaves the open one saving as itself', async () => {
325
+ const sb = await Sandbox.create('save');
326
+ try {
327
+ const t = triageTemplate('ZZB3 Triage Open', 'ZZB3');
328
+ await sb.writeTemplate(t);
329
+ const campaign = (id: string, status: string, templateName: string) => ({name: id, templateName, filters: [],
330
+ ingest: {type: 'File', query: sb.ingestPath(id), molColName: 'smiles'}, status, createDate: '2024/10/17',
331
+ campaignFields: {Chemist: id}, columnSemTypes: {smiles: 'Molecule'}, columnTypes: {smiles: 'string'},
332
+ permissions: {view: [allUsers], edit: [allUsers]}});
333
+ await sb.writeCampaign(campaign('ZZB3-1', 'In Progress', t.name), 'smiles\nCCO\n');
334
+ await sb.writeCampaign(campaign('ZZB3-2', 'Broken', 'ZZB3 Gone Template'), 'smiles\nCCN\n');
335
+ const app = await sb.hitTriage();
336
+ await sb.openTriage(app, 'ZZB3-1');
337
+ await app.infoView.setCampaign('ZZB3-2');
338
+ expect(hasBalloon('Campaign ZZB3-2 could not be opened'), true, 'the failed open says so');
339
+ expect(app.campaign?.name, 'ZZB3-1', 'the app still holds the open campaign');
340
+ await app.saveCampaign(undefined, false);
341
+ const own = await sb.readCampaign('ZZB3-1');
342
+ expect(own.status, 'In Progress', 'its own status, not the broken one\'s');
343
+ expectSame(own.campaignFields, {Chemist: 'ZZB3-1'}, 'its own fields');
344
+ } finally {
345
+ await sb.dispose();
346
+ }
347
+ }, {timeout: 120000});
348
+
349
+ test('deleting a campaign removes its last save, its lock and its V-iD links', async () => {
350
+ const sb = await Sandbox.create('save');
351
+ try {
352
+ const t = noComputeTemplate('ZZB3 Doomed', 'ZZB3');
353
+ await sb.writeTemplate(t);
354
+ await sb.writeCampaign(designCampaign(sb, 'ZZB3-1', t), designCsv);
355
+ await acquire(sb, 'ZZB3-1', 'an earlier save');
356
+ await release(sb, 'ZZB3-1');
357
+ await acquire(sb, 'ZZB3-1', 'a session that went away');
358
+ await api.queries.addMolecule(obfuscateSmiles(_package.convertToSmiles(sb.ownMolecule('CCCCCCCCCO'))), sb.appName,
359
+ 'ZZB3-1', 'test');
360
+ const where = `WHERE app_name = ${sqlText(sb.appName)} AND campaign_id = 'ZZB3-1'`;
361
+ const rows = async () => (await hitdesignSql(`SELECT (SELECT COUNT(*) FROM hitdesign.update_logs ${where}) + ` +
362
+ `(SELECT COUNT(*) FROM hitdesign.campaign_locks ${where}) + (SELECT COUNT(*) FROM hitdesign.campaign_vids ${where}) AS n`))
363
+ .get('n', 0);
364
+ expect(await rows(), 3, 'a save logged, a lock held, a V-iD linked');
365
+ const app = await sb.hitDesign();
366
+ await app.infoView.deleteCampaignAndRefresh(sb.appName, 'ZZB3-1');
367
+ expect(await _package.files.exists(sb.path('ZZB3-1')), false, 'the campaign\'s files are gone');
368
+ expect(await rows(), 0, 'and its hitdesign rows');
369
+ } finally {
370
+ await sb.dispose();
371
+ }
372
+ }, {timeout: 120000});
373
+
374
+ test('dropping a lock without a save lets go only of the caller\'s own lock', async () => {
375
+ const sb = await Sandbox.create('save');
376
+ try {
377
+ await acquire(sb, 'ZZB3-1', 'session A');
378
+ await api.queries.dropCampaignLock(sb.appName, 'ZZB3-1', 'session B');
379
+ expect((await lockRow(sb, 'ZZB3-1'))?.lockedBy, 'session A', 'another session\'s lock stays');
380
+ await api.queries.dropCampaignLock(sb.appName, 'ZZB3-1', 'session A');
381
+ expect(await lockRow(sb, 'ZZB3-1'), null, 'the holder\'s drop takes it');
382
+ expect(await sb.lastModified('ZZB3-1'), null, 'and logs no save');
383
+ } finally {
384
+ await sb.dispose();
385
+ }
386
+ }, {timeout: 60000});
387
+
388
+ test('a stale save keeps the other session\'s edits to the rows both hold', async () => {
389
+ const sb = await Sandbox.create('save');
390
+ try {
391
+ const [a, b] = await openShared(sb, 2);
392
+ a.dataFrame!.set('Stage', 0, 'Tested');
393
+ await a.saveCampaign(false);
394
+ b.dataFrame!.set('Note', 1, 'edited by B');
395
+ b.dataFrame!.set('Note', 0, 'B wins a cell both edited');
396
+ a.dataFrame!.set('Note', 0, 'A edited it first');
397
+ await a.saveCampaign(false);
398
+ await b.saveCampaign(false);
399
+ const rows = await serverRows(sb);
400
+ expect(rows.get('c1ccccc1')!['Note'], 'edited by B', 'the stale session\'s own edit is saved');
401
+ expect(rows.get('CCO')!['Stage'], 'Tested', 'the other session\'s Stage edit of CCO is kept');
402
+ expect(rows.get('CCO')!['Note'], 'B wins a cell both edited', 'a cell both edited takes the later save');
403
+ } finally {
404
+ await sb.dispose();
405
+ }
406
+ }, {timeout: 150000});
407
+
408
+ test('a refused view-only save does not log a change', async () => {
409
+ const sb = await Sandbox.create('save');
410
+ try {
411
+ await acquire(sb, 'ZZB3-1', 'an earlier save');
412
+ await release(sb, 'ZZB3-1');
413
+ const before = await sb.lastModified('ZZB3-1');
414
+ const [app] = await openShared(sb, 1, {authorUserId: otherUserId, permissions: {view: [allUsers], edit: [unknownGroupId]}});
415
+ app.dataFrame!.set('Note', 0, 'a local edit');
416
+ await app.saveCampaign(false);
417
+ expect(hasBalloon('You do not have permission to modify this campaign'), true, 'the save was refused');
418
+ expect(await sb.lastModified('ZZB3-1'), before, 'update_logs stays as it was');
419
+ expect(await lockRow(sb, 'ZZB3-1'), null, 'no lock was taken');
420
+ } finally {
421
+ await sb.dispose();
422
+ }
423
+ }, {timeout: 120000});
424
+
425
+ test('a save whose table cannot be written lets the lock go and says why', async () => {
426
+ const sb = await Sandbox.create('save');
427
+ try {
428
+ const [app] = await openShared(sb, 1);
429
+ const before = await sb.lastModified('ZZB3-1');
430
+ const toCsv = DG.DataFrame.prototype.toCsv;
431
+ DG.DataFrame.prototype.toCsv = () => {
432
+ throw new Error('ZZB3 unwritable table');
433
+ };
434
+ let saved: unknown;
435
+ try {
436
+ saved = await app.saveCampaign(false);
437
+ } finally {
438
+ DG.DataFrame.prototype.toCsv = toCsv;
439
+ }
440
+ expect(saved === undefined, true, 'the save answers that nothing was saved');
441
+ expect(hasBalloon('Failed to save the campaign: ZZB3 unwritable table'), true, 'the failure is shown');
442
+ expect(app.isSaving, false, 'the save has ended');
443
+ expect(await lockRow(sb, 'ZZB3-1'), null, 'the lock is let go');
444
+ expect(await sb.lastModified('ZZB3-1'), before, 'nothing written, no save logged');
445
+ expect((await sb.readCampaign('ZZB3-1')).version, 1, 'campaign.json untouched');
446
+ expect(await app.saveCampaign(false) !== undefined, true, 'the next save goes through');
447
+ } finally {
448
+ await sb.dispose();
449
+ }
450
+ }, {timeout: 120000});
451
+
452
+ test('a save whose table the share refuses lets the lock go and logs no save', async () => {
453
+ const sb = await Sandbox.create('save');
454
+ try {
455
+ const [app] = await openShared(sb, 1);
456
+ const before = await sb.lastModified('ZZB3-1');
457
+ const files = Object.getPrototypeOf(grok.dapi.files);
458
+ const writeAsText = files.writeAsText;
459
+ files.writeAsText = function(file: DG.FileInfo | string, data: string) {
460
+ return file === sb.savePath('ZZB3-1') ? Promise.reject(new Error('ZZB3 share refused the table')) :
461
+ writeAsText.call(this, file, data);
462
+ };
463
+ let saved: unknown;
464
+ try {
465
+ saved = await app.saveCampaign(false);
466
+ } finally {
467
+ files.writeAsText = writeAsText;
468
+ }
469
+ expect(saved === undefined, true, 'the save answers that nothing was saved');
470
+ expect(hasBalloon('Failed to save the campaign: ZZB3 share refused the table'), true, 'the failure is shown');
471
+ expect(await lockRow(sb, 'ZZB3-1'), null, 'the lock is let go');
472
+ expect(await sb.lastModified('ZZB3-1'), before, 'nothing written, no save logged');
473
+ expect((await sb.readCampaign('ZZB3-1')).version, 1, 'campaign.json untouched');
474
+ } finally {
475
+ await sb.dispose();
476
+ }
477
+ }, {timeout: 120000});
478
+
479
+ test('saves asked for while one runs fold into one more write', async () => {
480
+ const sb = await Sandbox.create('save');
481
+ try {
482
+ const [app] = await openShared(sb, 1);
483
+ const {calls} = await countQueryCalls('ReleaseCampaignLock', null, async () => {
484
+ const first = app.saveCampaign(false);
485
+ app.dataFrame!.set('Note', 0, 'second save');
486
+ const second = app.saveCampaign(false);
487
+ app.dataFrame!.set('Note', 1, 'third save');
488
+ const third = app.saveCampaign(false);
489
+ expect(second === third, true, 'the third save is folded into the second');
490
+ expect(app.isSaving, true, 'saving while the first runs');
491
+ await first;
492
+ expect(app.isSaving, true, 'still saving: the folded save runs after the first');
493
+ await second;
494
+ expect(app.isSaving, false, 'done after the last');
495
+ });
496
+ expect(calls.length, 2, 'two writes for three saves');
497
+ expect((await sb.readCampaign('ZZB3-1')).version, 3, 'the version went up by two');
498
+ const rows = await serverRows(sb);
499
+ expect(rows.get('CCO')!['Note'], 'second save', 'the folded save wrote the second edit');
500
+ expect(rows.get('c1ccccc1')!['Note'], 'third save', 'and the third');
501
+ } finally {
502
+ await sb.dispose();
503
+ }
504
+ }, {timeout: 120000});
505
+
506
+ test('a save asked for while another campaign opens writes the campaign it was asked for', async () => {
507
+ const sb = await Sandbox.create('save');
508
+ const files = Object.getPrototypeOf(grok.dapi.files) as {readCsv: (...args: unknown[]) => Promise<DG.DataFrame>};
509
+ const readCsv = files.readCsv;
510
+ try {
511
+ const [app] = await openShared(sb, 1);
512
+ const untouched = await writeOther(sb);
513
+ let release!: () => void;
514
+ const gate = new Promise<void>((resolve) => release = resolve);
515
+ let reading = false;
516
+ files.readCsv = async function(this: unknown, ...args: unknown[]) {
517
+ if (args[0] === sb.savePath('ZZB3-2')) {
518
+ reading = true;
519
+ await gate;
520
+ }
521
+ return readCsv.apply(this, args);
522
+ };
523
+ app.dataFrame!.set('Note', 0, 'asked for mid-open');
524
+ const opening = app.infoView.setCampaign('ZZB3-2');
525
+ await waitUntil(() => reading, 'the open never read ZZB3-2\'s table', 30000);
526
+ const saved = await app.saveCampaign(false);
527
+ release();
528
+ await opening;
529
+ expect(saved?.name, 'ZZB3-1', 'the save answers the campaign it was asked for');
530
+ const own = await sb.readCampaign('ZZB3-1');
531
+ expect(own.friendlyName, 'Friendly ZZB3-1', 'ZZB3-1\'s campaign.json is its own');
532
+ expect(own.savePath, sb.savePath('ZZB3-1'), 'and points at its own table');
533
+ expect((await serverRows(sb)).get('CCO')!['Note'], 'asked for mid-open', 'ZZB3-1\'s table took the edit');
534
+ await untouched();
535
+ expect(app.campaign?.name, 'ZZB3-2', 'the open went on');
536
+ } finally {
537
+ files.readCsv = readCsv;
538
+ await sb.dispose();
539
+ }
540
+ }, {timeout: 150000});
541
+
542
+ test('a save queued behind one waiting for the lock writes its campaign though another opened meanwhile', async () => {
543
+ const sb = await Sandbox.create('save');
544
+ try {
545
+ const [app] = await openShared(sb, 1);
546
+ const untouched = await writeOther(sb);
547
+ await acquire(sb, 'ZZB3-1', 'another session');
548
+ app.dataFrame!.set('Note', 0, 'first save');
549
+ const first = app.saveCampaign(false);
550
+ app.dataFrame!.set('Note', 1, 'queued save');
551
+ const queued = app.saveCampaign(false);
552
+ await app.infoView.setCampaign('ZZB3-2');
553
+ expect(app.campaign?.name, 'ZZB3-2', 'ZZB3-2 opened while the saves waited');
554
+ await release(sb, 'ZZB3-1');
555
+ expect((await first)?.name, 'ZZB3-1', 'the first save');
556
+ expect((await queued)?.name, 'ZZB3-1', 'the queued save wrote the campaign it was asked for');
557
+ expect((await sb.readCampaign('ZZB3-1')).version, 3, 'two saves of ZZB3-1');
558
+ const rows = await serverRows(sb);
559
+ expect(rows.get('CCO')!['Note'], 'first save', 'the first edit');
560
+ expect(rows.get('c1ccccc1')!['Note'], 'queued save', 'the queued edit');
561
+ await untouched();
562
+ expect(app.campaign?.version, 1, 'the open campaign is ZZB3-2 as it was read');
563
+ } finally {
564
+ await sb.dispose();
565
+ }
566
+ }, {timeout: 150000});
567
+
568
+ test('a lock query that fails says why; only a lock another session keeps blames someone else', async () => {
569
+ const sb = await Sandbox.create('save');
570
+ const someoneElse = 'Someone else might be editing the campaign';
571
+ try {
572
+ const [app] = await openShared(sb, 1);
573
+ const lock = app as unknown as {aquireAndWaitCampaignLock: (id: string) => Promise<{aquired: boolean}>};
574
+ try {
575
+ lock.aquireAndWaitCampaignLock = async () => {
576
+ throw new Error('ZZB3 query refused');
577
+ };
578
+ expect(await app.saveCampaign(false) === undefined, true, 'nothing saved');
579
+ expect(hasBalloon('Failed to save the campaign: ZZB3 query refused'), true, 'the failure is shown with its cause');
580
+ expect(hasBalloon(someoneElse), false, 'nobody else is blamed');
581
+ lock.aquireAndWaitCampaignLock = async () => ({aquired: false});
582
+ expect(await app.saveCampaign(false) === undefined, true, 'nothing saved while the lock is kept');
583
+ expect(hasBalloon(someoneElse), true, 'a lock another session kept blames someone else');
584
+ } finally {
585
+ delete (lock as {aquireAndWaitCampaignLock?: unknown}).aquireAndWaitCampaignLock;
586
+ }
587
+ expect((await sb.readCampaign('ZZB3-1')).version, 1, 'campaign.json untouched');
588
+ } finally {
589
+ await sb.dispose();
590
+ }
591
+ }, {timeout: 120000});
592
+
593
+ test('a stale save keeps its own cells of a molecule two rows hold', async () => {
594
+ const sb = await Sandbox.create('save');
595
+ try {
596
+ const t = noComputeTemplate('ZZB3 Shared', 'ZZB3');
597
+ await sb.writeTemplate(t);
598
+ await sb.writeCampaign(designCampaign(sb, 'ZZB3-1', t, {version: 1, rowCount: 3}),
599
+ 'Molecule,Stage,V-iD,Note\nCCO,Idea,,cco-1\nOCC,Idea,,cco-2\nc1ccccc1,Made,,benzene\n');
600
+ const [a, b] = [await sb.hitDesign(), await sb.hitDesign()];
601
+ await sb.openDesign(a, 'ZZB3-1');
602
+ await sb.openDesign(b, 'ZZB3-1');
603
+ a.dataFrame!.set('Note', 1, 'A edited the second CCO');
604
+ a.dataFrame!.set('Note', 2, 'A edited benzene');
605
+ await a.saveCampaign(false);
606
+ b.dataFrame!.set('Stage', 0, 'Made');
607
+ await b.saveCampaign(false);
608
+ const df = await grok.dapi.files.readCsv(sb.savePath('ZZB3-1'));
609
+ expect(df.rowCount, 3, 'rows');
610
+ expect(df.get('Note', 0), 'cco-1', 'the first CCO row');
611
+ expect(df.get('Note', 1), 'cco-2', 'the second CCO row keeps ours: which of the other session\'s rows is it is a guess');
612
+ expect(df.get('Stage', 0), 'Made', 'our own edit');
613
+ expect(df.get('Note', 2), 'A edited benzene', 'a molecule one row holds takes the other session\'s edit');
614
+ } finally {
615
+ await sb.dispose();
616
+ }
617
+ }, {timeout: 150000});
618
+ });
619
+
620
+ category('Campaign view: saves', () => {
621
+ test('Modify Stages saves a layout without the progress tracker\'s Tile Viewer', async () => {
622
+ const sb = await Sandbox.create('save');
623
+ try {
624
+ const [app] = await openShared(sb, 1);
625
+ const session = (app as unknown as SessionInternals)._session!;
626
+ session.openTracker().getButton('Modify Stages')!.click();
627
+ await waitUntil(() => u2Button('modify-stages', 'OK') !== undefined, 'Modify Stages did not open', 10000);
628
+ u2Button('modify-stages', 'OK')!.click();
629
+ await waitUntil(() => app.campaign?.version === 2 && !app.isSaving, 'Modify Stages did not save', 30000);
630
+ const layout = (await sb.readCampaign('ZZB3-1')).layout;
631
+ expect(typeof layout, 'string', 'a layout is saved');
632
+ expect(layout.includes(`"${DG.VIEWER.TILE_VIEWER}"`), false, 'the saved layout has no Tile Viewer');
633
+ expect(Array.from(app.designView!.viewers).some((v) => v.type === DG.VIEWER.TILE_VIEWER), true,
634
+ 'the tracker shows its lanes again');
635
+ } finally {
636
+ await sb.dispose();
637
+ }
638
+ }, {timeout: 120000});
639
+
640
+ test('a campaign whose layout has no grid opens with one, and its edits still save', async () => {
641
+ const sb = await Sandbox.create('save');
642
+ try {
643
+ const layout = layoutOf(designCsv, 'Note', (tv) => tv.grid.close());
644
+ expect(layout.includes('"Grid"'), false, 'the layout has no grid');
645
+ const [app] = await openShared(sb, 1, {layout});
646
+ const view = app.designView!;
647
+ expect(view.grid != null, true, 'the view has a grid');
648
+ view.grid.cell('Stage', 0).setValue('Tested', true);
649
+ await waitUntil(() => app.campaign?.version === 2 && !app.isSaving, 'the Stage edit was not saved', 30000);
650
+ expect((await serverRows(sb)).get('CCO')!['Stage'], 'Tested', 'the edit is in the saved table');
651
+ } finally {
652
+ await sb.dispose();
653
+ }
654
+ }, {timeout: 120000});
655
+
656
+ test('Calculate additional properties: OK keeps the campaign\'s compute as the editor reads it, and saves', async () => {
657
+ const sb = await Sandbox.create('save');
658
+ try {
659
+ const compute = {descriptors: {enabled: true, args: ['MolWt']}, functions: [], scripts: [], queries: []};
660
+ const t = {...noComputeTemplate('ZZB3 Shared', 'ZZB3'), compute};
661
+ await sb.writeTemplate(t);
662
+ await sb.writeCampaign(designCampaign(sb, 'ZZB3-1', t, {version: 1}), designCsv);
663
+ const app = await sb.hitDesign();
664
+ await sb.openDesign(app, 'ZZB3-1');
665
+ app.editCompute();
666
+ await waitUntil(() => u2Button('compute', 'OK')?.disabled === false, 'the compute dialog never let OK go', 30000);
667
+ u2Button('compute', 'OK')!.click();
668
+ await waitUntil(() => app.campaign?.version === 2 && !app.isSaving, 'the campaign was not saved', 30000);
669
+ expectSame((await sb.readCampaign('ZZB3-1')).template.compute, compute, 'the stored compute');
670
+ } finally {
671
+ await sb.dispose();
672
+ }
673
+ }, {timeout: 120000});
674
+
675
+ test('PeptiHit: a column only the layout binds is not saved while it is empty', async () => {
676
+ const sb = await Sandbox.create('save');
677
+ try {
678
+ const csv = 'Helm,Molecule,Stage,V-iD\nPEPTIDE1{A.G.L.V.K}$$$$V2.0,CC(N)C(=O)O,Design,\n';
679
+ const t = {...noComputeTemplate('ZZB3 Peptides', 'ZZB3'), stages: ['Design', 'Synthesis'], layoutViewState:
680
+ layoutOf('Helm,Molecule,Stage,V-iD,MolWt\nPEPTIDE1{A.G.L.V.K}$$$$V2.0,CC(N)C(=O)O,Design,,71.08\n', 'MolWt')};
681
+ await sb.writeTemplate(t);
682
+ const campaign = {name: 'ZZB3-1', templateName: t.name, status: 'In Progress', createDate: '2024/9/4',
683
+ campaignFields: {Chemist: 'Davit'}, columnSemTypes: {'Helm': 'Macromolecule', 'Molecule': 'Molecule'},
684
+ columnTypes: {'Helm': 'string', 'Molecule': 'string', 'Stage': 'string', 'V-iD': 'string'}, rowCount: 1,
685
+ filteredRowCount: 1, savePath: sb.savePath('ZZB3-1'), version: 1, permissions: {view: [allUsers], edit: [allUsers]},
686
+ template: t};
687
+ await sb.writeCampaign(campaign, csv);
688
+ const app = await sb.peptiHit();
689
+ await sb.openDesign(app, 'ZZB3-1');
690
+ expect(app.dataFrame!.columns.contains('MolWt'), true, 'the layout\'s scatter plot has its column, empty');
691
+ await app.saveCampaign(false);
692
+ const df = await grok.dapi.files.readCsv(sb.savePath('ZZB3-1'));
693
+ expectSame(df.columns.names(), ['Helm', 'Molecule', 'Stage', 'V-iD'], 'the saved table\'s columns');
694
+ const after = await sb.readCampaign('ZZB3-1');
695
+ expect('MolWt' in after.columnTypes || 'MolWt' in after.columnSemTypes || 'MolWt' in after.columnTags, false,
696
+ 'campaign.json does not name it');
697
+ const again = await sb.peptiHit();
698
+ await sb.openDesign(again, 'ZZB3-1');
699
+ expect(again.dataFrame!.columns.contains('MolWt'), true, 'reopened, the saved layout\'s column is back, empty');
700
+ } finally {
701
+ await sb.dispose();
702
+ }
703
+ }, {timeout: 180000});
704
+
705
+ test('the Stage cells offer the template\'s stages: set on open over a stored copy, changed by Modify Stages, never saved', async () => {
706
+ const sb = await Sandbox.create('save');
707
+ try {
708
+ const [app] = await openShared(sb, 1, {columnTags: {Stage: {[DG.TAGS.CHOICES]: '["Old"]'}}});
709
+ const choices = (a: HitDesignApp) => a.dataFrame!.col('Stage')!.getTag(DG.TAGS.CHOICES);
710
+ expect(choices(app), JSON.stringify(['Idea', 'Made', 'Tested']), 'the template\'s stages, not the stored copy');
711
+ await app.setStages(['Idea', 'Made', 'Tested', 'Shipped']);
712
+ expect(choices(app), JSON.stringify(['Idea', 'Made', 'Tested', 'Shipped']), 'Modify Stages changes them');
713
+ const saved = await sb.readCampaign('ZZB3-1');
714
+ expect(saved.version, 2, 'Modify Stages saved');
715
+ expect(DG.TAGS.CHOICES in (saved.columnTags.Stage ?? {}), false, 'campaign.json keeps no copy');
716
+ expect(saved.layout.includes(DG.TAGS.CHOICES), false, 'nor does its layout');
717
+ const again = await sb.hitDesign();
718
+ await sb.openDesign(again, 'ZZB3-1');
719
+ expect(choices(again), JSON.stringify(['Idea', 'Made', 'Tested', 'Shipped']), 'reopened, from the saved template');
720
+ } finally {
721
+ await sb.dispose();
722
+ }
723
+ }, {timeout: 120000});
724
+
725
+ test('a reopened number column shows as the grid shows numbers, unless the campaign chose its format', async () => {
726
+ const sb = await Sandbox.create('save');
727
+ try {
728
+ const t = noComputeTemplate('ZZB3 Shared', 'ZZB3');
729
+ await sb.writeTemplate(t);
730
+ const readerFormat = `0.${'0'.repeat(13)}`;
731
+ await sb.writeCampaign(designCampaign(sb, 'ZZB3-1', t, {version: 1, rowCount: 1,
732
+ columnTypes: {...designColumns.columnTypes, MW: 'double', Score: 'double', Old: 'double'},
733
+ columnTags: {Score: {format: '0.000'}, Old: {'format': readerFormat, '.source-precision': '13'}}}),
734
+ 'Molecule,Stage,V-iD,Note,MW,Score,Old\nCCO,Idea,,first,446.9100036621094,1.5,4.2755999565124\n');
735
+ const app = await sb.hitDesign();
736
+ await sb.openDesign(app, 'ZZB3-1');
737
+ const df = app.dataFrame!;
738
+ expect(df.col('MW')!.getTag(DG.TAGS.FORMAT), null, 'MW carries no format the CSV reader made up');
739
+ expect(df.col('MW')!.getString(0), '446.91', 'MW shows as it did when it was calculated');
740
+ expect(df.col('Old')!.getTag(DG.TAGS.FORMAT), null, 'nor one an earlier save kept');
741
+ expect(df.col('Score')!.getTag(DG.TAGS.FORMAT), '0.000', 'the campaign\'s own format stays');
742
+ await app.saveCampaign(false);
743
+ const tags = (await sb.readCampaign('ZZB3-1')).columnTags;
744
+ expect(DG.TAGS.FORMAT in tags.MW || DG.TAGS.SOURCE_PRECISION in tags.MW, false, 'the save keeps no reader format');
745
+ expect(DG.TAGS.FORMAT in tags.Old, false, 'nor the one an earlier save kept');
746
+ expect(tags.Score.format, '0.000', 'and keeps the campaign\'s own');
747
+ } finally {
748
+ await sb.dispose();
749
+ }
750
+ }, {timeout: 120000});
751
+
752
+ test('a new campaign\'s Molecule column is molblock: a drawn molecule is registered, calculated, saved and reopened as drawn', async () => {
753
+ const sb = await Sandbox.create('save');
754
+ try {
755
+ const t = withMolWeight(noComputeTemplate('ZZB3 Molblock', 'ZZB3'));
756
+ await sb.writeTemplate(t);
757
+ const app = await sb.hitDesign();
758
+ const id = await startDesignCampaign(app, t, {Chemist: 'Ann'}, undefined, drawnEthanol);
759
+ expect(units(app), DG.UNITS.Molecule.MOLBLOCK, 'the new campaign\'s units');
760
+ expect((await sb.readCampaign(id)).columnTags.Molecule.units, DG.UNITS.Molecule.MOLBLOCK, 'the units campaign.json keeps');
761
+ expect((await grok.dapi.files.readCsv(sb.savePath(id))).get('Molecule', 0), drawnEthanol, 'the molblock it started with, saved as it is');
762
+ app.designView!.grid.cell('Molecule', 0).setValue(drawnPropylamine, true);
763
+ await waitUntil(() => app.campaign?.version === 2 && !app.isSaving, 'the drawn molecule was not saved', 60000);
764
+ const vid = app.dataFrame!.get('V-iD', 0);
765
+ expect(/^V\d{6}$/.test(vid), true, `the V-iD registered: ${vid}`);
766
+ expect(Math.round(app.dataFrame!.get('MW', 0)), 59, 'the MW calculated');
767
+ const saved = await grok.dapi.files.readCsv(sb.savePath(id));
768
+ expect(saved.get('Molecule', 0), drawnPropylamine, 'the molblock saved as drawn');
769
+ expect(saved.get('V-iD', 0), vid, 'the V-iD saved');
770
+ const again = await sb.hitDesign();
771
+ await sb.openDesign(again, id);
772
+ expect(units(again), DG.UNITS.Molecule.MOLBLOCK, 'the units reopened');
773
+ expect(again.dataFrame!.get('Molecule', 0), drawnPropylamine, 'the molecule reopened as drawn');
774
+ expect(again.dataFrame!.get('V-iD', 0), vid, 'the V-iD reopened');
775
+ } finally {
776
+ await sb.dispose();
777
+ }
778
+ }, {timeout: 150000});
779
+
780
+ test('a new campaign saved before anything is drawn reopens molblock; an empty sketch is neither registered nor calculated', async () => {
781
+ const sb = await Sandbox.create('save');
782
+ try {
783
+ const t = withMolWeight(noComputeTemplate('ZZB3 Molblock', 'ZZB3'));
784
+ await sb.writeTemplate(t);
785
+ const app = await sb.hitDesign();
786
+ const id = await startDesignCampaign(app, t, {Chemist: 'Ann'}, undefined, '');
787
+ await closeSketcher();
788
+ expect((await sb.readCampaign(id)).columnTags.Molecule.units, DG.UNITS.Molecule.MOLBLOCK, 'the units campaign.json keeps');
789
+ const again = await sb.hitDesign();
790
+ await sb.openDesign(again, id);
791
+ await closeSketcher();
792
+ expect(units(again), DG.UNITS.Molecule.MOLBLOCK, 'the empty column reopened');
793
+ again.dataFrame!.set('Molecule', 0, emptySketch);
794
+ await again.registerRow(0);
795
+ await again.performSingleCellCalculations(0, emptySketch);
796
+ expect(again.dataFrame!.col('V-iD')!.isNone(0), true, 'no V-iD for an empty sketch');
797
+ expect(again.dataFrame!.columns.contains('MW'), false, 'no MW calculated for an empty sketch');
798
+ expect(again.isSaving || again.campaign?.version !== 1, false, 'nothing saved');
799
+ } finally {
800
+ await sb.dispose();
801
+ }
802
+ }, {timeout: 150000});
803
+
804
+ test('an existing SMILES campaign keeps its SMILES and its units through an open and a save', async () => {
805
+ const sb = await Sandbox.create('save');
806
+ try {
807
+ const t = noComputeTemplate('ZZB3 Shared', 'ZZB3');
808
+ await sb.writeTemplate(t);
809
+ const smilesTags = {'quality': 'Molecule', 'units': DG.UNITS.Molecule.SMILES, 'cell.renderer': 'Molecule'};
810
+ await sb.writeCampaign(designCampaign(sb, 'ZZB3-1', t, {version: 1, columnTags: {Molecule: smilesTags}}), designCsv);
811
+ // the shape of a campaign saved before campaign.json kept column tags (DMT1-1): its units stay unset
812
+ await sb.writeCampaign(designCampaign(sb, 'ZZB3-2', t, {version: 1}), designCsv);
813
+ for (const [id, expected] of [['ZZB3-1', DG.UNITS.Molecule.SMILES], ['ZZB3-2', null]]) {
814
+ const app = await sb.hitDesign();
815
+ await sb.openDesign(app, id!);
816
+ expect(units(app) ?? null, expected, `${id} units on open`);
817
+ await app.saveCampaign(false);
818
+ expect((await sb.readCampaign(id!)).columnTags.Molecule.units ?? null, expected, `${id} units saved`);
819
+ expectSame((await grok.dapi.files.readCsv(sb.savePath(id!))).col('Molecule')!.toList(), ['CCO', 'c1ccccc1'], `${id} molecules saved`);
820
+ }
821
+ } finally {
822
+ await sb.dispose();
823
+ }
824
+ }, {timeout: 150000});
825
+
826
+ test('a SMILES file merged into a molblock campaign matches its molecules by canonical SMILES', async () => {
827
+ const sb = await Sandbox.create('save');
828
+ try {
829
+ const t = noComputeTemplate('ZZB3 Molblock', 'ZZB3');
830
+ await sb.writeTemplate(t);
831
+ const app = await sb.hitDesign();
832
+ await startDesignCampaign(app, t, {Chemist: 'Ann'}, undefined, drawnEthanol);
833
+ await mergeIntoCampaign(app, DG.DataFrame.fromCsv('Molecule,Note\nOCC,merged\nCCN,new\n'), {mode: 'smiles',
834
+ molColName: 'Molecule', addNewRows: true, runComputeOnNewRows: false, clashStrategy: 'overwrite'});
835
+ const df = app.dataFrame!;
836
+ expect(df.rowCount, 2, 'the matched row kept, the new molecule added');
837
+ expect(df.get('Molecule', 0), drawnEthanol, 'the drawn molecule kept as drawn');
838
+ expect(df.get('Note', 0), 'merged', 'OCC matched the drawn ethanol');
839
+ expect(df.get('Molecule', 1), 'CCN', 'the new molecule');
840
+ expect(/^V\d{6}$/.test(df.get('V-iD', 1)), true, `the new molecule's V-iD: ${df.get('V-iD', 1)}`);
841
+ expect(units(app), DG.UNITS.Molecule.MOLBLOCK, 'the units after the merge');
842
+ } finally {
843
+ await sb.dispose();
844
+ }
845
+ }, {timeout: 150000});
846
+
847
+ test('PeptiHit: the molecule a HELM converts to is a molblock, saved and reopened as it is', async () => {
848
+ const sb = await Sandbox.create('save');
849
+ try {
850
+ const t = {...noComputeTemplate('ZZB3 Peptides', 'ZZB3'), stages: ['Design', 'Synthesis']};
851
+ await sb.writeTemplate(t);
852
+ const helm = 'PEPTIDE1{A.G.L}$$$$V2.0';
853
+ const app = await sb.peptiHit();
854
+ const id = await startDesignCampaign(app, t, {Chemist: 'Ann'}, undefined, helm);
855
+ expect(units(app), DG.UNITS.Molecule.MOLBLOCK, 'the new campaign\'s units');
856
+ await app.performSingleCellCalculations(0, helm);
857
+ await waitUntil(() => app.campaign?.version === 2 && !app.isSaving, 'the converted molecule was not saved', 60000);
858
+ const mol = app.dataFrame!.get('Molecule', 0);
859
+ expect(_package.convertToSmiles(mol) !== '' && mol.includes('M END'), true, `a molblock of the HELM: ${mol}`);
860
+ expect((await grok.dapi.files.readCsv(sb.savePath(id))).get('Molecule', 0), mol, 'the molblock saved as it is');
861
+ const again = await sb.peptiHit();
862
+ await sb.openDesign(again, id);
863
+ expect(units(again), DG.UNITS.Molecule.MOLBLOCK, 'the units reopened');
864
+ expect(again.dataFrame!.get('Molecule', 0), mol, 'the molecule reopened as it is');
865
+ } finally {
866
+ await sb.dispose();
867
+ }
868
+ }, {timeout: 180000});
869
+ });
870
+
871
+ /** Each card of the open progress tracker: the V-iD it shows, its structure's picture, its element. */
872
+ function trackerCards(): {vid: string, picture: string, card: Element}[] {
873
+ return Array.from(document.querySelectorAll('[data-u2-name="progress-tracker"] .d4-tile-viewer-form')).map((card) => ({
874
+ vid: Array.from(card.querySelectorAll('input')).map((i) => i.value).find((v) => /^ZV\d$/.test(v)) ?? '',
875
+ picture: card.querySelector('canvas')?.toDataURL() ?? '',
876
+ card,
877
+ }));
878
+ }
879
+
880
+ const picturesByVid = (cards: {vid: string, picture: string}[]) =>
881
+ cards.map((c) => `${c.vid}:${c.picture.length}:${c.picture.slice(-48)}`).sort().join(' | ');
882
+
883
+ category('Campaign view: tracker', () => {
884
+ test('a card the tracker refills for another row shows that row\'s structure', async () => {
885
+ const sb = await Sandbox.create('tracker');
886
+ try {
887
+ const t = noComputeTemplate('ZZB3 Shared', 'ZZB3');
888
+ await sb.writeTemplate(t);
889
+ await sb.writeCampaign(designCampaign(sb, 'ZZB3-1', t, {version: 1, rowCount: 3}),
890
+ 'Molecule,Stage,V-iD,Note\nCCO,Idea,ZV1,a\nc1ccccc1,Idea,ZV2,b\nCCN,Made,ZV3,c\n');
891
+ const app = await sb.hitDesign();
892
+ const view = await sb.openDesign(app, 'ZZB3-1');
893
+ (app as unknown as SessionInternals)._session!.openTracker();
894
+ let last = '';
895
+ await waitUntil(() => {
896
+ const cards = trackerCards();
897
+ const now = picturesByVid(cards);
898
+ const settled = cards.length === 3 && cards.every((c) => c.vid !== '' && c.picture !== '') && now === last;
899
+ last = now;
900
+ return settled;
901
+ }, 'the tracker\'s three cards were not drawn', 20000);
902
+ const before = last;
903
+ const hosts = trackerCards().map((c) => c.card);
904
+ // the lanes laid out again: the cards go to the spare ones and come back refilled for other rows
905
+ view.dataFrame.rows.requestFilter();
906
+ await waitUntil(() => trackerCards().every((c) => !hosts.includes(c.card)), 'the lanes were not laid out again', 10000);
907
+ await waitUntil(() => picturesByVid(trackerCards()) === before,
908
+ `a refilled card shows another row's structure: ${picturesByVid(trackerCards())} vs ${before}`, 10000);
909
+ } finally {
910
+ await sb.dispose();
911
+ }
912
+ }, {timeout: 120000});
913
+
914
+ test('closing the campaign view with the tracker open keeps its moves, and saves them', async () => {
915
+ const sb = await Sandbox.create('tracker');
916
+ try {
917
+ const [app] = await openShared(sb, 1);
918
+ (app as unknown as SessionInternals)._session!.openTracker();
919
+ await waitUntil(() => u2Button('progress-tracker', 'CLOSE') !== undefined, 'the tracker did not open', 10000);
920
+ expect(u2Button('progress-tracker', 'CANCEL') === undefined && u2Button('progress-tracker', 'OK') === undefined, true,
921
+ 'CLOSE is the tracker\'s one action');
922
+ const df = app.dataFrame!;
923
+ df.set('Stage', 0, 'Tested');
924
+ app.designView!.close();
925
+ await waitUntil(() => app.campaign?.version === 2 && !app.isSaving, 'the move was not saved', 30000);
926
+ expect(df.get('Stage', 0), 'Tested', 'the move stays in the table');
927
+ expect((await serverRows(sb)).get('CCO')!['Stage'], 'Tested', 'the move is in the saved table');
928
+ } finally {
929
+ await sb.dispose();
930
+ }
931
+ }, {timeout: 120000});
932
+ });