Repository navigation
Expand file tree
/
Copy pathtasks.py
More file actions
executable file
·1162 lines (1052 loc) · 39.6 KB
/
Copy pathtasks.py
File metadata and controls
executable file
·1162 lines (1052 loc) · 39.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# tasks.py -- CGI script for Apache. task stack tracker, main view
# Permissions: Public read, write access requires HTTP Basic Auth.
#
# All data are stored as JSON files, here's an overview of the `tasks.json`
# structure:
#
# ```json
# {
# "current": { "id": "...", "name": "...", "notes": "...", "created_at": "...", "label": "Juno" },
# "idle_active": false,
# "idle_notes": "",
# "labels": [ "Juno", "TRACERS", "Admin" ],
# "queue": [ { "id": "...", "name": "...", "notes": "...", "created_at": "...", "label": "Juno" } ]
# }
#
#
# `queue[0]` is the highest priority waiting task. `current` is what is being
# worked on right now. When `idle_active` is true the Idle state is active and
# `current` is null.
#
# `labels` is the master list of charge-account-style label strings (max 32 chars
# each). Tasks carry an optional `label` field referencing one of these. Labels
# are stored on the task itself, so completed tasks in done_YYYY.json retain their
# label even if the label is later removed from the master list.
#
# `done_YYYY.json` is a flat array of completed task objects, each with
# `name`, `notes`, `created_at`, and `completed_at` fields.
#
# AI Disclosure:
# This code was generated in cooperation with Claude, which is an Artificial
# Intelligence service provided by Anthropic. Though design and development was
# orchestrated by a human, reviewed by a human and tested by a human, most of
# the actual code was composed by an AI.
#
# It is completely reasonable to forbid AI generated software in some contexts.
# Please check the contribution guidelines of any projects you participate in.
# If the project has a rule against AI generated software then DO NOT INCLUDE
# THIS FILE, in whole or in part, in your patches or pull requests.
import urllib.parse
import json
import os
import sys
import html
import uuid
from datetime import datetime, timezone
# ########################################################################### #
# configuration #
# current state of insanity
TASKS_FILE = os.environ.get('INTR_TASKS_FILE', '/var/www/taskdata/tasks.json')
# Memorial for adventures of yore
DONE_DIR = os.environ.get('INTR_DONE_DIR', '/var/www/taskdata')
# Tokens to help the two scripts link to each other, assuming same relative path
#
# ScriptAlias /some/url/path/tasks "/var/www/cgi-bin/tasks.py"
# ScriptAlias /some/url/path/intr-auth/tasks "/var/www/cgi-bin/tasks.py"
#
# ScriptAlias /some/url/path/done "/var/www/cgi-bin/done.py"
# ScriptAlias /some/url/path/intr-auth/done "/var/www/cgi-bin/done.py"
#
# So in the case above TASK_PATH_TOK would be "tasks" and the done token
# would be "done". I prefer to use 'intr' and 'handled', so that's what's
# in the readme.
TASKS_SCRIPT_NAME = 'intr'
DONE_SCRIPT_NAME = 'handled'
# ########################################################################### #
# Label color palette #
# #
# Each entry: 'name': ('#background', '#foreground') #
# Order here is the order shown in the color picker. #
# Downstream folks: add, remove, or recolor entries freely. The name string #
# is what gets stored in tasks.json, so renaming an entry here will cause #
# existing tasks carrying that name to fall back to the default amber style. #
LABEL_COLORS = {
'amber': ('#fdf3dc', '#7a5c10'),
'rose': ('#fde8e8', '#8b2020'),
'sage': ('#e6f2e6', '#2a5c2a'),
'sky': ('#dff0fb', '#1a527a'),
'lavender': ('#ede8f8', '#4a2d8a'),
'mint': ('#dff5ef', '#185c40'),
'steel': ('#e4eaf2', '#2a3d5c'),
'lilac': ('#f5e8f5', '#6a1a6a'),
'sand': ('#f2eedf', '#4a3d10'),
'peach': ('#fdeede', '#7a3a10'),
}
# Default color applied to labels that predate this feature, or whose stored
# color name no longer appears in LABEL_COLORS (e.g. after a rename).
LABEL_COLOR_DEFAULT = 'amber'
# ########################################################################### #
# remove cgi module dependency #
def get_post_form():
length = int(os.environ.get('CONTENT_LENGTH', 0) or 0)
body = sys.stdin.buffer.read(length).decode('utf-8', errors='replace')
pairs = urllib.parse.parse_qs(body, keep_blank_values=True)
# parse_qs returns lists; wrap it to mimic FieldStorage.getvalue()
class SimpleForm:
def getvalue(self, key, default=None):
vals = pairs.get(key)
return vals[0] if vals else default
return SimpleForm()
# ########################################################################### #
# Operation and Data model
#
# tasks.json structure:
# {
# "current": {id, name, notes, created_at} | null,
# "idle_notes": "string",
# "idle_active": true|false,
# "queue": [ {id, name, notes, created_at}, ... ]
# }
#
# "current" is the task being actively worked on.
# "idle_active" true means Idle is the current state (no task selected).
# "queue" is the ordered priority list, index 0 = highest priority.
def load_tasks():
if not os.path.exists(TASKS_FILE):
return {"current": None, "idle_notes": "", "idle_active": True, "labels": [], "queue": []}
data = json.load(open(TASKS_FILE, 'r'))
# Migrate v1: files that predate the labels field entirely.
if "labels" not in data:
data["labels"] = []
# Migrate v2: labels were plain strings; promote to {name, color} dicts.
data["labels"] = [
lbl if isinstance(lbl, dict) else {"name": lbl, "color": LABEL_COLOR_DEFAULT}
for lbl in data["labels"]
]
return data
def save_tasks(data):
os.makedirs(os.path.dirname(TASKS_FILE), exist_ok=True)
tmp = TASKS_FILE + '.tmp'
with open(tmp, 'w') as f:
json.dump(data, f, indent='\t')
os.replace(tmp, TASKS_FILE)
def done_file():
year = datetime.now().year
return os.path.join(DONE_DIR, f'done_{year}.json')
def load_done():
path = done_file()
if not os.path.exists(path):
return []
with open(path, 'r') as f:
return json.load(f)
def save_done(entries):
os.makedirs(DONE_DIR, exist_ok=True)
path = done_file()
tmp = path + '.tmp'
with open(tmp, 'w') as f:
json.dump(entries, f, indent='\t')
os.replace(tmp, path)
def new_task(name, notes, label='', label_color=''):
task = {
"id": str(uuid.uuid4()),
"name": name.strip(),
"notes": notes.strip(),
"created_at": datetime.now(timezone.utc).isoformat()
}
if label:
task["label"] = label
task["label_color"] = label_color or LABEL_COLOR_DEFAULT
return task
def is_authenticated():
# Apache sets REMOTE_USER when HTTP auth succeeds.
return bool(os.environ.get('REMOTE_USER'))
def duration_str(created_at_iso):
# Human-readable time-in-stack from ISO timestamp to now.
try:
created = datetime.fromisoformat(created_at_iso)
if created.tzinfo is None:
created = created.replace(tzinfo=timezone.utc)
delta = datetime.now(timezone.utc) - created
days = delta.days
if days == 0:
hours = delta.seconds // 3600
return f"{hours}h" if hours else "<1h"
elif days < 14:
return f"{days}d"
elif days < 60:
return f"{days // 7}w"
else:
return f"{days // 30}mo"
except Exception:
return "?"
def seconds_to_str(secs):
# Human-readable duration from a raw second count.
if secs < 60:
return "<1m"
elif secs < 3600:
return f"{secs // 60}m"
days = secs // 86400
if days == 0:
return f"{secs // 3600}h"
elif days < 14:
return f"{days}d"
elif days < 60:
return f"{days // 7}w"
else:
return f"{days // 30}mo"
def task_active_seconds(task):
# Total seconds a task has spent in the current slot, including the
# ongoing activation if active_since is set. Returns 0 for tasks
# that have never been made current (queue-only tasks).
total = task.get('time_active', 0)
active_since = task.get('active_since')
if active_since:
try:
t = datetime.fromisoformat(active_since)
if t.tzinfo is None:
t = t.replace(tzinfo=timezone.utc)
total += int((datetime.now(timezone.utc) - t).total_seconds())
except Exception:
pass
return total
def activate_task(task):
# Stamp active_since on a task entering the current slot.
task['active_since'] = datetime.now(timezone.utc).isoformat()
def deactivate_task(task):
# Accumulate active time and clear active_since when leaving current slot.
active_since = task.pop('active_since', None)
if active_since:
try:
t = datetime.fromisoformat(active_since)
if t.tzinfo is None:
t = t.replace(tzinfo=timezone.utc)
elapsed = int((datetime.now(timezone.utc) - t).total_seconds())
task['time_active'] = task.get('time_active', 0) + elapsed
except Exception:
pass
def h(s):
# HTML-escape a string.
return html.escape(str(s) if s else '', quote=True)
def _label_colors(color_name):
"""Return (bg, fg) hex pair for a color name, falling back to default."""
return LABEL_COLORS.get(color_name, LABEL_COLORS[LABEL_COLOR_DEFAULT])
def label_select(labels, selected='', field_name='label'):
"""Render a <select> dropdown for label choice. Empty option = no label.
Labels is a list of {name, color} dicts."""
out = [f'<select name="{field_name}">']
out.append('<option value="">(no label)</option>')
for lbl in labels:
name = lbl['name']
color = lbl.get('color', LABEL_COLOR_DEFAULT)
bg, fg = _label_colors(color)
sel = ' selected' if name == selected else ''
# Inline badge style on each option so the user sees the color in the dropdown.
out.append(
f'<option value="{h(name)}"{sel} '
f'style="background:{bg};color:{fg};">{h(name)}</option>'
)
out.append('</select>')
return ''.join(out)
def label_badge(label, color=None):
"""Render a colored label badge span, or empty string if no label.
color is a key into LABEL_COLORS; falls back to default if absent/unknown."""
if not label:
return ''
bg, fg = _label_colors(color or LABEL_COLOR_DEFAULT)
return (
f'<span class="label-badge" '
f'style="background:{bg};color:{fg};">{h(label)}</span>'
)
# ########################################################################### #
# Handle POST actions (all require auth) #
def handle_post(form, data):
if not is_authenticated():
print("Status: 403 Forbidden\r")
print("Content-Type: text/plain\r\n\r")
print("Authentication required for write operations.")
return
action = form.getvalue('action', '')
if action == 'push':
name = form.getvalue('name', '').strip()
notes = form.getvalue('notes', '').strip()
label = form.getvalue('label', '').strip()[:32]
pos = form.getvalue('pos', 'top')
# Validate label name against master list; find its color entry.
label_color = ''
label_names = [l['name'] for l in data.get('labels', [])]
if label and label not in label_names:
label = ''
if label:
entry = next((l for l in data['labels'] if l['name'] == label), None)
label_color = entry['color'] if entry else LABEL_COLOR_DEFAULT
if not name:
redirect(); return
task = new_task(name, notes, label, label_color)
if pos == 'top':
# New task becomes current; old current goes to top of queue.
if data['current'] and not data['idle_active']:
deactivate_task(data['current'])
data['queue'].insert(0, data['current'])
data['current'] = task
activate_task(data['current'])
data['idle_active'] = False
elif pos == 'second':
data['queue'].insert(0, task)
else:
data['queue'].append(task)
elif action == 'grab':
# Move a queue item to current; old current returns to top of queue.
idx = int(form.getvalue('idx', -1))
if 0 <= idx < len(data['queue']):
grabbed = data['queue'].pop(idx)
if data['current'] and not data['idle_active']:
deactivate_task(data['current'])
data['queue'].insert(0, data['current'])
data['current'] = grabbed
activate_task(data['current'])
data['idle_active'] = False
elif action == 'complete':
# Complete current task: log to done file, promote queue head.
if data['current'] and not data['idle_active']:
deactivate_task(data['current'])
entry = dict(data['current'])
entry['completed_at'] = datetime.now(timezone.utc).isoformat()
done = load_done()
done.append(entry)
save_done(done)
if data['queue']:
data['current'] = data['queue'].pop(0)
activate_task(data['current'])
data['idle_active'] = False
else:
data['current'] = None
data['idle_active'] = True
elif action == 'complete_queue':
# Complete a task sitting in the queue without grabbing it first.
# Queue tasks have never been active, so time_active stays 0.
idx = int(form.getvalue('idx', -1))
if 0 <= idx < len(data['queue']):
task = data['queue'].pop(idx)
entry = dict(task)
entry['completed_at'] = datetime.now(timezone.utc).isoformat()
done = load_done()
done.append(entry)
save_done(done)
elif action == 'drop':
# Abandon a queue task: log to done with abandoned=True.
idx = int(form.getvalue('idx', -1))
if 0 <= idx < len(data['queue']):
task = data['queue'].pop(idx)
entry = dict(task)
entry['completed_at'] = datetime.now(timezone.utc).isoformat()
entry['abandoned'] = True
done = load_done()
done.append(entry)
save_done(done)
elif action == 'drop_current':
# Abandon the current task: log to done with abandoned=True.
if data['current'] and not data['idle_active']:
deactivate_task(data['current'])
entry = dict(data['current'])
entry['completed_at'] = datetime.now(timezone.utc).isoformat()
entry['abandoned'] = True
done = load_done()
done.append(entry)
save_done(done)
if data['queue']:
data['current'] = data['queue'].pop(0)
activate_task(data['current'])
data['idle_active'] = False
else:
data['current'] = None
data['idle_active'] = True
elif action == 'move_up':
idx = int(form.getvalue('idx', -1))
if 1 <= idx < len(data['queue']):
data['queue'][idx-1], data['queue'][idx] = data['queue'][idx], data['queue'][idx-1]
elif action == 'move_down':
idx = int(form.getvalue('idx', -1))
if 0 <= idx < len(data['queue']) - 1:
data['queue'][idx+1], data['queue'][idx] = data['queue'][idx], data['queue'][idx+1]
elif action == 'edit':
# Edit name/notes/label on a queue task or the current task.
target = form.getvalue('target', 'queue')
name = form.getvalue('name', '').strip()
notes = form.getvalue('notes', '').strip()
label = form.getvalue('label', '').strip()[:32]
# Validate label name; resolve its color.
label_color = ''
label_names = [l['name'] for l in data.get('labels', [])]
if label and label not in label_names:
label = ''
if label:
entry = next((l for l in data['labels'] if l['name'] == label), None)
label_color = entry['color'] if entry else LABEL_COLOR_DEFAULT
if target == 'current' and data['current']:
if name: data['current']['name'] = name
data['current']['notes'] = notes
if label:
data['current']['label'] = label
data['current']['label_color'] = label_color
else:
data['current'].pop('label', None)
data['current'].pop('label_color', None)
elif target == 'idle':
data['idle_notes'] = notes
else:
idx = int(form.getvalue('idx', -1))
if 0 <= idx < len(data['queue']):
if name: data['queue'][idx]['name'] = name
data['queue'][idx]['notes'] = notes
if label:
data['queue'][idx]['label'] = label
data['queue'][idx]['label_color'] = label_color
else:
data['queue'][idx].pop('label', None)
data['queue'][idx].pop('label_color', None)
elif action == 'set_idle':
# Park current task back on queue, set state to Idle.
if data['current'] and not data['idle_active']:
deactivate_task(data['current'])
data['queue'].insert(0, data['current'])
data['current'] = None
data['idle_active'] = True
elif action == 'add_label':
# Add a new label to the master list. 32-char max, no dupes by name.
new_label = form.getvalue('label_name', '').strip()[:32]
new_color = form.getvalue('label_color', LABEL_COLOR_DEFAULT)
if new_color not in LABEL_COLORS:
new_color = LABEL_COLOR_DEFAULT
label_names = [l['name'] for l in data.get('labels', [])]
if new_label and new_label not in label_names:
data.setdefault('labels', []).append({'name': new_label, 'color': new_color})
elif action == 'remove_label':
# Remove a label from the master list by name. Tasks that carry it keep
# their label value (historical record); it just won't appear in
# dropdowns anymore until re-added.
del_label = form.getvalue('label_name', '').strip()
data['labels'] = [l for l in data.get('labels', []) if l['name'] != del_label]
save_tasks(data)
redirect()
def redirect():
script = os.environ.get('SCRIPT_NAME', 'tasks')
print(f"Status: 303 See Other\r")
print(f"Location: {script}\r\n\r")
# ########################################################################### #
# Embedded Image #
BANNER_SVG = '''<svg xmlns="http://www.w3.org/2000/svg" width="100%" viewBox="0 0 800 140">
<defs>
<marker id="sa" viewBox="0 0 10 10" refX="8" refY="5"
markerWidth="5" markerHeight="5" orient="auto-start-reverse">
<path d="M2 1L8 5L2 9" fill="none" stroke="#C9A84C"
stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
</marker>
</defs>
<g transform="translate(80,0)">
<!-- ── SIGNAL LINE ── -->
<line x1="0" y1="105" x2="500" y2="105"
stroke="#C9A84C" stroke-width="1.3" opacity="0.4"/>
<line x1="0" y1="105" x2="25" y2="105"
stroke="#C9A84C" stroke-width="1" opacity="0.15"
stroke-dasharray="3 5"/>
<line x1="500" y1="105" x2="500" y2="78"
stroke="#C9A84C" stroke-width="2" stroke-linecap="round"/>
<line x1="500" y1="78" x2="541" y2="78"
stroke="#C9A84C" stroke-width="2" stroke-linecap="round"
marker-end="url(#sa)"/>
<!-- ── CHIP (skewY -9, right-side-up, 48px wide) ── -->
<g transform="translate(598,60) skewY(-9) translate(-598,-60)">
<rect x="574" y="12" width="48" height="96" rx="3"
fill="#111" stroke="#383838" stroke-width="1"/>
<path d="M590 12 Q598 9 606 12" fill="none" stroke="#444" stroke-width="1"/>
<circle cx="579" cy="18" r="1.2" fill="#555"/>
<text x="598" y="93" text-anchor="middle" dominant-baseline="central"
font-family="monospace,'Courier New',Courier"
font-size="10" font-weight="bold" fill="#C9A84C">INTR?!</text>
<!-- left pins 1-17 and 19-20 -->
<g stroke="#4a4a4a" stroke-width="1" stroke-linecap="round" fill="none">
<polyline points="574,16.0 564,16.0 562,20"/>
<polyline points="574,20.5 564,20.5 562,24.5"/>
<polyline points="574,25.0 564,25.0 562,29"/>
<polyline points="574,29.5 564,29.5 562,33.5"/>
<polyline points="574,34.0 564,34.0 562,38"/>
<polyline points="574,38.5 564,38.5 562,42.5"/>
<polyline points="574,43.0 564,43.0 562,47"/>
<polyline points="574,47.5 564,47.5 562,51.5"/>
<polyline points="574,52.0 564,52.0 562,56"/>
<polyline points="574,56.5 564,56.5 562,60.5"/>
<polyline points="574,61.0 564,61.0 562,65"/>
<polyline points="574,65.5 564,65.5 562,69.5"/>
<polyline points="574,70.0 564,70.0 562,74"/>
<polyline points="574,74.5 564,74.5 562,78.5"/>
<polyline points="574,79.0 564,79.0 562,83"/>
<polyline points="574,83.5 564,83.5 562,87.5"/>
<polyline points="574,88.0 564,88.0 562,92"/>
<polyline points="574,97.0 564,97.0 562,101"/>
<polyline points="574,101.5 564,101.5 562,105.5"/>
</g>
<!-- pin 18: gold, exits left, routes up to signal y=78 -->
<polyline points="574,92.5 548,92.5 548,78"
fill="none" stroke="#C9A84C" stroke-width="1.8"
stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="548" cy="78" r="1.8" fill="#C9A84C"/>
<!-- right pins 21-40 -->
<g stroke="#4a4a4a" stroke-width="1" stroke-linecap="round" fill="none">
<polyline points="622,16.0 632,16.0 634,20"/>
<polyline points="622,20.5 632,20.5 634,24.5"/>
<polyline points="622,25.0 632,25.0 634,29"/>
<polyline points="622,29.5 632,29.5 634,33.5"/>
<polyline points="622,34.0 632,34.0 634,38"/>
<polyline points="622,38.5 632,38.5 634,42.5"/>
<polyline points="622,43.0 632,43.0 634,47"/>
<polyline points="622,47.5 632,47.5 634,51.5"/>
<polyline points="622,52.0 632,52.0 634,56"/>
<polyline points="622,56.5 632,56.5 634,60.5"/>
<polyline points="622,61.0 632,61.0 634,65"/>
<polyline points="622,65.5 632,65.5 634,69.5"/>
<polyline points="622,70.0 632,70.0 634,74"/>
<polyline points="622,74.5 632,74.5 634,78.5"/>
<polyline points="622,79.0 632,79.0 634,83"/>
<polyline points="622,83.5 632,83.5 634,87.5"/>
<polyline points="622,88.0 632,88.0 634,92"/>
<polyline points="622,92.5 632,92.5 634,96.5"/>
<polyline points="622,97.0 632,97.0 634,101"/>
<polyline points="622,101.5 632,101.5 634,105.5"/>
</g>
</g>
<!-- ── STICK FIGURES ── -->
<!-- Figure 0: lying down far left -->
<g stroke="#111" stroke-width="1.5" stroke-linecap="round" fill="none">
<circle cx="30" cy="103" r="4" fill="#111" stroke="none"/>
<line x1="34" y1="104" x2="50" y2="105"/>
<line x1="40" y1="104" x2="38" y2="96"/>
<line x1="40" y1="104" x2="43" y2="108"/>
<line x1="50" y1="105" x2="53" y2="98"/>
<line x1="50" y1="105" x2="55" y2="107"/>
</g>
<!-- Figure 1 x=195: hand on chin -->
<g stroke="#111" stroke-width="1.5" stroke-linecap="round" fill="none">
<circle cx="195" cy="89" r="4.5" fill="#111" stroke="none"/>
<line x1="195" y1="93.5" x2="195" y2="103"/>
<line x1="195" y1="97" x2="189" y2="100"/>
<line x1="195" y1="97" x2="201" y2="94"/>
<line x1="195" y1="103" x2="191" y2="111"/>
<line x1="195" y1="103" x2="199" y2="111"/>
</g>
<!-- Figure 2 x=230: shrugging -->
<g stroke="#111" stroke-width="1.5" stroke-linecap="round" fill="none">
<circle cx="230" cy="88" r="4.5" fill="#111" stroke="none"/>
<line x1="230" y1="92.5" x2="230" y2="102"/>
<line x1="230" y1="96" x2="223" y2="92"/>
<line x1="230" y1="96" x2="237" y2="92"/>
<line x1="230" y1="102" x2="226" y2="111"/>
<line x1="230" y1="102" x2="234" y2="111"/>
</g>
<!-- Figure 3 x=265: peering down -->
<g stroke="#111" stroke-width="1.5" stroke-linecap="round" fill="none">
<circle cx="268" cy="88" r="4.5" fill="#111" stroke="none"/>
<line x1="267" y1="92.5" x2="264" y2="102"/>
<line x1="266" y1="96" x2="259" y2="99"/>
<line x1="266" y1="96" x2="272" y2="93"/>
<line x1="264" y1="102" x2="260" y2="111"/>
<line x1="264" y1="102" x2="268" y2="111"/>
</g>
<!-- Figure 4: pusher at x~490, leaning into rising edge -->
<g stroke="#111" stroke-width="1.5" stroke-linecap="round" fill="none">
<circle cx="492" cy="85" r="4.5" fill="#111" stroke="none"/>
<line x1="491" y1="89.5" x2="483" y2="101"/>
<line x1="489" y1="93" x2="499" y2="88"/>
<line x1="487" y1="97" x2="499" y2="94"/>
<line x1="483" y1="101" x2="476" y2="111"/>
<line x1="483" y1="101" x2="485" y2="111"/>
<line x1="502" y1="85" x2="506" y2="83" stroke-width="1" opacity="0.55"/>
<line x1="502" y1="89" x2="507" y2="89" stroke-width="1" opacity="0.55"/>
<line x1="502" y1="93" x2="506" y2="95" stroke-width="1" opacity="0.55"/>
</g>
<!-- ── LABELS ── -->
<text x="14" y="30"
font-family="monospace,'Courier New',Courier"
font-size="26" font-weight="bold" fill="#C9A84C"
opacity="0.9">INTR</text>
<text x="14" y="50"
font-family="monospace,'Courier New',Courier"
font-size="8.5" fill="#777"
letter-spacing="8">interrupt request pending</text>
</svg>'''
CSS = """
body {
font-family: monospace;
font-size: 14px;
margin: 0;
padding: 0;
background: #f4f4f4;
color: #111;
}
#page {
max-width: min(1400px, 95vw);
margin: 0 auto;
padding: 12px 16px;
}
h1 { font-size: 16px; margin: 0 0 12px; font-weight: bold; }
h2 { font-size: 14px; margin: 0 0 8px; font-weight: bold; }
a { color: #00e; }
a:visited { color: #551a8b; }
/* Current task box */
#current-box {
border: 2px solid #444;
background: #fff;
padding: 10px 12px;
margin-bottom: 14px;
}
#current-box.idle {
border-color: #aaa;
background: #f9f9f9;
color: #555;
}
#current-title {
font-size: 15px;
font-weight: bold;
margin-bottom: 4px;
}
.task-notes {
color: #444;
margin: 4px 0 8px;
white-space: pre-wrap;
font-size: 13px;
}
.task-meta {
font-size: 11px;
color: #777;
margin-bottom: 6px;
}
/* Queue table */
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 14px;
}
th {
text-align: left;
font-size: 12px;
border-bottom: 1px solid #aaa;
padding: 3px 6px;
background: #e8e8e8;
}
td {
padding: 4px 6px;
border-bottom: 1px solid #ddd;
vertical-align: top;
}
tr:hover td { background: #f0f0f0; }
.num { color: #888; font-size: 12px; width: 2em; text-align: right; }
.taskname { font-weight: bold; }
.qnotes { font-size: 12px; color: #555; white-space: pre-wrap; }
.actions { white-space: nowrap; font-size: 12px; }
.actions form { display: inline; }
.actions button {
font-size: 11px;
padding: 4px 8px;
cursor: pointer;
background: #e8e8e8;
border: 1px solid #aaa;
margin-right: 2px;
}
.actions button:hover { background: #d0d0d0; }
.btn-warn { background: #fdd !important; border-color: #c88 !important; }
/* Abandoned badge in done list */
.abandoned-badge {
display: inline-block;
font-size: 10px;
padding: 1px 5px;
background: #eee;
color: #888;
border-radius: 2px;
margin-left: 4px;
vertical-align: middle;
}
.btn-link {
display: inline-block;
font-size: 11px;
padding: 4px 8px;
cursor: pointer;
background: #e8e8e8;
border: 1px solid #aaa;
margin-right: 2px;
text-decoration: none;
color: #111;
}
.btn-link:visited { color: #111; }
.btn-link:hover { background: #d0d0d0; }
/* Label badge — colors applied via inline style; only structure here */
.label-badge {
display: inline-block;
font-size: 10px;
padding: 1px 5px;
border-radius: 2px;
margin-left: 4px;
vertical-align: middle;
white-space: nowrap;
}
/* Label management section */
#label-section {
border-top: 1px dashed #aaa;
padding-top: 10px;
margin-top: 6px;
color: #555;
font-size: 12px;
}
#label-section .label-list { margin: 4px 0 8px; }
#label-section .label-list form { display: inline; }
#label-section .label-list button {
font-size: 10px;
padding: 0px 4px;
cursor: pointer;
background: #fdd;
border: 1px solid #c88;
margin-left: 3px;
vertical-align: middle;
}
#label-add-form { margin-top: 4px; }
#label-add-form input[type=text] {
font-family: monospace;
font-size: 12px;
border: 1px solid #aaa;
padding: 2px 4px;
width: 18em;
}
#label-add-form input[type=submit] {
font-size: 12px;
padding: 2px 8px;
cursor: pointer;
}
/* Idle row */
#idle-section {
border-top: 1px dashed #aaa;
padding-top: 10px;
margin-top: 6px;
color: #555;
}
/* Push form */
#push-form {
background: #fff;
border: 1px solid #ccc;
padding: 10px 12px;
margin-bottom: 14px;
}
#push-form input[type=text],
#push-form textarea {
width: 100%;
font-family: monospace;
font-size: 13px;
box-sizing: border-box;
border: 1px solid #aaa;
padding: 3px 5px;
}
#push-form textarea { height: 60px; resize: vertical; }
#push-form label { display: block; margin: 6px 0 2px; font-size: 12px; }
#push-form .radio-row { margin: 4px 0; font-size: 12px; }
#push-form .submit-row { margin-top: 8px; }
#push-form input[type=submit] {
padding: 3px 12px;
font-size: 13px;
cursor: pointer;
}
/* Edit inline form */
.edit-form input[type=text],
.edit-form textarea {
font-family: monospace;
font-size: 13px;
border: 1px solid #aaa;
padding: 2px 4px;
width: 98%;
box-sizing: border-box;
}
.edit-form textarea { height: 50px; resize: vertical; }
/* Banner */
#banner {
width: 100%;
display: block;
margin-bottom: 8px;
border-bottom: 1px solid #ccc;
}
#nav a { margin-right: 12px; }
/* Auth notice */
#auth-notice {
font-size: 11px;
color: #888;
margin-bottom: 10px;
}
"""
# ########################################################################### #
# Render helpers #
def action_form(action, extra_inputs='', label='', btn_class=''):
script = os.environ.get('SCRIPT_NAME', 'tasks')
cls = f' class="{btn_class}"' if btn_class else ''
return (f'<form method="post" action="{script}">'
f'<input type="hidden" name="action" value="{action}">'
f'{extra_inputs}'
f'<button type="submit"{cls}>{label}</button>'
f'</form>')
def danger_form(action, extra_inputs='', label='Drop', confirm_msg='Drop this task?'):
# Like action_form but with a confirm() dialog to prevent accidental clicks.
script = os.environ.get('SCRIPT_NAME', 'tasks')
msg = confirm_msg.replace("'", "\\'")
return (f'<form method="post" action="{script}">'
f'<input type="hidden" name="action" value="{action}">'
f'{extra_inputs}'
f'<button type="submit" class="btn-warn" '
f"onclick=\"return confirm('{msg}')\">{label}</button>"
f'</form>')
def render_page(data, authenticated, edit_target=None, edit_idx=None, show_push=False):
labels = data.get('labels', [])
auth_notice = ""
print("Content-Type: text/html; charset=utf-8\r\n\r")
script = os.environ.get('SCRIPT_NAME')
base, _ = script.rsplit('/', 1)
done_script = f'{base}/{DONE_SCRIPT_NAME}'
if not authenticated:
auth_notice = (
'Read-only view — '
f'<form method="POST" action="{h(script)}" style="display:inline;">'
'<input type="hidden" name="action" value="login">'
'<button type="submit" style="background:none;border:none;color:blue;text-decoration:underline;cursor:pointer;padding:0;">log in</button>'
'</form>'
)
print(f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>INTR</title>
<style>{CSS}</style>
</head>
<body>
<div id="page">
<div id="banner">{BANNER_SVG}</div>
<div id="nav">
<a href="{h(script)}">Tasks</a>
<a href="{h(done_script)}">Done</a>
</div>
<div id="auth-notice">{auth_notice}</div>
""")
# --- Current task box ---
cur = data.get('current')
idle_active = data.get('idle_active', True)
print('<div id="current-box"' + (' class="idle"' if idle_active or not cur else '') + '>')
print('<div style="font-size:11px;color:#888;margin-bottom:4px;">CURRENT TASK</div>')
if idle_active or not cur:
print('<div id="current-title">Idle</div>')
idle_notes = data.get('idle_notes', '')
if idle_notes:
print(f'<div class="task-notes">{h(idle_notes)}</div>')
if authenticated:
if data['queue']:
print('<div class="actions" style="margin-top:6px;">')
print(action_form('grab', '<input type="hidden" name="idx" value="0">', 'Grab #1 from queue'))
print('</div>')
else:
if edit_target == 'current' and authenticated:
# Inline edit form for current task
print(f'<form method="post" action="{h(script)}" class="edit-form">')
print('<input type="hidden" name="action" value="edit">')
print('<input type="hidden" name="target" value="current">')
print(f'<input type="text" name="name" value="{h(cur["name"])}" style="font-size:15px;font-weight:bold;margin-bottom:4px;"><br>')
print(f'<textarea name="notes">{h(cur.get("notes",""))}</textarea><br>')
if labels:
print(f'<label style="font-size:11px;">Label: {label_select(labels, cur.get("label",""))}</label><br>')
print('<input type="submit" value="Save"> ')
print(f'<a href="{h(script)}" class="btn-link">Cancel</a>')
print('</form>')
print(danger_form('drop_current', '', 'NOP (drop, no log)', 'Drop current task without logging?'))
else:
cur_label = cur.get('label', '')
print(f'<div id="current-title">{label_badge(cur_label, cur.get("label_color",""))}{h(cur["name"])}</div>')
notes = cur.get('notes', '')
if notes:
print(f'<div class="task-notes">{h(notes)}</div>')
age = duration_str(cur.get('created_at',''))
active_secs = task_active_seconds(cur)
active_str = seconds_to_str(active_secs) if active_secs else '0m'
print(f'<div class="task-meta">In stack: {h(age)} — Active: {active_str}</div>')
if authenticated:
print('<div class="actions">')
print(action_form('complete', '', 'IRET', ''))
print(action_form('set_idle', '', 'STI HLT (idle)'))
print(f'<a href="{h(script)}?edit=current" class="btn-link">Edit</a>')
print('</div>')
print('</div>') # end current-box
# --- Push form ---
if authenticated:
if show_push:
print(f'<div id="push-form">')
print(f'<form method="post" action="{h(script)}">')
print('<input type="hidden" name="action" value="push">')
print('<label>Task name</label>')
print('<input type="text" name="name" autofocus required>')
print('<label>Notes</label>')
print('<textarea name="notes"></textarea>')
if labels:
print(f'<label>Label: {label_select(labels)}</label>')
print('<label>Position</label>')
print('<div class="radio-row"><label><input type="radio" name="pos" value="top" checked> Push to top (becomes current)</label></div>')
print('<div class="radio-row"><label><input type="radio" name="pos" value="second"> Insert at #1 in queue (after current)</label></div>')
print('<div class="radio-row"><label><input type="radio" name="pos" value="bottom"> Append to bottom</label></div>')
print('<div class="submit-row"><input type="submit" value="Push task"> ')
print(f'<a href="{h(script)}" class="btn-link">Cancel</a></div>')
print('</form></div>')
else:
print(f'<p><a href="{h(script)}?push=1">▶ PUSH (new task)</a></p>')
# --- Idle ---
print('<div id="idle-section">')
print('<b>Idle</b>')
idle_notes = data.get('idle_notes','')
if edit_target == 'idle' and authenticated:
print(f'<form method="post" action="{h(script)}" class="edit-form" style="margin-top:4px;">')
print('<input type="hidden" name="action" value="edit">')
print('<input type="hidden" name="target" value="idle">')
print(f'<textarea name="notes">{h(idle_notes)}</textarea><br>')