Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
159021e95e | ||
|
|
4b35ac856d | ||
|
|
efb25b1596 | ||
|
|
f6022f33d0 | ||
|
|
7d233d93ad |
No files matched your search
@@ -9,7 +9,6 @@ body:
|
||||
attributes:
|
||||
value: |
|
||||
Use this form for broken behavior, regressions, crashes, or reliability problems.
|
||||
Feature requests belong in [Discussions](https://github.com/pingdotgg/t3code/discussions/categories/ideas).
|
||||
Search existing issues first and keep the report focused on one problem.
|
||||
|
||||
- type: checkboxes
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Feature request
|
||||
url: https://github.com/pingdotgg/t3code/discussions/categories/ideas
|
||||
about: Suggest an improvement or new capability in Discussions.
|
||||
@@ -0,0 +1,102 @@
|
||||
name: Feature request
|
||||
description: Propose a scoped improvement or new capability.
|
||||
title: "[Feature]: "
|
||||
labels:
|
||||
- enhancement
|
||||
- needs-triage
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Use this form for new capabilities or meaningful improvements to existing behavior.
|
||||
This repo is still early. Small, concrete requests that clearly explain the problem and scope are much easier to evaluate.
|
||||
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
attributes:
|
||||
label: Before submitting
|
||||
options:
|
||||
- label: I searched existing issues and did not find a duplicate.
|
||||
required: true
|
||||
- label: I am describing a concrete problem or use case, not just a vague idea.
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: area
|
||||
attributes:
|
||||
label: Area
|
||||
description: Which part of the project would this change affect?
|
||||
options:
|
||||
- apps/web
|
||||
- apps/server
|
||||
- apps/desktop
|
||||
- apps/mobile
|
||||
- packages/contracts or packages/shared
|
||||
- Build, CI, or release tooling
|
||||
- Docs
|
||||
- Not sure
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem or use case
|
||||
description: What are you trying to do? What is hard, slow, or impossible today?
|
||||
placeholder: I want to reconnect to an existing provider session after a browser refresh without losing the current thread state.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: Proposed solution
|
||||
description: Describe the behavior, API, or UX you want.
|
||||
placeholder: Persist enough session metadata so the client can discover and reattach to the active provider session on load.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: value
|
||||
attributes:
|
||||
label: Why this matters
|
||||
description: Who benefits, and what outcome does this unlock?
|
||||
placeholder: This would make reconnects predictable during network drops and reduce accidental duplicate sessions.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: scope
|
||||
attributes:
|
||||
label: Smallest useful scope
|
||||
description: What is the narrowest version of this request that would still solve your problem?
|
||||
placeholder: A first pass only needs to support restoring the active session for the current thread.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives considered
|
||||
description: Workarounds, prior art, or other approaches you considered.
|
||||
placeholder: I currently work around this by manually restarting the provider session, but that loses in-flight context.
|
||||
|
||||
- type: textarea
|
||||
id: tradeoffs
|
||||
attributes:
|
||||
label: Risks or tradeoffs
|
||||
description: What costs, complexity, or edge cases should be considered?
|
||||
placeholder: This may require careful handling when the underlying provider session has already exited.
|
||||
|
||||
- type: textarea
|
||||
id: references
|
||||
attributes:
|
||||
label: Examples or references
|
||||
description: Links, screenshots, mockups, or comparable tools.
|
||||
|
||||
- type: checkboxes
|
||||
id: contribution
|
||||
attributes:
|
||||
label: Contribution
|
||||
options:
|
||||
- label: I would be open to helping implement this.
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="800"><image width="1280" height="800" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAAMgCAIAAADz+lisAAAQAElEQVR4nOzdB3gU5drG8YGEBAiEFnrvvQsISBUERUGxIBYsR1EsR0X0oCj2jl3xU8FCUVABUXrvHQzSIXRCJ4RAIJV8d/aVcd1AsoGokPf/u/baazIzO/tOWZh7nimBSUlJDgAAAAAA2V1OBwAAAAAACxCAAQAAAABWIAADAAAAAKxAAAYAAAAAWIEADAAAAACwAgEYAAAAAGAFAjAAAAAAwAoEYAAAAACAFQjAAAAAAAArEIABAAAAAFYgAAMAAAAArEAABgAAAABYgQAMAAAAALACARgAAAAAYAUCMAAAAADACgRgAAAAAIAVCMAAAAAAACsQgAEAAAAAViAAAwAAAACsQAAGAAAAAFiBAAwAAAAAsAIBGAAAAABgBQIwAAAAAMAKBGAAAAAAgBUIwAAAAAAAKxCAAQAAAABWIAADAAAAAKxAAAYAAAAAWIEADAAAAACwAgEYAAAAAGAFAjAAAAAAwAoEYAAAAACAFQjAAAAAAAArEIABAAAAAFYgAAMAAAAArEAABgAAAABYgQAMAAAAALACARgAAAAAYAUCMAAAAADACgRgAAAAAIAVCMAAAAAAACsQgAEAAAAAViAAAwAAAACsQAAGAAAAAFiBAAwAAAAAsEKgA8APKSkpDgAAwMUqR44cDoCMEICBszBx1/sdAADg4mdisPc7AG8EYOAvUs5ISkpKTNRbsuidGAwAAC5miruBgQE5c+bMlStQL8lxhgPgjBzawXcAeEXfhITE2NhTKSmnc+XKFRSUyyMwICDAAQAAuFjpkL2O3ScmJmpPRpR7Q0Lyak+GGAx4IwADqZR7T3ucPHkqPj6xSJFC+g/DAQAAuDQpBh85cjQ4OFfevHlyepCBAYcADDhn0q9+C8ePxwYHBxcsGOoAAABc+qKjY+Lj4/PnDwkMDCQDAw4BGDDpNzEx8cSJkwULFggODnIAAACyi/j4hOjoY/ny5c2VKxcZGOA5wLCaueg3OTmZ9AsAALIl7d4ULBiqXR3t8Jg9HwewGAEYVjPp9+TJU8GpSL8AACAb8uznBGuHx2RgB7AYARj2OnPP54TExCSu+wUAANmYdnUSEpK020MRGJYjAMNepvx76lR84cKFHAAAgGytSJGCp07FUQSG5QjAsJT7yF+988QjAACQ7QUFBZ0+7SQmJlIEhs0IwLCXuflzrlykXwAAYAUd9NfRf+0COYCtCMCw1Jn7P5+m/AsAACyh3R7t/FABhs0IwLCXDn/qX38qwAAAwBLa7dHODxVg2CzQAaxkjn0qAufKxa8AAABYQbs9p/8oAFMBhqXY9YfV9K9/QECAAwAAYAHt9hB9YTlOgYaNzD/9/AcAAAAsxI4QbEYABgAAAABYgQAMAAAAALACARgAAAAAYAUCMAAAAADACgRgAAAAAIAVCMAAAAAAACsQgAEAAAAAViAAAwAAAACsQAAGAAAAAFiBAAwAAAAAsAIBGAAAAABgBQIwAAAAAMAKBGAAAAAAgBUIwAAAAAAAKxCAAQAAAABWCBg4cKAD2CclJSU5OTk+PjE0NJ+T1U6fPr1nz56tW7eePp0SGprfyb6io4+9//6HOXLkKFeunGM9rfEffvipQIECRYoUdi5iO3bsHD/+l8mTpxQpUiRXrqCLZw1GRKQuwIIFCxYu7LsAZ8yYOWbM2IYNG+TKlcv5R3gvpaJFizr/qs8//3LDho3169dzAOCCHT9+Ijg4KDAwMIeHA1gm0AGQpebNm//6629o79n8GRKSt1evXg8/3Ef/0ziXvr1790VFHalatWpwcLD+XLRo0bffDgsPD7/iipZOltq8ecvp08k1atRwLoxPgzPl2LFju3fvLlWqVNo8dtZGbtkS8cEHH5YtW6Zq1SrOxWrXrl033nhTbOxJbZnNmjXZsWPH37QGz0NEROoCrFChfJUqlX0Gvfnm2zqo1Lx58wzbmZSUtHHjRh2GKFu2rHO+fJZSrVo1nX/PgQMH3n//A3V07359SEiIAwAALgABGMhKq1b91rv3g+rQbrpeOsg6ceLEzz77v9WrVw8e/Enu3LmdS9xXX309YsTIiRN/qVw5NaK0adP6iSceb9LkMier/fe/jx06dGjlyuXOhfFpcKYsWbL0sceeePnlF2+55Wbn72zkP2nhwsXKdX37Pn7fff/JmTNnbGzs37QGs9arr760du16f9p59Gj0TTf1uPbaLoMGve2cL5+l5Pyrihcv/sorL+kIDukXAIALRwAGskxk5N777++tjiFDvnDrVPfdd++TTz49a9asKVOmXn99Nyd70R75Aw/c7+DSERkZqff27dubXHeprMHLPZx/is9S+tfdfPNNDgAAyArcBAvIMnPmzFHV6OGHH/I+SzNPnjzPPfesOoYNG+72nDRpct++/Ro3btK16w3vvDNo585dpr86une/adSoH0aO/E5VrBo1aut9zpy5GrRnzx4NGjToPe9v/OWXX9Vz3rz56k5MTPzmm2/vuuteTbZPn4d/+mmMO5o+pdHWrl33wAN9NE0zaP36DQ899GiLFq300vgbN250x58/f/69996n6WjQI4/81wyKiYnRRMaNG6fuhx9+VN2bN2/Zv3+/OvyZNbn99jsHDHh+8eIl993XW83o3PmaoUO/TkpK8lmMS5cu0zR37NiphakOLQHT/1wz+NRT/9Noa9asMX+mpKSoAeqzYcOGtA120tAXPf543zZt2muymmsdpzD91fP1199UxwcffKTPjh//iz+NdDxXgL///geaO01QS2/z5s3eH9T0NWUNuu22Oz777P9UgHXOQXP00kuvdOjQyayFFStWuoO0KLTotBg1nV697v7ss8/VDDMonU3o8OHDGvT999+r+5FHUhdIePhqnzWoxuuDWg7uB7/44kuNEBUVpaFafVqJ3o389tthGnrgwAHnHJuZBn344UfaGDQXzzwzYMmSJd4f15ZmthYtrq+++ibtxuD6+ONPNXEzm+aLtm/fbpakpvziiy8dO3bMSS34f3P33feqY/bs2Rrn1VdfNx9Ppxlms5w6dVqPHj3V7OXLV6RdSs65txN/Vta5fpg+NPuDB3+mb1Qz9K7NQ581g7Su+/V7Wh2zZqXOV9qXO6b/GxgAAHaiAgxkGUVKvXfqdJVP/1KlSq5fv8b9U3vAzz2XevM51Zf279+nJDNhwqQffxxVrFixuLhTmoh2W7W/3q5d2woVyq9du/bBBx8aO/anmjVrnDx5Uvvl//3vI0FBQe6kNH7dunXU/eKLL48ZM7Z48eItW7bU/vfs2XNiYo7fe+/djic8a7TevR+Mj49r1apV4cKFNm3apJ1mDerZ89bjx49PmDBR40+a9GulSpXMDnRISN7mzZvv339gxoyZek2ePEHNq1y5sqapEFK2bLmCBQsEBwfHxydoyi1aNM9w1tRTQXr79h1qZKNGDZs2bbJs2XIl5ODgoDvuuN17cemr9UVmYarDvT/HuWZQH1d0GTBg4NixPwYGBiqpKoTfffdd5cqVS9tgn1WjJaPopQ7NQkBAoPLYokWL3333nS5drilbtuy+ffu0IkqUKK7pFChQwJ9Gyocffnz0aJSWnr5ai27Vqt/Gjx9XtGiY4zlg8fTT/c2yjYiI0Jhr1qz7+OMPAgICfBqmFXTzzbeqo3HjRhpq1sLgwR9rwSrhK7BpUoULF9ba/O23cC3J8PDwTz/9WLOfziZUqlQpd4GUL18+NDQ0T57cPmtQOVOfVQs7dLhy167d+mCZMmW0lEw0VeZUw7zbefDgQX08Li7+rJuZ0tf99z+oQwB16tTRVjpu3M96fffdCG0AGn/lylUaqg5tDHp/++131FrnHFSS1cSTkhLdL9JnAwMDmjW7fNasWQr8hw8f+eSTj8LCimjWtm7dGhycWzNbokQJjZ9+MzZ6aNPSnKrZKomnXUrpbCfpr6z0f5g++vd/Vr9Etequu3rpOJE2D62CN954zfH826LtUB358+f3Ppn/xIkTmqDWl9kC/d/AAACwFgEYyDJr1qzV+1l34t0TKXft2qWIqOjyyy/jwsJSQ5EJjS+88NJnn31qxlF0UVwx9935v//74oMPPlSo05/du9/w3nsfLF26VLvpGnTo0GElHwWVQoUKKfJpJ7tz507vvTfIc2HnyZ49b1eiaNu2tTKtmaz23bUzbW6iq2qYk1ouG2KSj5my9s41sopj9evXe/vtt8qXT70t8IgRI1VGmz9/Qa9ed77zzlvqVp/+/Z8ye+HeBV5/Zk2FxFdeecmcz6mvu+OOXt9/P9onACul6ItUUjt06JA6TM90ZlCt7dPnAVVB1bBu3bq+8sqrWgWPPfaoau9pG+xDMUNf98AD93fs2MHxxAwdF5g4cbKCzZNPPqGq4GOPPXHrrT3SXgN81kYaqsVNnjxRmV+hUbP/88/jV65cqZYrwimcKGX99NPoggULasznn3/hxx9/0gg33tjdZ/q9e/fxXkGmYR98kJqpfv11gnKOtoH/+79PTbDRZNVHs6nYn84m9Mwz/1NTVT4dMmToM8/0Nxuq9xo0ydnTwh90vMDxnLZgyuD+897MXnrpZcXO55571qziLVsirruumwqkCxfO05+PPvqY5yu+MQFYG7Oq2f5/kYLim2++ro1Btd/27Tsocx49erRr1+uU/RSJ1Qx3vQwa9O65mmFyozan558fcPvtt5nx0y4lraZzbSfpr6xJfvwwDXMcSjM1cuRwtUobj0q+27Zti4uL8753QJMml3lfCK3M7KT+nD/QsY9MbWAAAFiLU6CBLKOdbMU/tzx7ViYkP/10PxMR5aabblRQURnn9OnTpo8yrXvX2auuSt3h3r17j97NLine truncated
|
||||
|
Before Width: | Height: | Size: 42 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="800"><image width="1280" height="800" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAAMgCAIAAADz+lisAAAQAElEQVR4nOzdB5gV5dkG4AEWkCoKKopiw96wx15jD3YNaogaC5bEgmJHrDFW7LH3KNgrVuwFKypWmgVUivS2u5T/3Z14/s02V8VE9rvva69zzc6ZM/PNN3N255n3zJyiWbNmZQAAAFDfNcwAAAAgAQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJJQlAF1MHfu3AwA4LeqQYMGGfBjBGCoRh53Kz4CAPz25TG44iNQkQAM/2HuD2bNmlVaGg+zQzyKwQDAb1nE3aKiRg0bNmzcuCh+QoMfZMAPGsQBfgZUiL4lJaXTps2YO3dO48aNmzRpXK6oUaNGGQDAb1Wcso9z96WlpXEkEyL3tmjRPI5kxGCoSACGMpF755SbPn1GcXFp27YLxT+MDABg/hQx+PvvJzRt2rh582YNy8nAkAnAkP2QfuO9MGXKtKZNm7Zp0zoDAJj/TZw4ubi4uFWrFkVFRTIwZAIw5Om3tLR06tTpbdos2LRpkwwAoL4oLi6ZOHFSy5bNGzduLAOD7wEmaflFv7Nnz5Z+AYB6KQ5v2rRpHYc6ccCTH/lkkDABmKTl6Xf69BlNy0i/AEA9VH6c0zQOePIMnEHCBGDS9cM9n0tKS2e57hcAqMfiUKekZFYc9igCkzgBmHTl5d8ZM4oXXnihDACgXmvbts2MGTMVgUmcAEyiCl/5G4++8QgAqPeaNGkyZ05WWlqqCEzKBGDSld/8uXFj6RcASEKc9I+z/3EIlEGqBGAS9cP9n+co/wIAiYjDnjj4UQEmZQIw6YrTn/HXXwUYAEhEHPbEwY8KMCkryiBJ+bnPiMCNG3sXAABJiMOeOf8uAKsAkyiH/iQt/vo3atQoAwBIQBz2iL4kzkegSVH+p98/AAAgQQ6ESJkADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASWjUq1evDNIzd+7c2bNnFxeXtm7dMpvX5syZM3LkyGHDhs2ZM7d161ZZ/TVx4qTLLru8QYMGHTt2zJIXW7xfv/sWXHDBtm0Xzn7Dvvjiy4cffqR//yfbtm3buHGT384WHDq0rAPbtGmz8MKVO/DZZ5+7//4H1l67c+PGjbP/ioq9tMgii2T/U9ddd8Mnn3y61lprZgC/2JQpU5s2bVJUVNSgXAaJKcqAeeqll14+//y/x9Fz/muLFs27det21FFHxH+abP73zTffjh///QorrNC0adP49bXXXrvtttsHDRq06aabZPPU558PmTNn9sorr5z9MpUa/JNMmjTp66+/XmKJJarmsWobOWTI0D59Ll9qqSVXWKFT9lv11Vdf7bnnXtOmTY89c8MN1//iiy9+pS34MwwdWtaByyyzdKdOy1d66oILLoyTShtttNGPtnPWrFmffvppnIZYaqmlsp+rUi+tuuoq2f/O6NGjL7usTwzsscduLVq0yACAX0AAhnnp3XffO+yw7jEQh+nxEydZH3/88Wuv/ef7779/zTVXLbDAAtl87uabb7nzzrsef/yR5ZcviyhbbLH5cccdu/7662Xz2t/+dszYsWPfeeet7Jep1OCf5I03Bh5zzHFnn917n332zn7NRv43vfrq65Hrjj/+2EMO+UvDhg2nTZv2K23Beevcc88aPPjjurRzwoSJe+217y677HzxxRdmP1elXsr+pxZbbLFzzjkrzuBIvwDwywnAMM+MGvXNoYceFgM33nh9oU51yCEH9+jRc8CAAU8++dRuu+2a1S9xRH744YdmzD9GjRoVj1tvvXWe6+aXLfi7ctl/S6Ve+p/be++9MgBgXnATLJhnXnjhhagaHXXUkRU/pdmsWbPTTz81Bm6//Y7CyCee6H/88Sesu+76XbrsftFFF3/55Vf5+BjYY4+97rmn3113/SuqWCuvvFo8vvDCi/HUyJEj46mLL7604hIfeeTRGPnSSy/HcGlp6a233vbnPx8csz3iiKPuu+/+wmTxqphs8OCPDj/8iJhn/tTHH39y5JF/3XjjzeInpv/0008L07/88ssHH3xIzCeeOvrov+VPTZ48OWby4IMPxvBRR/01hj//fMh3330XA3VZtbD//n867bQzXn/9jUMOOSyascMOO9100y2zZs2q1I0DB74Z8/ziiy+jM2MgeiAfX9MKnnjiSTHZhx9+mP86d+7caECM+eSTT6o2OKsiFnTsscdvscXWMdtY6zhPkY+Pkeeff0EM9OlzRbz24YcfqUsjs/IrwC+7rE+sXcwweu/zzz+v+MKYf8w5ntpvvwOuvfafUYDNahBrdNZZ52y77fb5Vnj77XcKT0VXRNdFN8Z8unU78Nprr4tm5E/VsguNGzcunrr77rtj+Oijyzpk0KD3K23BaHy8MPqh8MLrr78hJhg/fnw8G5svNmLFRt522+3x7OjRo7MadrN46vLLr4idIdbilFNOe+ONNyq+PPa0fG+J7rr55lur7gwFV155dcw8X818QSNGjMh7Mubcu/dZkyZNysoK/rceeODBMfD888/HNOeee37+8lqake+WTz319L77do1mv/XW21V7Kat5P6nLxqrpjVlJrP4111wbS4xmxGPsHvHa/KnY1iec0DMGBgwoW6+qP4Up676DAUCaVIBhnolIGY/bb79dpfFLLLH4xx9/WPg1joBPP73s5nNRX/ruu28jyTz22BP33nvPoosuOnPmjJhJHLbG8fpWW225zDJLDx48uHv3Ix944L5VVll5+vTpcVz+t78d3aRJk8KsYvo11lg9hnv3Pvv++x9YbLHFNtlkkzj+fv75FyZPnnLwwQdm5eE5JjvssO7FxTM322yzhRde6LPPPouD5niqa9c/Tpky5bHHHo/pn3ji0eWWWy4/gG7RovlGG2303Xejn332ufjp3/+xaN7yyy8f84wQstRSHdu0WbBp06bFxSUx54033uhHVy1GRpAeMeKLaOQ666y9wQbrv/nmW5GQmzZtcsAB+1fsrlh0LCjvzBgo3J+jphWMl0d0Oe20Xg88cG9RUVEk1QjhBx74544dO1ZtcKVNEz0T0SsGYhUaNSqKPPbaa69fcslFO++801JLLfXtt9/GhmjffrGYz4ILLliXRobLL79ywoTx0Xux6Oi6d9997+GHH1xkkXZZ+QmLnj1Pzvt26NChMeWHH3505ZV9GjVqVKlhsYH23vuPMbDuuuvEs/lWuOaaK6NjI+FHYItZLbzwwrE133tvUPTkoEGDrr76ylj9WnahJZZYotAhSy+9dOvWrZs1W6DSFoycGa+NFm677TZfffV1vHDJJZeMXsqjaWTOaFjFdo4ZMyZePnNmcbW7WaSvQw/tHqcAVl999dhLH3zwofj517/ujB0gpn/nnXfj2RiInSEeL7zwomhtVoMoycbMZ80qLSwoXltU1GjDDX83YMCACPzjxn1/1VVXtGvXNlZt2LBhTZsuECvbvn37mL72ZnxaLnatWNNodpTEq/ZSLftJ7Rur9jdmJSeffGq8E6NVf/5ztzhPFLtHbIK///28rPxvS+yHMdCqVauKH+afOnVqzDC2V74H1n0HA4BkCcAwz3z44eB4rPYgvvBByq+++ioiYkSXRx55sF27slCUh8Yzzzzr2muvzqeJ6BJxJb/vzj//eX2fPpdHqItf99hj90sv7TNw4MA4TI+nxo4dF8kngspCCy0UkS8OsnfYYftLL724/MLO6V277h+JYsstN49Mm882jt3jYDq/iW5Uw7KyctmNefLJ5xxH5zFxFMfWWmvNCy/8x9JLl90W+M4774oy2ssvv9Kt258uuugfMRxjTj75xPwovGKBty6rFoXEc845K/88ZyzugAO63X1330oBOFJKLChKamPHjo2BfGQtKxitPeKIw6MKGg3bddcu55xzbmyCY475a9Teqza4kogZsbjDDz/097/fNiuPGXFe4PHH+0ew6dHjuKgKHnPMcX/8475VrwGutpG5qMX17/94ZP4IjbH6Dz308DvvvBMtjwgX4SRS1n339W3Tpk1MecYZZ957730xwZ577lFp/ocddkTFDZQ3rE+fskz16KOPRc6JfeCf/7w6DzYx2xgTqxmxv5Zd6JRTToqmRvn0xhtvOuWUk/MdteIWzJNzeQv7xfmCrPxjC3kZvO4q7mZnnXV2xM7TTz8138RDhgz9wx92jQLpq6++FL/+9a/HlC/i1jwAx84c1ey6LyiC4gUXnB87Q9R+t95628icEyZM6NLlD5H9IhJHMwrb5eKLL6mpGXlujN3pjDNO23///fLpq/ZSbKaa9pPaN9YTdXhj5vLzULFSd911R7Qqdp4o+Q4fPnzmzJkV7x2w/vrrVbwQOjJzVvZ27hPnPn7SDgYAyfIRaJhn4iA74l+hPFutPCT37HlCHhHDXnvtGUElyjhz5szJx0SmLdx1drvtyg64v/56ZDzmR9tPLine truncated
|
||||
|
Before Width: | Height: | Size: 30 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="1000" viewBox="0 0 1280 1000"><image width="1280" height="1000" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAAPkCAIAAAB5gwQOAAABLGlDQ1BfAAB4nJWQPUsDQRCGH0NA1DSiooXFlWnUJGI+UAsTNWiZKES7y+UIYhKPy4n2af0R1naCjQipbawEKxEbe0Gwje/dFReQFJlhdp59d9jdGYgtIYunoN3x3Eq5aNROTo3JTybkgZlW12G0qer3Lax9XWF8m2rYXUv5W+G5elxXNsTzzZCvfa6HfOPzled44luf3aNKSfwgTjaHuD7EluP69e/irXbr0or+TcLuHFeVa4plylzIm7SwWaPKOWeYohR7FMizrrwj31CkyUgpkNUuRYkiOa059qXkdZZmN2BV+PMMn+x9wHZ/MBg8RdphH+6zMP0YaclNmE3A80ukRTN2TNcMpLgiZhfhZ0Gt3MHcF8z0pC76xyN6Nf71anBAB4tVUUbdpMn+AQyUTdocuQPoAAAQAElEQVR4nOz9B3hUV7rvCe9SFgiRQWSJnDMGTLIBY4NtbGMbnAPO3T7dfbrPmZl7n5nnztz7PTPfnXtudzvnhHMAY3LOOeeco8hBOdb8ai3VZqtKEgIjLKz/73HTpaq9V3hX2O9/vXuvHVVQUOAIIYQQQgghhBC/d6IcIYQQQgghhBCiCiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLEQofr/f5/PxryOEEEIIcWtinRn+dYQQHiSAhQjFXip0wRBCCCHELY2cGSHCkQAWVRHFeIUQQghRlVF8WFRZJIBFlcOrfkuc9wsLCyMiIvhXFwYhhBBC3HJYB8Y6M/xb4gGuOyRXR1Q1JIBFVcE70bvTvftnyAWgDHkshBBCCFGZcZ0c918n6POU6AVJCYsqha+goMAR4vdIyH3O3inePcD9vsQUdJu0EEIIIW45yuPbuHI33EGSHha/bxQBFr9bQvayCgn2lnhhCJnqzZGOEEIIIcQtRLgDE+71hDwRFqJ4pX7F7xgJYPF7ozR9W/xGoCti2DEP/Zonfu2v/KdJXwghhBC/D/xGzwYkbYTBvRfa/BR6p7QXhYLF7xLdAi1+t9iNH5i4+WDmbl9Q3BZN9HkB8vPzC+x+V8GpP3CsbnwWQgghxK1O0KUpCvPanbGioiKjo6Oio6ODyvaKgwQcwPel7Z4lxO8ACWDx+6HE2K8ra82cHrgMoHhzcnLz8nLp/OZCEBkVFfjXTPg+RYCFEEII8TvCb70gVvsLCwvy89G2BfwVGYkMjomNjUEP4/4UFjpuTDgk5Ks4sPidIQEsbnlC9mywH5jdQ44yX/qzs3Oys3PtvB8bGx2J+I2KNIudEUV3AwkhhBBC/L6wz3mZu+IKiQQUFOTn5OTZSEBcXExcXCyukHGiinlC9k46p/iuWvKWxK2OBLD4/WCXJ630dVcrzf3PgS/y8vKzkb85udHR0fHxcfxrljx9V90LWgghhBDiVifE50EG5+XlZWVl8y9x4Lg4XKMoG1ZwnxO2x7t/OkL8LpAAFrcwJd7tHK5p+ZdlTqZ4PjLFx8fHe+72cRypXyGEEEJUATyukeM+F5aVlUV4gB8JD8TGRrsv0Qh3q0KScoS4NZEAFrcq7mJk2GZXTkgcmGk9IyMzIiKyRo3qMTHR4bv8a11TCCGEEL97XIfHu+7P59zcvLS0jMLCgurVqxEqCIn92mNCNseS7yRuXSSAxa2NO4N7lye903p2dk5mZmZkZGRCQoJVv1Yne1/7rhlcCCGEEFUBr/NjX4FhVS4aOD09HV1QrVq1uLhY93ivZ+X6S3KcxC2N9jcXtx7+IO5OV954r7tUyZ95eXmZmdnM7DVqJLCiaX8NEcmaxIUQQghRRXDdHu8dzoCbhLOEy4TjhPvkfY7Me8+dPdd9f6SeIBO3IhLA4tbDG791glrXu5xpj2EVk/Avv1evXj06Otr93osjhBBCCFHFCHeHcJNwlnCZ+Ij7ZDaIvuJleX0tx7PVqFwpcSsiASxuJfwevIuR4fcz84HpOzc3r1q1+Li4WLtA6Q0RCyGEEEJUcYrfHOfgMuE44T7hRIVo3RJdL8WBxa2IBLC4lShP7NdiXnqUEx0dFRcXF1ygVOBXCCGEEOIKHtco8A//s+9DwonClXIPUxxY/J6QABa3Eu46pbvcGK5+7U9m1g5M4pGR7jvctUIphBBCCBGKcaWKnvjFccJ9wm/ClfJGd8NvtQtxyYS4VZAAFrcM3uk1/M5n9xim5YKCwLvdo6IiY2KineAcbVc5HSGEEEII4cFGgF0pi/uEE4UrZZ4EdkrTwO6eWE5xJ02ISo4EsLhl8HnezF7inc+u0GXNkkk5NjYmMjJSN+cIIYQQQlwV17nCfcKJwpWy99OVFgf2imE5WuIWQgJY3Bp4d1nwFX/dkfcAX+A1v4H7n/kQGRlln2bx602/QgghhBBl4lG2jnGibEQh9D5nf9jrkbxOmhCVHwlgcQvgD3tpu7tnQ8iGWI65IaegoIDFy+joSHt6yP5YQgghhBAiBG/AACcKcKi8D505xW/E83pl/rDtSIWotEgAi1uAEKHreILA4RtiFRQEViuZtSMiIty3HykCLIQQQghRBq6/hPuEE4UrhUOFW1XaxlfhjpncLXFLIAEsbgHC73MO+dLxSGKWKvkYGVm0nYOjjRmEEEIIIcqBx3Hy4UrhUOFWlcf78n4pRCVHAlhUdkLurnG/DFl3dIrdKW2/0cYMQgghhBDlxeM4FT0M7L23OTzk657l1yuRxK2DBLCo1HhFb+nbPhf7YP716aVHQgghhBDXR/DFSFcUb7jT5YS9GMnRxiviVkACWFRqwtcUvd+E7MHgXAkXK+orhBBCCHH9uBHg4i5WsV1I/SU9HiwfTFRyJIBFpcY7n4ZMqe4SY8itOBylO3CEEEIIIX4N/iKKvWvDdb3CXTLdBS1uFaIcISo3ERERdgt+Pjiem22806t3Ojarlbr/WQghhBDi+jHuls/eVed93Nd+CLkvz7x6I7Bjlv3gCFGJUQRYVGr8YW9dD/m+lPfROUIIIYQQ4tfg3gIdcuez/fWqTpoQlRMJYFF58RffeLDEu2v8xTfEMn9K/gohhBBC3BB8HhcrgD/s5ZTe59T8xfcrFaISIgEsKin+4jtdlfbBPdizQqk5VwghhBDiBoBb5UrcEu+/K+2DNLCotOgZYFFJCdlaMOTtR07xd697dyDUhFtJCGk1n3aG9OAPe5F11TFOuGMU7idVkEFKnBzUMysP/rCXi3r/VBuFUKLGUH8WNxyvrxVy5XKKX85Ki1IIUdmQABaVFPeibnfAcr+0Eytfhlz4/Vf26HcqgnIuZ4a8GKCcx4d/DvmmjJ+ccrxzLzxgfq0JXrUkxZ8I4nOxx4Gc4g8IXcel8VpyvzaDlKfHhLjg5Wnc8DqGHO8vZRc3f9jrvkIS5sASyx/eRuVxjsuQo9fhu5Sz25eHivCcfGHPrYV8L35bTOcp+XtHhFGaWWQucWNhVPrD3m/kfuPdoNT+ZD00J2ynaCEqDxLAojJilxvt/s/u9GqnVKt+7WG+sDcAmy8rRAGHa4YSj3F/cv8tjwYuz68lihmnHHjLE1LOciYYkkLZJwYve1d+9Ye9LMG5dhetNIOXmLsna6e0fHye6jjFnmgq+RSf53LuK7flvXX3lay+ij21XuLxIWWwj2P5SupaZZzrlGL5Mo68Dnzl6/bhI+i6c7w+wvqJvLTKgpnAfWqO8iNbiYrGulUhq9jeK5qrgV1vzfG8wkNdVFRCJIBFZcQXFnBzP3vn0xC1EFQFFTLVepVP+Gzukd/XdtNvSOTNc0UpSrWMpLy/lpaL37yToEQpVf4EyxBa7gHhmse9FvqKP6pddlKl4S2bN7XSukqwpUpOx1/KrbAlnYIB/SHHlC2DvdX0lbTWUPz0kvfSdE8Pa4hiEeASg8y+sIiuN19/8ehuiXXx/+oI8FXPzcrK2rfvQFra5fbt29epUzs7O/vUqTP01rp161SvXt2+ReM6CnDV4tkPly9fvnDhQlRUVN26dePj4x1RObBDh2kjLS0tNfVUXFxcUlLD6Ojo6+6QlRB/8a0c3WnHLL1dWwVtUrm5uefPn2dA1axZs1atWhU0dkRVxl4lQrwg759ufCJcHqsrisqJBLCojPjDHh+1b5Line truncated
|
||||
|
Before Width: | Height: | Size: 231 KiB |
@@ -1,65 +0,0 @@
|
||||
name: Publish AUR package
|
||||
|
||||
# See packaging/aur/README.md.
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
release_tag:
|
||||
required: true
|
||||
type: string
|
||||
pkgrel:
|
||||
required: false
|
||||
default: "1"
|
||||
type: string
|
||||
secrets:
|
||||
AUR_SSH_PRIVATE_KEY:
|
||||
required: true
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
release_tag:
|
||||
description: "Release tag to publish"
|
||||
required: true
|
||||
type: string
|
||||
pkgrel:
|
||||
description: "Arch package release override"
|
||||
required: false
|
||||
default: "1"
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: publish-aur
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Validate and publish
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 30
|
||||
container:
|
||||
image: archlinux:base-devel
|
||||
|
||||
steps:
|
||||
- name: Install Arch packaging tools
|
||||
run: pacman -Syu --noconfirm --needed git github-cli jq namcap openssh sudo
|
||||
|
||||
- name: Checkout packaging sources
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Create unprivileged build user
|
||||
run: |
|
||||
useradd --create-home builder
|
||||
install -Dm0440 /dev/stdin /etc/sudoers.d/builder <<'EOF'
|
||||
builder ALL=(root) NOPASSWD: /usr/bin/pacman
|
||||
EOF
|
||||
|
||||
- name: Validate and publish package sources
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||
PKGREL: ${{ inputs.pkgrel || '1' }}
|
||||
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||
run: packaging/aur/scripts/release.sh
|
||||
@@ -856,16 +856,6 @@ jobs:
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ github.token }}
|
||||
|
||||
publish_aur:
|
||||
name: Publish AUR package
|
||||
needs: [preflight, release]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' }}
|
||||
uses: ./.github/workflows/publish-aur.yml
|
||||
with:
|
||||
release_tag: ${{ needs.preflight.outputs.tag }}
|
||||
secrets:
|
||||
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||
|
||||
deploy_web:
|
||||
name: Deploy hosted web app
|
||||
needs: [preflight, relay_public_config, release]
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
---
|
||||
title: UI Consistency
|
||||
model: claude-opus-5
|
||||
effort: high
|
||||
input: full_diff
|
||||
tools:
|
||||
- browse_code
|
||||
- git_tools
|
||||
- github_api_read_only
|
||||
- modify_pr
|
||||
include:
|
||||
- "apps/web/src/**/*.ts"
|
||||
- "apps/web/src/**/*.tsx"
|
||||
- "apps/web/src/**/*.css"
|
||||
conclusion: failure
|
||||
showToolCalls: true
|
||||
---
|
||||
|
||||
# UI consistency review
|
||||
|
||||
Review changed web UI code and directly affected call sites for consistency with the shared component system, Tailwind ownership, and the behavioral constraints below. Apply these rules when a pull request creates, moves, or modifies controls or styling. Do not demand unrelated repository-wide cleanup.
|
||||
|
||||
The goal is not to minimize CSS or class counts at any cost. The goal is to put each behavior in the smallest correct owner while preserving interaction, theming, accessibility, layout, and browser behavior.
|
||||
|
||||
## Shared controls and variants
|
||||
|
||||
- Prefer the core UI primitives in `apps/web/src/components/ui` over native controls or locally reconstructed primitives. In ordinary product UI, a raw `<button>` that recreates `Button`, a raw input that recreates `Input` or `InputGroup`, or a local trigger that recreates `Select`, `Toggle`, or `Menu` is a concrete finding.
|
||||
- Do not flag raw elements that intentionally implement a semantic row, tab, resize handle, swatch, image target, editor surface, or another interaction whose behavior or geometry differs from the core primitive.
|
||||
- When multiple call sites repeat the same durable geometry or treatment, prefer a named primitive size or variant. Examples include compact controls, micro icon actions, muted ghost actions, and glass actions. Keep contextual layout, width, and color at the call site.
|
||||
- Flag large call-site class strings that override a primitive's core height, radius, padding, focus ring, cursor, hit target, or base state colors. Prefer extending the primitive contract when the same pattern is genuinely shared.
|
||||
- Preserve accessibility and interaction semantics during migrations: focus-visible rings, disabled behavior, loading state, keyboard behavior, pointer cursor, `aria-*`, Base UI or Radix render/close props, and coarse-pointer hit targets.
|
||||
- Do not require tests for a tiny visual-only class migration. Require focused tests when primitive composition changes behavior, prop forwarding, state transitions, keyboard handling, or width/defaulting logic.
|
||||
|
||||
## CSS and Tailwind ownership
|
||||
|
||||
- Ordinary one-owner presentation belongs in the owning TS or TSX module as static Tailwind classes or owner-level CSS variables. Examples include local geometry, spacing, typography, backgrounds, borders, simple vendor pseudo-elements, and component-only positioning.
|
||||
- Keep global CSS when it is genuinely reusable or behaviorally complex: generated markdown or imperative DOM, custom elements and shadow roots, masks, shared or complex pseudo-elements, animations, glass composition, runtime theme variables, safe-area calculations, scrollbar-lane preservation, Electron drag regions, and browser/vendor integration. Simple owner-local pseudo-elements may still belong in the owning module.
|
||||
- Before calling a selector dead, trace literal, dynamic, generated, imperative, test, custom-element, and shadow-root consumers. Search both the emitted class string and any class-valued field names through their final DOM sink. A helper returning a class is not proof that it is rendered, and a missed downstream property read can make a deletion unsafe.
|
||||
- Flag duplicate declarations only after comparing cascade layer, selector specificity, inheritance, runtime theme scope, media/variant scope, and the final owning element. Textually identical declarations are not necessarily behaviorally redundant.
|
||||
- When moving CSS into Tailwind, preserve selector scope and cascade ownership. A utility at the owner is preferable to a fragile global override that depends on stylesheet order.
|
||||
- Do not request moving complex global behavior into arbitrary Tailwind merely to reduce `index.css`. Do not preserve ordinary one-owner CSS merely because it already exists globally.
|
||||
|
||||
## Themes and generated CSS
|
||||
|
||||
- Use the project variants for theme-only declarations:
|
||||
- dark-only declarations use `@variant dark`;
|
||||
- light-only declarations use `@variant light`;
|
||||
- raw `.dark` should remain only in the `dark` and `light` custom-variant definitions.
|
||||
- Preserve custom themes and runtime token bridges. Removing a variable or selector is safe only when all runtime, inspector, generated, and theme-palette consumers are accounted for.
|
||||
- Inspect emitted production CSS after unusual variants, arbitrary selectors, nested pseudo-elements, or attribute matching. Source syntax that looks valid is insufficient.
|
||||
- Flag malformed or empty emitted selectors such as empty `:is()` or `:not(:is())`, selector branches that can never match their own class attribute, and transformations that silently drop the intended rule.
|
||||
- Prefer source-level logic over clever selectors when behavior depends on consumer-provided class strings. Preserve `MenuPopup`'s current defaulting contract: a string `className` containing a `w-*`, `min-w-*`, or `max-w-*` utility after variant prefixes are stripped suppresses `min-w-32`; a string without one and a functional/non-string `className` keep the default. Arbitrary width values count as width utilities, and the consumer class must be merged last so it retains control. Do not replace this with a raw class-attribute substring selector.
|
||||
- Do not fail solely because a valid emitted selector is verbose or because a source rule uses an intentional custom property.
|
||||
|
||||
## Scroll and virtualized lists
|
||||
|
||||
- `ScrollArea` owns and masks its Base UI viewport. A virtualized list usually owns a native scrolling element and cannot automatically reuse viewport-specific `ScrollArea` behavior.
|
||||
- Repeated native or virtualized overflow fades should use the shared virtualized-scroll-fade contract rather than component-named mask selectors.
|
||||
- Preserve runtime top and bottom overflow state. Do not replace dynamic fades with an always-on static mask.
|
||||
- Preserve fade geometry and keep the native scrollbar lane opaque so the track and thumb stay visible and usable. A visually similar mask that fades the scrollbar is a regression.
|
||||
- Verify actual scroll behavior when changing virtualizers, masks, overflow ownership, or scrollbar selectors. Source-level class comparison is not enough.
|
||||
|
||||
## Visual and layout preservation
|
||||
|
||||
- Preserve responsive geometry, titlebar insets, panel and inline-preview modes, desktop Electron layout, light and dark contrast, clipping, radius, and composable shadows.
|
||||
- For meaningful visual changes, prefer available real-app evidence using the actual component and state. A mock recreation does not validate the real component. Light and dark evidence is useful when theme-sensitive styles change, but missing or inaccessible evidence alone is not a finding; report only a concrete regression supported by the diff, code, or available artifacts.
|
||||
- Do not treat a screenshot as proof of keyboard, overflow, scrollbar, responsive, or runtime-theme behavior. Pair visual evidence with source, computed-style, emitted-CSS, or interaction checks as appropriate.
|
||||
- Be alert to shared primitive color indirection. When a primitive routes icon color through a CSS variable, ensure migrated contextual icons retain their intended tone, including pressed and disabled states.
|
||||
|
||||
## Change discipline
|
||||
|
||||
- Review the pull request's changed scope and directly affected consumers. Do not turn a focused PR into a demand for unrelated legacy cleanup.
|
||||
- Prefer the smallest durable contract over a component-specific workaround or a broad abstraction with one consumer.
|
||||
- Preserve intentional exceptions and comments that explain browser, virtualizer, theme, or Electron constraints.
|
||||
- If a proposed cleanup cannot prove ownership or semantic equivalence, ask for evidence or leave it unchanged rather than guessing.
|
||||
- Select verification gates according to the changed behavior: typecheck or focused tests for typing and interaction contracts, production build and emitted-CSS inspection for Tailwind or selector transformations, and real-app evidence for meaningful visual behavior when available. These gates are complementary when applicable, but do not require every gate for tiny visual-only migrations or fail solely because an artifact the configured tools cannot produce is absent.
|
||||
|
||||
## Reporting
|
||||
|
||||
Report only concrete violations introduced by changed lines or behavior, plus pre-existing behavior that the patch directly makes relevant or worsens. Touching a large file does not make unrelated retained issues reportable. Prefer precise inline comments on the smallest relevant line range. Explain the broken behavior or ownership rule, not merely the preferred syntax, and state the smallest expected fix. A clear consistency or regression risk may fail the check. Do not fail for optional aesthetic preferences, harmless class ordering, or unrelated legacy code.
|
||||
|
||||
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
|
||||
@@ -4,9 +4,7 @@
|
||||
|
||||
We are not actively accepting contributions right now.
|
||||
|
||||
You can still report a bug or open a PR, but please do so knowing there is a high chance we close it, defer it forever, or never look at it.
|
||||
|
||||
Feature requests and proposals belong in [Ideas discussions](https://github.com/pingdotgg/t3code/discussions/categories/ideas), not issues.
|
||||
You can still open an issue or PR, but please do so knowing there is a high chance we close it, defer it forever, or never look at it.
|
||||
|
||||
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
|
||||
|
||||
@@ -52,9 +50,9 @@ If the change depends on motion, timing, transitions, or interaction details, in
|
||||
|
||||
If we have to guess what changed, we are much less likely to review it.
|
||||
|
||||
## Discuss Changes First
|
||||
## Issues First
|
||||
|
||||
If you are thinking about a non-trivial change, start a discussion first. Issues are reserved for bug reports.
|
||||
If you are thinking about a non-trivial change, open an issue first.
|
||||
|
||||
That still does not mean we will want the PR, but it gives you a chance to avoid wasting your time.
|
||||
|
||||
|
||||
@@ -51,20 +51,10 @@ brew install --cask t3-code
|
||||
|
||||
#### Arch Linux (AUR)
|
||||
|
||||
Stable:
|
||||
|
||||
```bash
|
||||
yay -S t3code-bin
|
||||
```
|
||||
|
||||
Nightly:
|
||||
|
||||
```bash
|
||||
yay -S t3code-nightly-bin
|
||||
```
|
||||
|
||||
The AUR packaging is maintained in this repository under [`packaging/aur`](./packaging/aur).
|
||||
|
||||
## Some notes
|
||||
|
||||
We are very very early in this project. Expect bugs.
|
||||
@@ -113,8 +103,6 @@ Checkout their getting started guide for more information: https://viteplus.dev/
|
||||
vp i
|
||||
```
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before reporting a bug or opening a PR.
|
||||
|
||||
Have a feature request? Start an [Ideas discussion](https://github.com/pingdotgg/t3code/discussions/categories/ideas).
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
||||
@@ -1,33 +0,0 @@
|
||||
<svg width="1080" height="760" viewBox="0 0 540 380" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<linearGradient id="latest-surface" x1="0" y1="0" x2="540" y2="380" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#FAFAF9"/>
|
||||
<stop offset="1" stop-color="#F5F5F4"/>
|
||||
</linearGradient>
|
||||
<radialGradient id="latest-light" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(430 0) rotate(152) scale(320 150)">
|
||||
<stop stop-color="#FFFFFF"/>
|
||||
<stop offset="1" stop-color="#FFFFFF" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
</defs>
|
||||
|
||||
<rect width="540" height="380" fill="url(#latest-surface)"/>
|
||||
<rect width="540" height="112" fill="#EFEFED"/>
|
||||
<rect width="540" height="112" fill="url(#latest-light)"/>
|
||||
<path d="M0 111.5H540" stroke="#18181B" stroke-opacity="0.08"/>
|
||||
<path d="M32 28H64" stroke="#18181B" stroke-width="2"/>
|
||||
|
||||
<g font-family="-apple-system, BlinkMacSystemFont, sans-serif" fill="#18181B">
|
||||
<text x="32" y="50" font-size="12" font-weight="600" letter-spacing="1.4">T3 CODE</text>
|
||||
<text x="32" y="82" font-size="22" font-weight="600" letter-spacing="-0.45">Desktop</text>
|
||||
<text x="508" y="50" text-anchor="end" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="8.5" font-weight="600" letter-spacing="1.2" fill="#71717A">LATEST RELEASE</text>
|
||||
</g>
|
||||
|
||||
<path d="M196 224C242 239 307 201 362 220" stroke="#71717A" stroke-width="1.5" stroke-linecap="round" stroke-dasharray="1 7" opacity="0.42"/>
|
||||
<circle cx="362" cy="220" r="2" fill="#71717A" opacity="0.55"/>
|
||||
<path d="M176 204V227L182 221L187.5 232L192 229.8L186.5 219H194L176 204Z" fill="#71717A" stroke="#F7F7F5" stroke-width="1.5" stroke-linejoin="round"/>
|
||||
|
||||
<g font-family="-apple-system, BlinkMacSystemFont, sans-serif" text-anchor="middle">
|
||||
<text x="270" y="322" font-size="13" font-weight="600" letter-spacing="-0.1" fill="#18181B">Drag T3 Code to Applications</text>
|
||||
<text x="270" y="345" font-size="9.5" fill="#71717A">Open it from Applications when the copy finishes.</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.0 KiB |
@@ -1,64 +0,0 @@
|
||||
<svg width="1080" height="760" viewBox="0 0 540 380" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<linearGradient id="night-sky" x1="28" y1="0" x2="510" y2="112" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#07152F"/>
|
||||
<stop offset="0.52" stop-color="#151443"/>
|
||||
<stop offset="1" stop-color="#32155B"/>
|
||||
</linearGradient>
|
||||
<radialGradient id="night-glow" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(420 18) rotate(157) scale(260 126)">
|
||||
<stop stop-color="#5165D8" stop-opacity="0.42"/>
|
||||
<stop offset="0.55" stop-color="#283075" stop-opacity="0.15"/>
|
||||
<stop offset="1" stop-color="#111635" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="night-cloud" x1="18" y1="62" x2="260" y2="112" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#4EA4FF" stop-opacity="0.5"/>
|
||||
<stop offset="0.52" stop-color="#696FEA" stop-opacity="0.62"/>
|
||||
<stop offset="1" stop-color="#A85BEA" stop-opacity="0.5"/>
|
||||
</linearGradient>
|
||||
<filter id="night-soft" x="-24" y="35" width="588" height="101" filterUnits="userSpaceOnUse">
|
||||
<feGaussianBlur stdDeviation="4"/>
|
||||
</filter>
|
||||
</defs>
|
||||
|
||||
<rect width="540" height="380" fill="#F7F7F5"/>
|
||||
<rect width="540" height="112" fill="url(#night-sky)"/>
|
||||
<rect width="540" height="112" fill="url(#night-glow)"/>
|
||||
|
||||
<g fill="#E4EAFF">
|
||||
<circle cx="20" cy="18" r="0.8" opacity="0.82"/>
|
||||
<circle cx="76" cy="27" r="0.55" opacity="0.55"/>
|
||||
<circle cx="133" cy="13" r="0.65" opacity="0.7"/>
|
||||
<circle cx="198" cy="28" r="0.5" opacity="0.5"/>
|
||||
<circle cx="258" cy="15" r="0.75" opacity="0.8"/>
|
||||
<circle cx="326" cy="29" r="0.5" opacity="0.55"/>
|
||||
<circle cx="384" cy="12" r="0.65" opacity="0.72"/>
|
||||
<circle cx="455" cy="26" r="0.55" opacity="0.58"/>
|
||||
<circle cx="517" cy="15" r="0.75" opacity="0.78"/>
|
||||
</g>
|
||||
<g stroke="#EEF2FF" stroke-linecap="round" stroke-width="0.65" opacity="0.68">
|
||||
<path d="M104 30V34M102 32H106"/>
|
||||
<path d="M448 24V28M446 26H450"/>
|
||||
</g>
|
||||
|
||||
<g filter="url(#night-soft)">
|
||||
<path d="M-12 112V101C-12 87 0 76 14 76C18 63 30 54 44 54C58 54 70 62 74 75C79 70 86 67 94 67C110 67 123 79 124 95C132 96 138 101 141 112H-12Z" fill="url(#night-cloud)"/>
|
||||
<path d="M374 112C375 98 387 87 401 87C405 72 418 62 434 62C450 62 463 72 467 87C478 87 488 94 492 104C506 103 518 106 526 112H374Z" fill="url(#night-cloud)" opacity="0.82"/>
|
||||
</g>
|
||||
<path d="M0 111.5H540" stroke="#050A19" stroke-opacity="0.3"/>
|
||||
<path d="M32 28H64" stroke="#FFFFFF" stroke-width="2"/>
|
||||
|
||||
<g font-family="-apple-system, BlinkMacSystemFont, sans-serif" fill="#FFFFFF">
|
||||
<text x="32" y="50" font-size="12" font-weight="600" letter-spacing="1.4">T3 CODE</text>
|
||||
<text x="32" y="82" font-size="22" font-weight="600" letter-spacing="-0.45">Desktop</text>
|
||||
<text x="508" y="50" text-anchor="end" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="8.5" font-weight="600" letter-spacing="1.2" opacity="0.84">NIGHTLY BUILD</text>
|
||||
</g>
|
||||
|
||||
<path d="M196 224C242 239 307 201 362 220" stroke="#71717A" stroke-width="1.5" stroke-linecap="round" stroke-dasharray="1 7" opacity="0.42"/>
|
||||
<circle cx="362" cy="220" r="2" fill="#71717A" opacity="0.55"/>
|
||||
<path d="M176 204V227L182 221L187.5 232L192 229.8L186.5 219H194L176 204Z" fill="#71717A" stroke="#F7F7F5" stroke-width="1.5" stroke-linejoin="round"/>
|
||||
|
||||
<g font-family="-apple-system, BlinkMacSystemFont, sans-serif" text-anchor="middle">
|
||||
<text x="270" y="322" font-size="13" font-weight="600" letter-spacing="-0.1" fill="#18181B">Drag T3 Code to Applications</text>
|
||||
<text x="270" y="345" font-size="9.5" fill="#71717A">Open it from Applications when the copy finishes.</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 279 KiB |
|
After Width: | Height: | Size: 313 KiB |
@@ -20,14 +20,14 @@ export const APP_BUNDLE_ID = isDevelopment
|
||||
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
|
||||
: "com.t3tools.t3code";
|
||||
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
|
||||
const LAUNCHER_VERSION = 15;
|
||||
const LAUNCHER_VERSION = 14;
|
||||
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = NodePath.join(
|
||||
repoRoot,
|
||||
"assets",
|
||||
"dev",
|
||||
"blueprint-macos-1024.png",
|
||||
);
|
||||
const productionMacIconPngPath = NodePath.join(repoRoot, "assets", "prod", "black-macos-1024.png");
|
||||
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
|
||||
const hostPlatform = NodeOS.platform();
|
||||
|
||||
@@ -165,22 +165,15 @@ function registerMacLauncherBundle(appBundlePath) {
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveMacLauncherIconPaths(runtimeDir, development = isDevelopment) {
|
||||
return {
|
||||
sourceIconPath: development ? developmentMacIconPngPath : productionMacIconPngPath,
|
||||
generatedIconPath: NodePath.join(runtimeDir, development ? "icon-dev.icns" : "icon-prod.icns"),
|
||||
};
|
||||
}
|
||||
|
||||
function ensureMacIconIcns(runtimeDir) {
|
||||
const { sourceIconPath, generatedIconPath } = resolveMacLauncherIconPaths(runtimeDir);
|
||||
function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
const generatedIconPath = NodePath.join(runtimeDir, "icon-dev.icns");
|
||||
NodeFS.mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
if (!NodeFS.existsSync(sourceIconPath)) {
|
||||
throw new Error(`Desktop macOS icon source is missing at ${sourceIconPath}`);
|
||||
if (!NodeFS.existsSync(developmentMacIconPngPath)) {
|
||||
return defaultIconPath;
|
||||
}
|
||||
|
||||
const sourceMtimeMs = NodeFS.statSync(sourceIconPath).mtimeMs;
|
||||
const sourceMtimeMs = NodeFS.statSync(developmentMacIconPngPath).mtimeMs;
|
||||
if (
|
||||
NodeFS.existsSync(generatedIconPath) &&
|
||||
NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
|
||||
@@ -198,7 +191,7 @@ function ensureMacIconIcns(runtimeDir) {
|
||||
"-z",
|
||||
String(size),
|
||||
String(size),
|
||||
sourceIconPath,
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
|
||||
]);
|
||||
@@ -208,7 +201,7 @@ function ensureMacIconIcns(runtimeDir) {
|
||||
"-z",
|
||||
String(retinaSize),
|
||||
String(retinaSize),
|
||||
sourceIconPath,
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
]);
|
||||
@@ -216,6 +209,12 @@ function ensureMacIconIcns(runtimeDir) {
|
||||
|
||||
runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
|
||||
return generatedIconPath;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
"[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
|
||||
error,
|
||||
);
|
||||
return defaultIconPath;
|
||||
} finally {
|
||||
NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
|
||||
}
|
||||
@@ -298,7 +297,7 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
const launcherBinaryPath = isDevelopment
|
||||
? developmentPaths.launcherBinaryPath
|
||||
: runtimeElectronBinaryPath;
|
||||
const iconPath = ensureMacIconIcns(runtimeDir);
|
||||
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
|
||||
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
|
||||
|
||||
NodeFS.mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
@@ -3,7 +3,6 @@ import { assert, describe, it } from "vite-plus/test";
|
||||
import {
|
||||
makeDevelopmentLauncherScript,
|
||||
resolveElectronBinaryPath,
|
||||
resolveMacLauncherIconPaths,
|
||||
resolveMacLauncherPaths,
|
||||
} from "./electron-launcher.mjs";
|
||||
|
||||
@@ -79,14 +78,4 @@ describe("electron development launcher", () => {
|
||||
);
|
||||
assert.notInclude(script, "node_modules/electron");
|
||||
});
|
||||
|
||||
it("derives launcher icons from canonical development and production assets", () => {
|
||||
const development = resolveMacLauncherIconPaths("/runtime", true);
|
||||
const production = resolveMacLauncherIconPaths("/runtime", false);
|
||||
|
||||
assert.match(development.sourceIconPath, /assets\/dev\/blueprint-macos-1024\.png$/);
|
||||
assert.equal(development.generatedIconPath, "/runtime/icon-dev.icns");
|
||||
assert.match(production.sourceIconPath, /assets\/prod\/black-macos-1024\.png$/);
|
||||
assert.equal(production.generatedIconPath, "/runtime/icon-prod.icns");
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,7 @@ import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopState from "./DesktopState.ts";
|
||||
import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";
|
||||
import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
|
||||
import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
|
||||
|
||||
@@ -286,6 +287,7 @@ const startup = Effect.gen(function* () {
|
||||
yield* appIdentity.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* updates.configure;
|
||||
yield* DesktopRemoteUpdates.listen;
|
||||
yield* linuxUrlHandler.register;
|
||||
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
|
||||
}).pipe(Effect.withSpan("desktop.startup"));
|
||||
|
||||
@@ -40,7 +40,6 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
systemLocale: Effect.succeed("en-US"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
|
||||
@@ -3,7 +3,6 @@ import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as DesktopAssets from "./DesktopAssets.ts";
|
||||
@@ -23,45 +22,6 @@ const environmentLayer = DesktopEnvironment.layer({
|
||||
}).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))));
|
||||
|
||||
describe("DesktopAssets", () => {
|
||||
it.effect("uses canonical source-tree icons for unpackaged development", () =>
|
||||
Effect.gen(function* () {
|
||||
const developmentEnvironmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/dist-electron",
|
||||
homeDirectory: "/Users/alice",
|
||||
platform: "linux",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: false,
|
||||
resourcesPath: "/repo/apps/desktop/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({ VITE_DEV_SERVER_URL: "http://localhost:5733" }),
|
||||
),
|
||||
),
|
||||
);
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
exists: (path) => Effect.succeed(String(path).includes("/assets/dev/")),
|
||||
});
|
||||
const assets = yield* DesktopAssets.DesktopAssets.pipe(
|
||||
Effect.provide(
|
||||
DesktopAssets.layer.pipe(
|
||||
Layer.provide(Layer.merge(fileSystemLayer, developmentEnvironmentLayer)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const icons = yield* assets.iconPaths;
|
||||
|
||||
assert.match(Option.getOrThrow(icons.ico), /assets\/dev\/blueprint-windows\.ico$/);
|
||||
assert.match(Option.getOrThrow(icons.png), /assets\/dev\/blueprint-universal-1024\.png$/);
|
||||
assert.isTrue(Option.isNone(icons.icns));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves the failed asset candidate and filesystem cause", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileName = "custom.bin";
|
||||
|
||||
@@ -61,35 +61,6 @@ const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(func
|
||||
return Option.none<string>();
|
||||
});
|
||||
|
||||
const sourceTreeIconFileNames = {
|
||||
dev: {
|
||||
ico: "blueprint-windows.ico",
|
||||
macPng: "blueprint-macos-1024.png",
|
||||
universalPng: "blueprint-universal-1024.png",
|
||||
},
|
||||
prod: {
|
||||
ico: "t3-black-windows.ico",
|
||||
macPng: "black-macos-1024.png",
|
||||
universalPng: "black-universal-1024.png",
|
||||
},
|
||||
} as const;
|
||||
|
||||
function resolveSourceTreeIconPath(
|
||||
environment: DesktopEnvironment.DesktopEnvironment["Service"],
|
||||
ext: keyof DesktopIconPaths,
|
||||
): string | undefined {
|
||||
if (environment.isPackaged || ext === "icns") return undefined;
|
||||
const brand = environment.isDevelopment ? "dev" : "prod";
|
||||
const fileNames = sourceTreeIconFileNames[brand];
|
||||
const fileName =
|
||||
ext === "ico"
|
||||
? fileNames.ico
|
||||
: environment.platform === "darwin"
|
||||
? fileNames.macPng
|
||||
: fileNames.universalPng;
|
||||
return environment.path.join(environment.rootDir, "assets", brand, fileName);
|
||||
}
|
||||
|
||||
const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
|
||||
ext: keyof DesktopIconPaths,
|
||||
): Effect.fn.Return<
|
||||
@@ -99,20 +70,20 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const sourceTreeIconPath = resolveSourceTreeIconPath(environment, ext);
|
||||
if (sourceTreeIconPath !== undefined) {
|
||||
const sourceTreeIconExists = yield* fileSystem.exists(sourceTreeIconPath).pipe(
|
||||
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
|
||||
const developmentDockIconPath = environment.developmentDockIconPath;
|
||||
const developmentDockIconExists = yield* fileSystem.exists(developmentDockIconPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopAssetProbeError({
|
||||
fileName: `icon.${ext}`,
|
||||
candidatePath: sourceTreeIconPath,
|
||||
fileName: "icon.png",
|
||||
candidatePath: developmentDockIconPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (sourceTreeIconExists) {
|
||||
return Option.some(sourceTreeIconPath);
|
||||
if (developmentDockIconExists) {
|
||||
return Option.some(developmentDockIconPath);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +65,6 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.rootDir, "/repo");
|
||||
assert.equal(environment.appRoot, "/repo");
|
||||
assert.equal(environment.serverRoot, "/repo");
|
||||
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
|
||||
assert.equal(environment.backendCwd, "/repo");
|
||||
assert.equal(environment.appUserModelId, "com.t3tools.t3code.dev");
|
||||
@@ -99,24 +98,6 @@ describe("DesktopEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses the packaged Windows server sidecar as the backend root", () =>
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* makeEnvironment({
|
||||
platform: "win32",
|
||||
isPackaged: true,
|
||||
appPath: "/install/resources/app.asar",
|
||||
resourcesPath: "/install/resources",
|
||||
});
|
||||
|
||||
assert.equal(environment.appRoot, "/install/resources/app.asar");
|
||||
assert.equal(environment.serverRoot, "/install/resources/server.asar");
|
||||
assert.equal(
|
||||
environment.backendEntryPath,
|
||||
"/install/resources/server.asar/apps/server/dist/bin.mjs",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps implicit development state separate from production state", () =>
|
||||
Effect.gen(function* () {
|
||||
const development = yield* makeEnvironment(
|
||||
|
||||
@@ -52,13 +52,6 @@ export class DesktopEnvironment extends Context.Service<
|
||||
readonly browserArtifactsDir: string;
|
||||
readonly rootDir: string;
|
||||
readonly appRoot: string;
|
||||
// Root of the tree containing apps/server/dist and node_modules for the
|
||||
// backend. Equals appRoot everywhere except packaged Windows, where the
|
||||
// server tree ships as the resources/server.asar sidecar (see
|
||||
// scripts/build-desktop-artifact.ts) that the asar-aware
|
||||
// ELECTRON_RUN_AS_NODE primary reads in place and the WSL backend
|
||||
// extracts on demand (see DesktopWslServerTree).
|
||||
readonly serverRoot: string;
|
||||
readonly backendEntryPath: string;
|
||||
readonly backendCwd: string;
|
||||
readonly preloadPath: string;
|
||||
@@ -82,6 +75,7 @@ export class DesktopEnvironment extends Context.Service<
|
||||
readonly runtimeInfo: DesktopRuntimeInfo;
|
||||
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
|
||||
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
|
||||
readonly developmentDockIconPath: string;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopEnvironment") {}
|
||||
|
||||
@@ -163,10 +157,6 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
});
|
||||
const rootDir = path.resolve(input.dirname, "../../..");
|
||||
const appRoot = input.isPackaged ? input.appPath : rootDir;
|
||||
const serverRoot =
|
||||
input.isPackaged && input.platform === "win32"
|
||||
? path.join(input.resourcesPath, "server.asar")
|
||||
: appRoot;
|
||||
const branding = resolveDesktopAppBranding({
|
||||
isDevelopment,
|
||||
appVersion: input.appVersion,
|
||||
@@ -208,8 +198,7 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
|
||||
rootDir,
|
||||
appRoot,
|
||||
serverRoot,
|
||||
backendEntryPath: path.join(serverRoot, "apps/server/dist/bin.mjs"),
|
||||
backendEntryPath: path.join(appRoot, "apps/server/dist/bin.mjs"),
|
||||
backendCwd: input.isPackaged ? homeDirectory : appRoot,
|
||||
preloadPath: path.join(input.dirname, "preload.cjs"),
|
||||
appUpdateYmlPath: input.isPackaged
|
||||
@@ -269,6 +258,7 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
path.join(resourcesPath, "resources", fileName),
|
||||
path.join(resourcesPath, fileName),
|
||||
],
|
||||
developmentDockIconPath: path.join(rootDir, "assets", "dev", "blueprint-macos-1024.png"),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ describe("DesktopLifecycle", () => {
|
||||
const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
systemLocale: Effect.succeed("en-US"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
|
||||
@@ -17,7 +17,6 @@ import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
|
||||
import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
|
||||
|
||||
const PersistedServerObservabilitySettingsDocument = Schema.Struct({
|
||||
observability: Schema.Struct({
|
||||
@@ -116,7 +115,6 @@ const withHarness = <A, E, R>(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
),
|
||||
),
|
||||
@@ -155,47 +153,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolvePrimary starts from server.asar without materializing the WSL tree", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const resourcesPath = `${baseDir}/resources`;
|
||||
|
||||
const config = yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
return yield* configuration.resolvePrimary;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(
|
||||
DesktopWslServerTree.DesktopWslServerTree,
|
||||
DesktopWslServerTree.DesktopWslServerTree.of({
|
||||
ensure: Effect.die("Windows primary must not extract the WSL server tree"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
appPath: `${resourcesPath}/app.asar`,
|
||||
platform: "win32",
|
||||
resourcesPath,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(config.entryPath, `${resourcesPath}/server.asar/apps/server/dist/bin.mjs`);
|
||||
assert.equal(config.env.ELECTRON_RUN_AS_NODE, "1");
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl reuses the primary's bootstrap token", () =>
|
||||
withHarness(
|
||||
Effect.gen(function* () {
|
||||
@@ -216,7 +173,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
|
||||
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
|
||||
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(entryPath, "");
|
||||
|
||||
@@ -229,7 +186,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -278,7 +234,7 @@ describe("DesktopBackendConfiguration", () => {
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
|
||||
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
|
||||
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(entryPath, "");
|
||||
|
||||
@@ -294,7 +250,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -431,7 +386,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
|
||||
Layer.provideMerge(failingFileSystemLayer),
|
||||
@@ -473,7 +427,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
@@ -533,7 +486,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -584,7 +536,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
wslOnly: true,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
@@ -622,7 +573,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
wslDistro: "Removed-Distro",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -656,7 +606,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -691,49 +640,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("resolveWsl surfaces sidecar extraction failures through typed preflight", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-backend-config-test-",
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
|
||||
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
|
||||
const failure = Option.getOrThrow(config.preflightFailure);
|
||||
|
||||
assert.isFalse(failure.fatal);
|
||||
assert.equal(failure.retryLimit, 12);
|
||||
assert.include(failure.reason, "could not be extracted");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslServerTree.layerTest({
|
||||
result: {
|
||||
ok: false,
|
||||
reason: "WSL server files could not be extracted",
|
||||
fatal: false,
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -766,7 +672,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(
|
||||
DesktopWslEnvironment.layerTest({
|
||||
isAvailable: true,
|
||||
@@ -803,7 +708,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
wslDistro: "Ubuntu",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
@@ -844,7 +748,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
@@ -890,7 +793,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
|
||||
Layer.provideMerge(
|
||||
makeEnvironmentLayer(baseDir, {
|
||||
@@ -941,7 +843,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
wslDistro: "Ubuntu",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
|
||||
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
|
||||
),
|
||||
@@ -963,7 +864,6 @@ describe("DesktopBackendConfiguration", () => {
|
||||
DesktopBackendConfiguration.layer.pipe(
|
||||
Layer.provideMerge(serverExposureLayer),
|
||||
Layer.provideMerge(DesktopAppSettings.layerTest()),
|
||||
Layer.provideMerge(DesktopWslServerTree.layerTest()),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layer),
|
||||
// isAvailable on win32 only touches the filesystem, never the spawner,
|
||||
// so a die-stub is enough to satisfy the layer's deps.
|
||||
|
||||
@@ -19,7 +19,6 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
|
||||
import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
|
||||
|
||||
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
|
||||
"DesktopBackendObservabilitySettingsReadError",
|
||||
@@ -425,12 +424,10 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
|
||||
never,
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopWslEnvironment.DesktopWslEnvironment
|
||||
| DesktopWslServerTree.DesktopWslServerTree
|
||||
| FileSystem.FileSystem
|
||||
> {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
|
||||
|
||||
// Bind to 0.0.0.0 inside WSL so the backend is reachable both via
|
||||
// WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
|
||||
@@ -467,31 +464,31 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
|
||||
...buildObservabilityFragment(input.observabilitySettings),
|
||||
};
|
||||
|
||||
// In packaged builds the server tree ships inside resources/server.asar —
|
||||
// an archive FILE the Windows primary reads through ELECTRON_RUN_AS_NODE
|
||||
// (asar-aware). The WSL backend launches plain `wsl.exe -- node`, which
|
||||
// can't read an asar, so materialize (or reuse) the extracted copy of the
|
||||
// sidecar before preflighting. In dev the server tree is the real checkout
|
||||
// directory and ensure returns it unchanged.
|
||||
const serverTree = yield* wslServerTree.ensure;
|
||||
const wslAppRoot = serverTree.ok ? serverTree.root : environment.serverRoot;
|
||||
// In packaged builds environment.appRoot is .../resources/app.asar — an
|
||||
// archive FILE. The Windows primary reads its entry through
|
||||
// ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain
|
||||
// `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks
|
||||
// the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts)
|
||||
// to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is
|
||||
// already a real directory, so this is a no-op.
|
||||
const wslAppRoot = environment.isPackaged
|
||||
? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
|
||||
: environment.appRoot;
|
||||
const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
|
||||
|
||||
const preflight = serverTree.ok
|
||||
? yield* runWslPreflight({
|
||||
distro: input.distro,
|
||||
windowsEntryPath: wslEntryPath,
|
||||
windowsRepoRoot: wslAppRoot,
|
||||
// Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
|
||||
// attached to the Windows artifact — see build-desktop-artifact.ts), so the
|
||||
// WSL backend never needs a compiler, node-gyp, or network on first launch.
|
||||
// Compiling from source is a dev-only convenience: a checkout has no shipped
|
||||
// prebuilt, and developers have the toolchain. In packaged builds we instead
|
||||
// surface a clear diagnostic if the prebuilt can't load (unsupported
|
||||
// arch/distro), rather than silently dropping into a fragile runtime build.
|
||||
allowBuild: !environment.isPackaged,
|
||||
})
|
||||
: ({ _tag: "Failed", reason: serverTree.reason, fatal: serverTree.fatal } as const);
|
||||
const preflight = yield* runWslPreflight({
|
||||
distro: input.distro,
|
||||
windowsEntryPath: wslEntryPath,
|
||||
windowsRepoRoot: wslAppRoot,
|
||||
// Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
|
||||
// attached to the Windows artifact — see build-desktop-artifact.ts), so the
|
||||
// WSL backend never needs a compiler, node-gyp, or network on first launch.
|
||||
// Compiling from source is a dev-only convenience: a checkout has no shipped
|
||||
// prebuilt, and developers have the toolchain. In packaged builds we instead
|
||||
// surface a clear diagnostic if the prebuilt can't load (unsupported
|
||||
// arch/distro), rather than silently dropping into a fragile runtime build.
|
||||
allowBuild: !environment.isPackaged,
|
||||
});
|
||||
|
||||
// Every operation after preflight uses the same concrete distro. In
|
||||
// default-tracking mode this closes the race where the system default
|
||||
@@ -613,7 +610,6 @@ export const make = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
|
||||
const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
// SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
|
||||
@@ -669,7 +665,6 @@ export const make = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
});
|
||||
@@ -732,7 +727,6 @@ export const make = Effect.gen(function* () {
|
||||
return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
|
||||
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
|
||||
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
|
||||
Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
);
|
||||
}).pipe(
|
||||
|
||||
@@ -165,6 +165,8 @@ function makeTestInstance(input: MakeInstanceInput) {
|
||||
handleControlForSource: (_sourceId, message) =>
|
||||
(input.desktopTelemetryPublisher?.handleControl ?? (() => Effect.void))(message),
|
||||
removeControlSource: () => Effect.void,
|
||||
publishUpdateReport: () => Effect.void,
|
||||
updateRequests: Stream.empty,
|
||||
...input.desktopTelemetryPublisher,
|
||||
}),
|
||||
);
|
||||
@@ -701,84 +703,6 @@ describe("DesktopBackendManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"re-probes readiness after the first budget expires while the backend is still alive",
|
||||
() =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const requestUrls: Array<string> = [];
|
||||
let requestCount = 0;
|
||||
let readyCount = 0;
|
||||
let readinessTimeoutCount = 0;
|
||||
const firstProbe = yield* Deferred.make<void>();
|
||||
const childExit = yield* Deferred.make<void>();
|
||||
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
makeProcess({
|
||||
exitCode: Deferred.await(childExit).pipe(
|
||||
Effect.as(ChildProcessSpawner.ExitCode(0)),
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// The backend stays 503 through the first *two* readiness budgets
|
||||
// and only becomes healthy (200) for the third round, i.e. it comes
|
||||
// up well after the initial 50ms budget has expired.
|
||||
const httpLayer = httpClientLayer((request) =>
|
||||
Effect.gen(function* () {
|
||||
requestCount += 1;
|
||||
requestUrls.push(request.url);
|
||||
yield* Deferred.succeed(firstProbe, void 0);
|
||||
return responseForRequest(request, requestCount <= 2 ? 503 : 200);
|
||||
}),
|
||||
);
|
||||
|
||||
const runFiber = yield* DesktopBackendManager.runBackendProcess({
|
||||
...baseConfig,
|
||||
desktopTelemetryStream: Stream.empty,
|
||||
readinessTimeout: Duration.millis(50),
|
||||
onReady: () =>
|
||||
Effect.sync(() => {
|
||||
readyCount += 1;
|
||||
}),
|
||||
onReadinessFailure: () =>
|
||||
Effect.sync(() => {
|
||||
readinessTimeoutCount += 1;
|
||||
}),
|
||||
}).pipe(Effect.provide(Layer.merge(spawnerLayer, httpLayer)), Effect.forkChild);
|
||||
|
||||
yield* Deferred.await(firstProbe);
|
||||
assert.equal(readyCount, 0);
|
||||
assert.equal(readinessTimeoutCount, 0);
|
||||
|
||||
// The first 50ms readiness budget expires while the backend still
|
||||
// answers 503. The child is alive and may yet become healthy, so the
|
||||
// probe must start a fresh round instead of stopping permanently —
|
||||
// the pre-fix behavior left the app stuck on "Connecting to WSL…"
|
||||
// forever even though the backend kept running.
|
||||
yield* TestClock.adjust(Duration.millis(50));
|
||||
assert.equal(readinessTimeoutCount, 1);
|
||||
assert.equal(readyCount, 0);
|
||||
|
||||
// The second budget also expires (backend still 503), then the third
|
||||
// round connects. The point is the probe persisted across budgets
|
||||
// while the process was alive instead of giving up after the first.
|
||||
yield* TestClock.adjust(Duration.millis(100));
|
||||
assert.equal(readinessTimeoutCount, 2);
|
||||
assert.equal(readyCount, 1);
|
||||
assert.equal(requestUrls.length, 3);
|
||||
|
||||
yield* Deferred.succeed(childExit, void 0);
|
||||
assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 0);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("starts the configured backend and closes the scoped process on stop", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -563,33 +563,20 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
|
||||
).pipe(Effect.forkScoped),
|
||||
);
|
||||
}
|
||||
// Probe readiness in a loop while the backend process is still alive
|
||||
// instead of giving up after the first budget. A slow cold boot (the
|
||||
// WSL bundle loading across /mnt/c, or a first launch right after an
|
||||
// update) can exceed the initial readiness budget while the backend is
|
||||
// about to come up moments later; a one-shot probe left the app stuck
|
||||
// on "Connecting to WSL…" forever even though the backend kept running
|
||||
// and became healthy. Each round gets a fresh budget, and the forked
|
||||
// loop is torn down with the run scope once the child exits.
|
||||
const probeReadiness = Effect.fn("desktop.backendProcess.probeReadiness")(() =>
|
||||
waitForHttpReady({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
}).pipe(
|
||||
Effect.flatMap(() => options.onReady?.() ?? Effect.void),
|
||||
Effect.as(true),
|
||||
Effect.catchTags({
|
||||
BackendReadinessTimeoutError: (error) =>
|
||||
(options.onReadinessFailure?.(error) ?? Effect.void).pipe(Effect.as(false)),
|
||||
}),
|
||||
),
|
||||
yield* waitForHttpReady({
|
||||
executablePath: options.executablePath,
|
||||
entryPath: options.entryPath,
|
||||
cwd: options.cwd,
|
||||
httpBaseUrl: options.httpBaseUrl,
|
||||
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
|
||||
}).pipe(
|
||||
Effect.tap(() => options.onReady?.() ?? Effect.void),
|
||||
Effect.catchTags({
|
||||
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
|
||||
}),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* probeReadiness().pipe(Effect.repeat({ while: (ready) => !ready }), Effect.forkScoped);
|
||||
|
||||
const exit = yield* handle.exitCode.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
|
||||
@@ -72,6 +72,8 @@ function makePoolLayer(
|
||||
handleControl: () => Effect.void,
|
||||
handleControlForSource: () => Effect.void,
|
||||
removeControlSource: () => Effect.void,
|
||||
publishUpdateReport: () => Effect.void,
|
||||
updateRequests: Stream.empty,
|
||||
}),
|
||||
Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
|
||||
resolvePrimary: Effect.die("unexpected primary config resolve"),
|
||||
|
||||
@@ -8,7 +8,6 @@ const {
|
||||
autoUpdaterRemoveListenerMock,
|
||||
exitMock,
|
||||
getAppPathMock,
|
||||
getSystemLocaleMock,
|
||||
getVersionMock,
|
||||
isDefaultProtocolClientMock,
|
||||
onMock,
|
||||
@@ -30,7 +29,6 @@ const {
|
||||
autoUpdaterRemoveListenerMock: vi.fn(),
|
||||
exitMock: vi.fn(),
|
||||
getAppPathMock: vi.fn(() => "/app"),
|
||||
getSystemLocaleMock: vi.fn(() => "en-GB"),
|
||||
getVersionMock: vi.fn(() => "1.2.3"),
|
||||
isDefaultProtocolClientMock: vi.fn(() => false),
|
||||
onMock: vi.fn(),
|
||||
@@ -62,7 +60,6 @@ vi.mock("electron", () => ({
|
||||
setIcon: setDockIconMock,
|
||||
},
|
||||
getAppPath: getAppPathMock,
|
||||
getSystemLocale: getSystemLocaleMock,
|
||||
getVersion: getVersionMock,
|
||||
isDefaultProtocolClient: isDefaultProtocolClientMock,
|
||||
isPackaged: true,
|
||||
@@ -114,23 +111,6 @@ describe("ElectronApp", () => {
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("reads the OS locale through the service", () =>
|
||||
Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
|
||||
assert.strictEqual(yield* electronApp.systemLocale, "en-GB");
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("normalizes POSIX-style locale identifiers that Intl rejects", () =>
|
||||
Effect.gen(function* () {
|
||||
getSystemLocaleMock.mockImplementationOnce(() => "en_GB");
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
|
||||
assert.strictEqual(yield* electronApp.systemLocale, "en-GB");
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports which app metadata property failed", () =>
|
||||
Effect.gen(function* () {
|
||||
const cause = new Error("version unavailable");
|
||||
|
||||
@@ -43,13 +43,6 @@ export class ElectronApp extends Context.Service<
|
||||
{
|
||||
readonly metadata: Effect.Effect<ElectronAppMetadata, ElectronAppMetadataReadError>;
|
||||
readonly name: Effect.Effect<string>;
|
||||
/**
|
||||
* The OS locale, read from the operating system rather than from Chromium's
|
||||
* resolved application locale — the packaged app ships only the `en-US`
|
||||
* locale pak, so `app.getLocale()` and the renderer's `Intl` default are
|
||||
* pinned to `en-US` however the machine is configured.
|
||||
*/
|
||||
readonly systemLocale: Effect.Effect<string>;
|
||||
readonly whenReady: Effect.Effect<void, ElectronAppWhenReadyError>;
|
||||
readonly quit: Effect.Effect<void>;
|
||||
readonly exit: (code: number) => Effect.Effect<void>;
|
||||
@@ -126,10 +119,6 @@ export const make = ElectronApp.of({
|
||||
};
|
||||
}),
|
||||
name: Effect.sync(() => Electron.app.name),
|
||||
// macOS derives this from NSLocale, which uses POSIX-style identifiers
|
||||
// (`en_GB`). `Intl` rejects those outright rather than normalizing them, so
|
||||
// the tag is normalized here rather than in the renderer that consumes it.
|
||||
systemLocale: Effect.sync(() => Electron.app.getSystemLocale().replace(/_/g, "-")),
|
||||
whenReady: Effect.gen(function* () {
|
||||
const isPackaged = Electron.app.isPackaged;
|
||||
yield* Effect.tryPromise({
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { REMOTE_CAPABLE_EDITOR_IDS, remoteSchemeForEditor } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -6,16 +5,7 @@ import * as Option from "effect/Option";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
// Remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`)
|
||||
// must reach the OS handler; every other non-web scheme stays blocked.
|
||||
const SAFE_EXTERNAL_PROTOCOLS = new Set([
|
||||
"http:",
|
||||
"https:",
|
||||
...REMOTE_CAPABLE_EDITOR_IDS.flatMap((id) => {
|
||||
const scheme = remoteSchemeForEditor(id);
|
||||
return scheme === undefined ? [] : [`${scheme}:`];
|
||||
}),
|
||||
]);
|
||||
const SAFE_EXTERNAL_PROTOCOLS = new Set(["http:", "https:"]);
|
||||
|
||||
export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
|
||||
if (typeof rawUrl !== "string") {
|
||||
|
||||
@@ -34,10 +34,8 @@ import {
|
||||
getAppBranding,
|
||||
getLocalEnvironmentBootstraps,
|
||||
getLocalEnvironmentBearerToken,
|
||||
getSystemLocale,
|
||||
getWindowFullscreenState,
|
||||
openExternal,
|
||||
probeRemoteEditors,
|
||||
pickFolder,
|
||||
pickThemeFiles,
|
||||
setTheme,
|
||||
@@ -51,7 +49,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* PreviewIpc.installPreviewEventForwarding();
|
||||
|
||||
yield* ipc.handleSync(getAppBranding);
|
||||
yield* ipc.handleSync(getSystemLocale);
|
||||
yield* ipc.handleSync(getWindowFullscreenState);
|
||||
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
|
||||
yield* ipc.handle(getLocalEnvironmentBearerToken);
|
||||
@@ -86,7 +83,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* ipc.handle(setTheme);
|
||||
yield* ipc.handle(showContextMenu);
|
||||
yield* ipc.handle(openExternal);
|
||||
yield* ipc.handle(probeRemoteEditors);
|
||||
yield* ipc.handle(getUpdateState);
|
||||
yield* ipc.handle(setUpdateChannel);
|
||||
yield* ipc.handle(downloadUpdate);
|
||||
|
||||
@@ -3,9 +3,7 @@ export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
|
||||
export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
export const PROBE_REMOTE_EDITORS_CHANNEL = "desktop:probe-remote-editors";
|
||||
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const QUIT_SHORTCUT_CHANNEL = "desktop:quit-shortcut";
|
||||
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
|
||||
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
|
||||
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
@@ -15,7 +13,6 @@ export const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
export const GET_SYSTEM_LOCALE_CHANNEL = "desktop:get-system-locale";
|
||||
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps";
|
||||
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
|
||||
"desktop:get-local-environment-bearer-token";
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
DesktopPreviewRegisterWebviewInputSchema,
|
||||
DesktopPreviewScreenshotArtifactSchema,
|
||||
DesktopPreviewSetColorSchemeInputSchema,
|
||||
DesktopPreviewCreateTabInputSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationSubmissionResultSchema,
|
||||
@@ -49,15 +48,11 @@ export const installPreviewEventForwarding = Effect.fn(
|
||||
|
||||
export const createTab = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
|
||||
payload: DesktopPreviewCreateTabInputSchema,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.Void,
|
||||
handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({
|
||||
tabId,
|
||||
zoomFactor,
|
||||
colorScheme,
|
||||
}) {
|
||||
handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
yield* manager.createTab(tabId, { zoomFactor, colorScheme });
|
||||
yield* manager.createTab(tabId);
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -3,16 +3,12 @@ import {
|
||||
DesktopAppBrandingSchema,
|
||||
DesktopEnvironmentBootstrapSchema,
|
||||
DesktopThemeSchema,
|
||||
EDITORS,
|
||||
EditorId,
|
||||
PickedThemeFileSchema,
|
||||
PickFolderOptionsSchema,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
REMOTE_CAPABLE_EDITOR_IDS,
|
||||
type DesktopEnvironmentBootstrap,
|
||||
type PickedThemeFile,
|
||||
} from "@t3tools/contracts";
|
||||
import { isCommandAvailable } from "@t3tools/shared/shell";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
@@ -26,7 +22,6 @@ import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
import * as ElectronApp from "../../electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
|
||||
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../../electron/ElectronShell.ts";
|
||||
@@ -65,15 +60,6 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL,
|
||||
result: Schema.String,
|
||||
handler: Effect.fn("desktop.ipc.window.getSystemLocale")(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
return yield* electronApp.systemLocale;
|
||||
}),
|
||||
});
|
||||
|
||||
export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
|
||||
channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
|
||||
result: Schema.Boolean,
|
||||
@@ -275,30 +261,6 @@ export const openExternal = DesktopIpc.makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
|
||||
payload: Schema.Undefined,
|
||||
result: Schema.Array(EditorId),
|
||||
// Probes THIS machine (where the renderer runs) for remote-capable editor
|
||||
// CLIs, unlike the server's probe which walks the environment host's PATH.
|
||||
// A Finder-launched app can miss PATH entries; an empty result makes the
|
||||
// renderer fall back to VS Code only, so that fails soft.
|
||||
handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
|
||||
const available: Array<EditorId> = [];
|
||||
for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
|
||||
const commands = EDITORS.find((editor) => editor.id === editorId)?.commands;
|
||||
if (!commands) continue;
|
||||
for (const command of commands) {
|
||||
if (yield* isCommandAvailable(command, { env: process.env })) {
|
||||
available.push(editorId);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return available;
|
||||
}),
|
||||
});
|
||||
|
||||
/** Theme files are a few KB; anything larger returns empty text and lets the
|
||||
* renderer reject it by size without the contents ever crossing the bridge. */
|
||||
const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
|
||||
|
||||
@@ -10,11 +10,8 @@ import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
|
||||
import * as DesktopShutdown from "../../app/DesktopShutdown.ts";
|
||||
import * as DesktopState from "../../app/DesktopState.ts";
|
||||
import * as ElectronApp from "../../electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
|
||||
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
|
||||
import * as DesktopWindow from "../../window/DesktopWindow.ts";
|
||||
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
@@ -73,15 +70,6 @@ const unusedLifecycleRuntimeLayer = Layer.mergeAll(
|
||||
ElectronTheme.ElectronTheme,
|
||||
ElectronTheme.ElectronTheme.of({} as ElectronTheme.ElectronTheme["Service"]),
|
||||
),
|
||||
Layer.succeed(
|
||||
ElectronDialog.ElectronDialog,
|
||||
ElectronDialog.ElectronDialog.of({} as ElectronDialog.ElectronDialog["Service"]),
|
||||
),
|
||||
Layer.succeed(
|
||||
ElectronWindow.ElectronWindow,
|
||||
ElectronWindow.ElectronWindow.of({} as ElectronWindow.ElectronWindow["Service"]),
|
||||
),
|
||||
DesktopClientSettings.layerTest(),
|
||||
);
|
||||
|
||||
describe("WSL IPC", () => {
|
||||
|
||||
@@ -62,7 +62,6 @@ import * as PreviewManager from "./preview/Manager.ts";
|
||||
import * as DesktopWindow from "./window/DesktopWindow.ts";
|
||||
import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
|
||||
import * as DesktopWslServerTree from "./wsl/DesktopWslServerTree.ts";
|
||||
|
||||
const desktopEnvironmentLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -166,7 +165,6 @@ const desktopBackendLayer = DesktopBackendPool.layer.pipe(
|
||||
Layer.provideMerge(DesktopAppIdentity.layer),
|
||||
Layer.provideMerge(DesktopBackendConfiguration.layer),
|
||||
Layer.provideMerge(DesktopWslEnvironment.layer),
|
||||
Layer.provideMerge(DesktopWslServerTree.layer),
|
||||
Layer.provideMerge(DesktopTelemetryPublisher.layer),
|
||||
Layer.provideMerge(desktopWindowLayer),
|
||||
);
|
||||
|
||||
@@ -35,10 +35,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getAppBranding"]>;
|
||||
},
|
||||
getSystemLocale: () => {
|
||||
const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL);
|
||||
return typeof result === "string" ? result : null;
|
||||
},
|
||||
getLocalEnvironmentBootstraps: () => {
|
||||
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);
|
||||
if (!Array.isArray(result)) {
|
||||
@@ -109,7 +105,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
...(position === undefined ? {} : { position }),
|
||||
}),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
|
||||
probeRemoteEditors: () => ipcRenderer.invoke(IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL, undefined),
|
||||
onMenuAction: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
|
||||
if (typeof action !== "string") return;
|
||||
@@ -121,17 +116,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
onQuitShortcut: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
|
||||
if (state !== "down" && state !== "up") return;
|
||||
listener(state);
|
||||
};
|
||||
|
||||
ipcRenderer.on(IpcChannels.QUIT_SHORTCUT_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(IpcChannels.QUIT_SHORTCUT_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getWindowFullscreenState: () =>
|
||||
ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true,
|
||||
onWindowFullscreenStateChange: (listener) => {
|
||||
@@ -163,12 +147,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
};
|
||||
},
|
||||
preview: {
|
||||
createTab: (tabId, defaults) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, {
|
||||
tabId,
|
||||
zoomFactor: defaults?.zoomFactor,
|
||||
colorScheme: defaults?.colorScheme,
|
||||
}),
|
||||
createTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, { tabId }),
|
||||
closeTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL, { tabId }),
|
||||
registerWebview: (tabId, webContentsId) =>
|
||||
ipcRenderer.invoke(IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL, { tabId, webContentsId }),
|
||||
|
||||
@@ -1,999 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
MAX_FAVICON_CANDIDATES,
|
||||
MAX_FAVICON_RESPONSE_BYTES,
|
||||
captureFavicon,
|
||||
selectFaviconCandidates,
|
||||
} from "./FaviconCapture.ts";
|
||||
|
||||
const PNG = "data:image/png;base64,cG5n";
|
||||
const SOURCE_PNG = Buffer.alloc(24);
|
||||
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(SOURCE_PNG);
|
||||
SOURCE_PNG.writeUInt32BE(1, 16);
|
||||
SOURCE_PNG.writeUInt32BE(1, 20);
|
||||
const SOURCE_PNG_URL = `data:image/png;base64,${SOURCE_PNG.toString("base64")}`;
|
||||
|
||||
function sourceGif(
|
||||
width: number,
|
||||
height: number,
|
||||
frameWidth = width,
|
||||
frameHeight = height,
|
||||
additionalFrames: ReadonlyArray<{
|
||||
readonly left?: number;
|
||||
readonly top?: number;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}> = [],
|
||||
): Buffer {
|
||||
const frames = [{ width: frameWidth, height: frameHeight }, ...additionalFrames];
|
||||
const buffer = Buffer.alloc(13 + frames.length * 12 + 1);
|
||||
buffer.write("GIF89a", 0, "ascii");
|
||||
buffer.writeUInt16LE(width, 6);
|
||||
buffer.writeUInt16LE(height, 8);
|
||||
let offset = 13;
|
||||
for (const frame of frames) {
|
||||
buffer[offset] = 0x2c;
|
||||
buffer.writeUInt16LE(frame.left ?? 0, offset + 1);
|
||||
buffer.writeUInt16LE(frame.top ?? 0, offset + 3);
|
||||
buffer.writeUInt16LE(frame.width, offset + 5);
|
||||
buffer.writeUInt16LE(frame.height, offset + 7);
|
||||
offset += 10;
|
||||
buffer[offset] = 2;
|
||||
buffer[offset + 1] = 0;
|
||||
offset += 2;
|
||||
}
|
||||
buffer[offset] = 0x3b;
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function sourceJpeg(
|
||||
width: number,
|
||||
height: number,
|
||||
orientations: number | ReadonlyArray<number> = [],
|
||||
): Buffer {
|
||||
const frame = Buffer.from([
|
||||
0xff,
|
||||
0xd8,
|
||||
0xff,
|
||||
0xc0,
|
||||
0x00,
|
||||
0x07,
|
||||
0x08,
|
||||
height >>> 8,
|
||||
height & 0xff,
|
||||
width >>> 8,
|
||||
width & 0xff,
|
||||
]);
|
||||
const app1Segments = (typeof orientations === "number" ? [orientations] : orientations).map(
|
||||
(orientation) => sourceJpegExifSegment([orientation]),
|
||||
);
|
||||
return Buffer.concat([frame.subarray(0, 2), ...app1Segments, frame.subarray(2)]);
|
||||
}
|
||||
|
||||
function sourceJpegApp1Segment(payload: Buffer): Buffer {
|
||||
const app1 = Buffer.alloc(4 + payload.byteLength);
|
||||
app1[0] = 0xff;
|
||||
app1[1] = 0xe1;
|
||||
app1.writeUInt16BE(payload.byteLength + 2, 2);
|
||||
payload.copy(app1, 4);
|
||||
return app1;
|
||||
}
|
||||
|
||||
function sourceJpegExifSegment(
|
||||
orientations: ReadonlyArray<number>,
|
||||
options?: {
|
||||
readonly byteOrder?: "II" | "MM";
|
||||
readonly magic?: number;
|
||||
readonly padding?: number;
|
||||
},
|
||||
): Buffer {
|
||||
const exif = Buffer.alloc(20 + orientations.length * 12);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif[5] = options?.padding ?? 0;
|
||||
const littleEndian = options?.byteOrder !== "MM";
|
||||
exif.write(littleEndian ? "II" : "MM", 6, "ascii");
|
||||
const writeUInt16 = (value: number, offset: number) =>
|
||||
littleEndian ? exif.writeUInt16LE(value, offset) : exif.writeUInt16BE(value, offset);
|
||||
const writeUInt32 = (value: number, offset: number) =>
|
||||
littleEndian ? exif.writeUInt32LE(value, offset) : exif.writeUInt32BE(value, offset);
|
||||
writeUInt16(options?.magic ?? 42, 8);
|
||||
writeUInt32(8, 10);
|
||||
writeUInt16(orientations.length, 14);
|
||||
orientations.forEach((orientation, index) => {
|
||||
const entryOffset = 16 + index * 12;
|
||||
writeUInt16(0x0112, entryOffset);
|
||||
writeUInt16(3, entryOffset + 2);
|
||||
writeUInt32(1, entryOffset + 4);
|
||||
writeUInt16(orientation, entryOffset + 8);
|
||||
});
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceJpegWithApp1Segments(
|
||||
width: number,
|
||||
height: number,
|
||||
segments: ReadonlyArray<Buffer>,
|
||||
): Buffer {
|
||||
const frame = sourceJpeg(width, height);
|
||||
return Buffer.concat([frame.subarray(0, 2), ...segments, frame.subarray(2)]);
|
||||
}
|
||||
|
||||
function sourceJpegWithOrientationEntries(
|
||||
width: number,
|
||||
height: number,
|
||||
orientations: ReadonlyArray<number>,
|
||||
): Buffer {
|
||||
return sourceJpegWithApp1Segments(width, height, [sourceJpegExifSegment(orientations)]);
|
||||
}
|
||||
|
||||
function sourceJpegWithEndianAlias(alias: number, byteOrder: "II" | "MM"): Buffer {
|
||||
const exif = sourceJpegExifSegment([6], { byteOrder });
|
||||
exif[10] = alias;
|
||||
exif[11] = alias;
|
||||
return sourceJpegWithApp1Segments(64, 32, [exif]);
|
||||
}
|
||||
|
||||
function sourceJpegExifWithSubIfd(options: {
|
||||
readonly rootOrientation?: number;
|
||||
readonly subIfdFirst?: boolean;
|
||||
readonly subIfdOrientation: number;
|
||||
}): Buffer {
|
||||
const rootEntries = options.rootOrientation === undefined ? 1 : 2;
|
||||
const rootIfdOffset = 14;
|
||||
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
|
||||
const exif = Buffer.alloc(subIfdOffset + 2 + 12 + 4);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif.write("II", 6, "ascii");
|
||||
exif.writeUInt16LE(42, 8);
|
||||
exif.writeUInt32LE(8, 10);
|
||||
exif.writeUInt16LE(rootEntries, rootIfdOffset);
|
||||
|
||||
const writeOrientation = (offset: number, orientation: number) => {
|
||||
exif.writeUInt16LE(0x0112, offset);
|
||||
exif.writeUInt16LE(3, offset + 2);
|
||||
exif.writeUInt32LE(1, offset + 4);
|
||||
exif.writeUInt16LE(orientation, offset + 8);
|
||||
};
|
||||
const writeSubIfdPointer = (offset: number) => {
|
||||
exif.writeUInt16LE(0x8769, offset);
|
||||
exif.writeUInt16LE(4, offset + 2);
|
||||
exif.writeUInt32LE(1, offset + 4);
|
||||
exif.writeUInt32LE(subIfdOffset - 6, offset + 8);
|
||||
};
|
||||
|
||||
const firstRootEntryOffset = rootIfdOffset + 2;
|
||||
if (options.rootOrientation === undefined) {
|
||||
writeSubIfdPointer(firstRootEntryOffset);
|
||||
} else if (options.subIfdFirst) {
|
||||
writeSubIfdPointer(firstRootEntryOffset);
|
||||
writeOrientation(firstRootEntryOffset + 12, options.rootOrientation);
|
||||
} else {
|
||||
writeOrientation(firstRootEntryOffset, options.rootOrientation);
|
||||
writeSubIfdPointer(firstRootEntryOffset + 12);
|
||||
}
|
||||
|
||||
exif.writeUInt16LE(1, subIfdOffset);
|
||||
writeOrientation(subIfdOffset + 2, options.subIfdOrientation);
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceJpegExifWithSubIfdPointers(options: {
|
||||
readonly pointerCount: number;
|
||||
readonly subIfdEntries: number;
|
||||
}): Buffer {
|
||||
const { pointerCount, subIfdEntries } = options;
|
||||
const rootIfdOffset = 14;
|
||||
const rootEntries = pointerCount + 1;
|
||||
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
|
||||
const exif = Buffer.alloc(subIfdOffset + 2 + subIfdEntries * 12 + 4);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif.write("II", 6, "ascii");
|
||||
exif.writeUInt16LE(42, 8);
|
||||
exif.writeUInt32LE(8, 10);
|
||||
exif.writeUInt16LE(rootEntries, rootIfdOffset);
|
||||
for (let index = 0; index < pointerCount; index += 1) {
|
||||
const entryOffset = rootIfdOffset + 2 + index * 12;
|
||||
exif.writeUInt16LE(0x8769, entryOffset);
|
||||
exif.writeUInt16LE(4, entryOffset + 2);
|
||||
exif.writeUInt32LE(1, entryOffset + 4);
|
||||
exif.writeUInt32LE(subIfdOffset - 6, entryOffset + 8);
|
||||
}
|
||||
const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
|
||||
exif.writeUInt16LE(0x0112, orientationOffset);
|
||||
exif.writeUInt16LE(3, orientationOffset + 2);
|
||||
exif.writeUInt32LE(1, orientationOffset + 4);
|
||||
exif.writeUInt16LE(6, orientationOffset + 8);
|
||||
|
||||
exif.writeUInt16LE(subIfdEntries, subIfdOffset);
|
||||
for (let index = 0; index < subIfdEntries; index += 1) {
|
||||
const entryOffset = subIfdOffset + 2 + index * 12;
|
||||
exif.writeUInt16LE(1, entryOffset);
|
||||
exif.writeUInt16LE(3, entryOffset + 2);
|
||||
exif.writeUInt32LE(1, entryOffset + 4);
|
||||
}
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceJpegExifWithOverlappingSubIfds(pointerCount: number, subIfdEntries: number): Buffer {
|
||||
const rootIfdOffset = 14;
|
||||
const rootEntries = pointerCount + 1;
|
||||
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
|
||||
const exif = Buffer.alloc(subIfdOffset + pointerCount * 2 + 2 + subIfdEntries * 12);
|
||||
exif.write("Exif\0\0", 0, "binary");
|
||||
exif.write("II", 6, "ascii");
|
||||
exif.writeUInt32LE(8, 10);
|
||||
exif.writeUInt16LE(rootEntries, rootIfdOffset);
|
||||
for (let index = 0; index < pointerCount; index += 1) {
|
||||
const entryOffset = rootIfdOffset + 2 + index * 12;
|
||||
exif.writeUInt16LE(0x8769, entryOffset);
|
||||
exif.writeUInt16LE(4, entryOffset + 2);
|
||||
exif.writeUInt32LE(1, entryOffset + 4);
|
||||
exif.writeUInt32LE(subIfdOffset + index * 2 - 6, entryOffset + 8);
|
||||
exif.writeUInt16LE(subIfdEntries, subIfdOffset + index * 2);
|
||||
}
|
||||
const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
|
||||
exif.writeUInt16LE(0x0112, orientationOffset);
|
||||
exif.writeUInt16LE(3, orientationOffset + 2);
|
||||
exif.writeUInt32LE(1, orientationOffset + 4);
|
||||
exif.writeUInt16LE(6, orientationOffset + 8);
|
||||
return sourceJpegApp1Segment(exif);
|
||||
}
|
||||
|
||||
function sourceWebp(width: number, height: number): Buffer {
|
||||
const buffer = Buffer.alloc(30);
|
||||
buffer.write("RIFF", 0, "ascii");
|
||||
buffer.write("WEBP", 8, "ascii");
|
||||
buffer.write("VP8X", 12, "ascii");
|
||||
buffer.writeUIntLE(width - 1, 24, 3);
|
||||
buffer.writeUIntLE(height - 1, 27, 3);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function sourceIco(embedded: Buffer): Buffer {
|
||||
const buffer = Buffer.alloc(22 + embedded.byteLength);
|
||||
buffer.writeUInt16LE(1, 2);
|
||||
buffer.writeUInt16LE(1, 4);
|
||||
buffer.writeUInt32LE(embedded.byteLength, 14);
|
||||
buffer.writeUInt32LE(22, 18);
|
||||
embedded.copy(buffer, 22);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function makeUnsafePng(): Buffer {
|
||||
const buffer = Buffer.from(SOURCE_PNG);
|
||||
buffer.writeUInt32BE(4096, 16);
|
||||
buffer.writeUInt32BE(4096, 20);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function sourcePng(width: number, height: number): Buffer {
|
||||
const buffer = Buffer.from(SOURCE_PNG);
|
||||
buffer.writeUInt32BE(width, 16);
|
||||
buffer.writeUInt32BE(height, 20);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function makeUnsafeDib(): Buffer {
|
||||
const buffer = Buffer.alloc(40);
|
||||
buffer.writeUInt32LE(40, 0);
|
||||
buffer.writeInt32LE(4096, 4);
|
||||
buffer.writeInt32LE(4096, 8);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function makeWebContents(options?: {
|
||||
readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
|
||||
readonly rasterize?: (code: string) => Promise<unknown>;
|
||||
}) {
|
||||
const fetch = vi.fn(
|
||||
options?.fetch ??
|
||||
(async () =>
|
||||
new Response(new Uint8Array(SOURCE_PNG), {
|
||||
headers: { "content-type": "image/png" },
|
||||
})),
|
||||
);
|
||||
const executeJavaScriptInIsolatedWorld = vi.fn(
|
||||
async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
|
||||
options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : PNG,
|
||||
);
|
||||
return {
|
||||
webContents: {
|
||||
session: { fetch },
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
} as never,
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
fetch,
|
||||
};
|
||||
}
|
||||
|
||||
const JPEG_LANDSCAPE_LAYOUT = {
|
||||
draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
|
||||
resizeHeight: 16,
|
||||
resizeWidth: 32,
|
||||
} as const;
|
||||
const JPEG_PORTRAIT_LAYOUT = {
|
||||
draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
|
||||
resizeHeight: 32,
|
||||
resizeWidth: 16,
|
||||
} as const;
|
||||
|
||||
async function expectJpegLayout(
|
||||
source: Buffer,
|
||||
layout: typeof JPEG_LANDSCAPE_LAYOUT | typeof JPEG_PORTRAIT_LAYOUT,
|
||||
): Promise<void> {
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: async (code) => {
|
||||
expect(code).toContain(`resizeWidth: ${layout.resizeWidth}`);
|
||||
expect(code).toContain(`resizeHeight: ${layout.resizeHeight}`);
|
||||
expect(code).toContain(layout.draw);
|
||||
return PNG;
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
}
|
||||
|
||||
describe("selectFaviconCandidates", () => {
|
||||
it("filters and deduplicates before applying the candidate cap", () => {
|
||||
const valid = Array.from(
|
||||
{ length: MAX_FAVICON_CANDIDATES + 2 },
|
||||
(_, index) => `https://example.com/favicon-${index}.png`,
|
||||
);
|
||||
expect(
|
||||
selectFaviconCandidates([
|
||||
...Array.from({ length: 64 }, () => "javascript:alert(1)"),
|
||||
valid[0]!,
|
||||
valid[0]!,
|
||||
...valid.slice(1),
|
||||
]),
|
||||
).toEqual(valid.slice(0, MAX_FAVICON_CANDIDATES));
|
||||
});
|
||||
|
||||
it("bounds raw candidate scanning independently of the usable-candidate cap", () => {
|
||||
const oversizedInvalid = `javascript:${"x".repeat(2_048)}`;
|
||||
expect(
|
||||
selectFaviconCandidates([
|
||||
...Array.from({ length: 128 }, () => oversizedInvalid),
|
||||
"https://example.com/too-late.png",
|
||||
]),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("captureFavicon", () => {
|
||||
it.each([
|
||||
{
|
||||
label: "same-origin",
|
||||
pageUrl: "https://example.com/page",
|
||||
faviconUrl: "https://example.com/favicon.png",
|
||||
credentials: "include",
|
||||
},
|
||||
{
|
||||
label: "cross-origin",
|
||||
pageUrl: "https://example.com/page",
|
||||
faviconUrl: "https://cdn.example.net/favicon.png",
|
||||
credentials: "omit",
|
||||
},
|
||||
])("uses the explicit credential policy for $label requests", async (testCase) => {
|
||||
const { webContents, fetch } = makeWebContents();
|
||||
const result = await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: testCase.pageUrl,
|
||||
candidates: [testCase.faviconUrl],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
expect(result).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
testCase.faviconUrl,
|
||||
expect.objectContaining({ credentials: testCase.credentials, redirect: "error" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("decodes base64 and percent-encoded inline images without fetching", async () => {
|
||||
const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
const percentEncodedPng = [...SOURCE_PNG]
|
||||
.map((byte) => `%${byte.toString(16).padStart(2, "0")}`)
|
||||
.join("");
|
||||
|
||||
for (const candidate of [SOURCE_PNG_URL, `data:image/png,${percentEncodedPng}`]) {
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [candidate],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
}
|
||||
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("tries the next candidate after an ordinary rejection", async () => {
|
||||
const { webContents, fetch } = makeWebContents({
|
||||
fetch: async (url) =>
|
||||
url.endsWith("first.png")
|
||||
? new Response(null, { status: 404 })
|
||||
: new Response(new Uint8Array(SOURCE_PNG), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("cancels a rejected response body before trying the next candidate", async () => {
|
||||
const cancel = vi.fn();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(1));
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
const { webContents, fetch } = makeWebContents({
|
||||
fetch: async (url) =>
|
||||
url.endsWith("first.png")
|
||||
? new Response(body, { status: 404 })
|
||||
: new Response(new Uint8Array(SOURCE_PNG), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("stops a pending fetch when its capture is aborted", async () => {
|
||||
const controller = new AbortController();
|
||||
const { webContents } = makeWebContents({
|
||||
fetch: (_url, init) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
|
||||
once: true,
|
||||
});
|
||||
}),
|
||||
});
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.abort();
|
||||
expect(await capture).toEqual({ kind: "none" });
|
||||
});
|
||||
|
||||
it("ends candidate fallback when the overall capture deadline expires", async () => {
|
||||
const timeoutController = new AbortController();
|
||||
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
|
||||
const { webContents, fetch } = makeWebContents({
|
||||
fetch: (url, init) => {
|
||||
if (url.endsWith("first.png")) return Promise.resolve(new Response(null, { status: 404 }));
|
||||
return new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
|
||||
once: true,
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
try {
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [
|
||||
"https://example.com/first.png",
|
||||
"https://example.com/second.png",
|
||||
"https://example.com/third.png",
|
||||
],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
|
||||
timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(timeout).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not publish a rasterization that completes after the capture deadline", async () => {
|
||||
const captureTimeoutController = new AbortController();
|
||||
const rasterTimeoutController = new AbortController();
|
||||
const timeout = vi
|
||||
.spyOn(AbortSignal, "timeout")
|
||||
.mockImplementation((milliseconds) =>
|
||||
milliseconds === 5_000 ? captureTimeoutController.signal : rasterTimeoutController.signal,
|
||||
);
|
||||
let resolveRasterization!: (value: unknown) => void;
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
rasterize: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveRasterization = resolve;
|
||||
}),
|
||||
});
|
||||
try {
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
await vi.waitFor(() => expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce());
|
||||
captureTimeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
resolveRasterization(PNG);
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("cancels a stalled response body when the capture deadline expires", async () => {
|
||||
const timeoutController = new AbortController();
|
||||
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
|
||||
const cancel = vi.fn();
|
||||
const { webContents } = makeWebContents({
|
||||
fetch: async () =>
|
||||
new Response(
|
||||
new ReadableStream<Uint8Array>({
|
||||
cancel,
|
||||
}),
|
||||
{ headers: { "content-type": "image/png" } },
|
||||
),
|
||||
});
|
||||
try {
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
timeout.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects and cancels an oversized streamed response", async () => {
|
||||
const cancel = vi.fn();
|
||||
const body = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(new Uint8Array(MAX_FAVICON_RESPONSE_BYTES));
|
||||
controller.enqueue(new Uint8Array(1));
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
fetch: async () => new Response(body, { headers: { "content-type": "image/png" } }),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retains bounded compatibility with common favicon formats", async () => {
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
for (const [mime, buffer] of [
|
||||
["image/gif", sourceGif(32, 32)],
|
||||
["image/jpeg", sourceJpeg(32, 32)],
|
||||
["image/webp", sourceWebp(32, 32)],
|
||||
["image/x-icon", sourceIco(SOURCE_PNG)],
|
||||
] as const) {
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:${mime};base64,${buffer.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
}
|
||||
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
label: "landscape",
|
||||
source: sourcePng(64, 32),
|
||||
resizeWidth: 32,
|
||||
resizeHeight: 16,
|
||||
draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
|
||||
},
|
||||
{
|
||||
label: "portrait",
|
||||
source: sourcePng(32, 64),
|
||||
resizeWidth: 16,
|
||||
resizeHeight: 32,
|
||||
draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
|
||||
},
|
||||
])("preserves $label aspect ratio within the 32x32 output", async (testCase) => {
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: async (code) => {
|
||||
expect(code).toContain(`resizeWidth: ${testCase.resizeWidth}`);
|
||||
expect(code).toContain(`resizeHeight: ${testCase.resizeHeight}`);
|
||||
expect(code).toContain('resizeQuality: "high"');
|
||||
expect(code).toContain(testCase.draw);
|
||||
return PNG;
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/png;base64,${testCase.source.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
});
|
||||
|
||||
it.each([
|
||||
...[1, 2, 3, 4].map((orientation) => ({
|
||||
label: `keeps stored dimensions for orientation ${orientation}`,
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpeg(64, 32, orientation),
|
||||
})),
|
||||
...[5, 6, 7, 8].map((orientation) => ({
|
||||
label: `uses display dimensions for orientation ${orientation}`,
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpeg(64, 32, orientation),
|
||||
})),
|
||||
{
|
||||
label: "uses the first separate EXIF segment when it is transposed",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpeg(64, 32, [6, 1]),
|
||||
},
|
||||
{
|
||||
label: "uses the first separate EXIF segment when it is untransposed",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpeg(64, 32, [1, 6]),
|
||||
},
|
||||
{
|
||||
label: "does not consult a later EXIF segment after an invalid orientation",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpeg(64, 32, [9, 6]),
|
||||
},
|
||||
{
|
||||
label: "uses a later valid orientation in the same IFD",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithOrientationEntries(64, 32, [9, 6]),
|
||||
},
|
||||
{
|
||||
label: "skips a non-EXIF APP1 segment",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegApp1Segment(Buffer.from("not-exif")),
|
||||
sourceJpegExifSegment([6]),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "skips an empty EXIF APP1 segment",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegApp1Segment(Buffer.from("Exif\0\0", "binary")),
|
||||
sourceJpegExifSegment([6]),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "stops after a malformed qualifying EXIF APP1 segment",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegApp1Segment(Buffer.from("Exif\0\0broken", "binary")),
|
||||
sourceJpegExifSegment([6]),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "ignores the EXIF padding byte",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { padding: 0xff })]),
|
||||
},
|
||||
{
|
||||
label: "reads big-endian EXIF",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { byteOrder: "MM" })]),
|
||||
},
|
||||
{
|
||||
label: "matches Chromium for a nonstandard TIFF magic field",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { magic: 0 })]),
|
||||
},
|
||||
{
|
||||
label: "rejects a high-bit little-endian alias",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithEndianAlias(0xc9, "II"),
|
||||
},
|
||||
{
|
||||
label: "rejects a high-bit big-endian alias",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithEndianAlias(0xcd, "MM"),
|
||||
},
|
||||
{
|
||||
label: "reads an orientation from a SubIFD",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfd({ subIfdOrientation: 6 }),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "uses a SubIFD orientation before a later root orientation",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfd({
|
||||
rootOrientation: 1,
|
||||
subIfdFirst: true,
|
||||
subIfdOrientation: 6,
|
||||
}),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "uses a root orientation before a later SubIFD orientation",
|
||||
layout: JPEG_LANDSCAPE_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfd({ rootOrientation: 1, subIfdOrientation: 6 }),
|
||||
]),
|
||||
},
|
||||
{
|
||||
label: "memoizes repeated aliases to the same SubIFD",
|
||||
layout: JPEG_PORTRAIT_LAYOUT,
|
||||
source: sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithSubIfdPointers({ pointerCount: 32, subIfdEntries: 32 }),
|
||||
]),
|
||||
},
|
||||
])("matches Chromium JPEG layout: $label", async ({ source, layout }) => {
|
||||
await expectJpegLayout(source, layout);
|
||||
});
|
||||
|
||||
it("rejects JPEG metadata when distinct SubIFDs exhaust the linear work budget", async () => {
|
||||
const source = sourceJpegWithApp1Segments(64, 32, [
|
||||
sourceJpegExifWithOverlappingSubIfds(32, 32),
|
||||
]);
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects JPEGs with multiple frame headers before rasterization", async () => {
|
||||
const buffer = Buffer.concat([sourceJpeg(4096, 4096), sourceJpeg(1, 1).subarray(2)]);
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [`data:image/jpeg;base64,${buffer.toString("base64")}`],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an unsafe PNG size before rasterization", async () => {
|
||||
const buffer = makeUnsafePng();
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
fetch: async () =>
|
||||
new Response(new Uint8Array(buffer), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/favicon.png"],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["GIF", "image/gif", sourceGif(4096, 4096)],
|
||||
["GIF frame", "image/gif", sourceGif(1, 1, 4096, 4096)],
|
||||
["GIF later frame", "image/gif", sourceGif(1, 1, 1, 1, [{ width: 4096, height: 4096 }])],
|
||||
[
|
||||
"GIF cumulative frames",
|
||||
"image/gif",
|
||||
sourceGif(
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
64,
|
||||
Array.from({ length: 256 }, () => ({ width: 64, height: 64 })),
|
||||
),
|
||||
],
|
||||
["JPEG", "image/jpeg", sourceJpeg(4096, 4096)],
|
||||
["WebP", "image/webp", sourceWebp(4096, 4096)],
|
||||
["ICO with PNG", "image/x-icon", sourceIco(makeUnsafePng())],
|
||||
["ICO with DIB", "image/x-icon", sourceIco(makeUnsafeDib())],
|
||||
["SVG", "image/svg+xml", Buffer.from('<svg width="1" height="1"/>')],
|
||||
[
|
||||
"SVG with embedded bitmap",
|
||||
"image/svg+xml",
|
||||
Buffer.from(
|
||||
`<svg width="1" height="1"><image href="data:image/png;base64,${makeUnsafePng().toString("base64")}"/></svg>`,
|
||||
),
|
||||
],
|
||||
[
|
||||
"ICO invalid payload span",
|
||||
"image/x-icon",
|
||||
(() => {
|
||||
const buffer = Buffer.alloc(22);
|
||||
buffer.writeUInt16LE(1, 2);
|
||||
buffer.writeUInt16LE(1, 4);
|
||||
buffer.writeUInt32LE(100, 14);
|
||||
buffer.writeUInt32LE(22, 18);
|
||||
return buffer;
|
||||
})(),
|
||||
],
|
||||
])("rejects unsafe or unsupported %s before rasterization", async (_label, mime, buffer) => {
|
||||
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
|
||||
const candidate = `data:${mime};base64,${buffer.toString("base64")}`;
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [candidate],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores output that is not a bounded PNG data URL", async () => {
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: async () => "data:image/svg+xml;base64,c3Zn",
|
||||
});
|
||||
|
||||
expect(
|
||||
await captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
}),
|
||||
).toEqual({ kind: "none" });
|
||||
});
|
||||
|
||||
it("waits for physical rasterization settlement after a logical timeout", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let resolveOld!: (value: unknown) => void;
|
||||
let executions = 0;
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: () => {
|
||||
executions += 1;
|
||||
return executions === 1
|
||||
? new Promise((resolve) => {
|
||||
resolveOld = resolve;
|
||||
})
|
||||
: Promise.resolve(PNG);
|
||||
},
|
||||
});
|
||||
const input = {
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
};
|
||||
const timedOut = captureFavicon(input);
|
||||
await vi.advanceTimersByTimeAsync(1_001);
|
||||
expect(await timedOut).toEqual({ kind: "timed-out" });
|
||||
|
||||
const newer = captureFavicon(input);
|
||||
await Promise.resolve();
|
||||
expect(executions).toBe(1);
|
||||
resolveOld(PNG);
|
||||
expect(await newer).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(executions).toBe(2);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("ends candidate fallback after a rasterization timeout", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
let resolveRasterization!: (value: unknown) => void;
|
||||
const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents({
|
||||
rasterize: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveRasterization = resolve;
|
||||
}),
|
||||
});
|
||||
const capture = captureFavicon({
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_001);
|
||||
|
||||
expect(await capture).toEqual({ kind: "timed-out" });
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce();
|
||||
resolveRasterization(PNG);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("coalesces queued rasterizations so only the latest pending capture launches", async () => {
|
||||
let resolveFirst!: (value: unknown) => void;
|
||||
let executions = 0;
|
||||
const { webContents } = makeWebContents({
|
||||
rasterize: () => {
|
||||
executions += 1;
|
||||
return executions === 1
|
||||
? new Promise((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
})
|
||||
: Promise.resolve(PNG);
|
||||
},
|
||||
});
|
||||
const input = {
|
||||
webContents,
|
||||
pageUrl: "https://example.com/page",
|
||||
candidates: [SOURCE_PNG_URL],
|
||||
signal: new AbortController().signal,
|
||||
};
|
||||
const first = captureFavicon(input);
|
||||
const superseded = captureFavicon(input);
|
||||
const newest = captureFavicon(input);
|
||||
|
||||
expect(executions).toBe(1);
|
||||
resolveFirst(PNG);
|
||||
expect(await first).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(await superseded).toEqual({ kind: "none" });
|
||||
expect(await newest).toEqual({ kind: "captured", dataUrl: PNG });
|
||||
expect(executions).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -1,679 +0,0 @@
|
||||
import { FAVICON_DATA_URL_MAX_LENGTH } from "@t3tools/contracts";
|
||||
|
||||
export const MAX_FAVICON_RESPONSE_BYTES = 100_000;
|
||||
export const MAX_FAVICON_CANDIDATES = 8;
|
||||
export const MAX_FAVICON_HTTP_URL_LENGTH = 2_048;
|
||||
|
||||
const MAX_FAVICON_CANDIDATE_INPUT_UNITS = 262_144;
|
||||
const MIN_FAVICON_CANDIDATE_INPUT_UNITS = 256;
|
||||
const MAX_FAVICON_SOURCE_PIXELS = 1_048_576;
|
||||
const MAX_FAVICON_INLINE_URL_LENGTH = Math.ceil((MAX_FAVICON_RESPONSE_BYTES * 4) / 3) + 128;
|
||||
const FAVICON_CAPTURE_TIMEOUT_MS = 5_000;
|
||||
const FAVICON_RASTER_WORLD_ID = 1001;
|
||||
const FAVICON_RASTER_TIMEOUT_MS = 1_000;
|
||||
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
|
||||
interface RasterizationGate {
|
||||
generation: number;
|
||||
launchAllowed?: Promise<void>;
|
||||
}
|
||||
|
||||
const rasterizationGates = new WeakMap<Electron.WebContents, RasterizationGate>();
|
||||
|
||||
async function waitForRasterLaunch(previous: Promise<void>, signal: AbortSignal): Promise<void> {
|
||||
if (signal.aborted) return;
|
||||
await new Promise<void>((resolve) => {
|
||||
const finish = () => {
|
||||
signal.removeEventListener("abort", finish);
|
||||
resolve();
|
||||
};
|
||||
signal.addEventListener("abort", finish, { once: true });
|
||||
void previous.then(finish);
|
||||
});
|
||||
}
|
||||
|
||||
export type FaviconCaptureResult =
|
||||
| { readonly kind: "captured"; readonly dataUrl: string }
|
||||
| { readonly kind: "none" }
|
||||
| { readonly kind: "timed-out" };
|
||||
|
||||
type RasterizationResult =
|
||||
| { readonly kind: "completed"; readonly value: unknown }
|
||||
| { readonly kind: "timed-out" };
|
||||
|
||||
export function safeHttpOrigin(url: string): string | null {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function selectFaviconCandidates(candidates: ReadonlyArray<string>): ReadonlyArray<string> {
|
||||
const selected: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
let inputUnits = 0;
|
||||
for (const candidate of candidates) {
|
||||
// Charge a minimum per entry so a large array of tiny malformed values is bounded too.
|
||||
inputUnits += Math.max(MIN_FAVICON_CANDIDATE_INPUT_UNITS, candidate.length);
|
||||
if (inputUnits > MAX_FAVICON_CANDIDATE_INPUT_UNITS) break;
|
||||
if (!isSupportedFaviconUrl(candidate) || seen.has(candidate)) continue;
|
||||
seen.add(candidate);
|
||||
selected.push(candidate);
|
||||
if (selected.length === MAX_FAVICON_CANDIDATES) break;
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
export async function captureFavicon(input: {
|
||||
readonly webContents: Electron.WebContents;
|
||||
readonly pageUrl: string;
|
||||
readonly candidates: ReadonlyArray<string>;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<FaviconCaptureResult> {
|
||||
const pageOrigin = safeHttpOrigin(input.pageUrl);
|
||||
if (!pageOrigin) return { kind: "none" };
|
||||
const captureTimeout = AbortSignal.timeout(FAVICON_CAPTURE_TIMEOUT_MS);
|
||||
const captureSignal = AbortSignal.any([input.signal, captureTimeout]);
|
||||
|
||||
for (const candidate of selectFaviconCandidates(input.candidates)) {
|
||||
if (captureSignal.aborted) {
|
||||
return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
|
||||
}
|
||||
const captured = await captureCandidate({
|
||||
webContents: input.webContents,
|
||||
pageOrigin,
|
||||
candidate,
|
||||
signal: captureSignal,
|
||||
});
|
||||
if (captureSignal.aborted) {
|
||||
return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
|
||||
}
|
||||
if (captured.kind === "captured" || captured.kind === "timed-out") return captured;
|
||||
}
|
||||
|
||||
return { kind: "none" };
|
||||
}
|
||||
|
||||
async function captureCandidate(input: {
|
||||
readonly webContents: Electron.WebContents;
|
||||
readonly pageOrigin: string;
|
||||
readonly candidate: string;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<FaviconCaptureResult> {
|
||||
try {
|
||||
const inline = parseInlineFavicon(input.candidate);
|
||||
if (inline) {
|
||||
return await normalizeFaviconBuffer(
|
||||
input.webContents,
|
||||
inline.mime,
|
||||
inline.buffer,
|
||||
input.signal,
|
||||
);
|
||||
}
|
||||
|
||||
const candidateOrigin = safeHttpOrigin(input.candidate);
|
||||
if (!candidateOrigin) return { kind: "none" };
|
||||
const response = await input.webContents.session.fetch(input.candidate, {
|
||||
credentials: candidateOrigin === input.pageOrigin ? "include" : "omit",
|
||||
redirect: "error",
|
||||
signal: input.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
return { kind: "none" };
|
||||
}
|
||||
const buffer = await readFaviconResponse(response, input.signal);
|
||||
if (!buffer || input.signal.aborted) return { kind: "none" };
|
||||
const mime = response.headers.get("content-type")?.split(";", 1)[0] ?? null;
|
||||
return await normalizeFaviconBuffer(input.webContents, mime, buffer, input.signal);
|
||||
} catch {
|
||||
return { kind: "none" };
|
||||
}
|
||||
}
|
||||
|
||||
async function readFaviconResponse(
|
||||
response: Response,
|
||||
signal: AbortSignal,
|
||||
): Promise<Buffer | null> {
|
||||
const contentLength = Number(response.headers.get("content-length"));
|
||||
if (Number.isFinite(contentLength) && contentLength > MAX_FAVICON_RESPONSE_BYTES) {
|
||||
await response.body?.cancel();
|
||||
return null;
|
||||
}
|
||||
if (!response.body) {
|
||||
const buffer = Buffer.from(await response.arrayBuffer());
|
||||
return buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES ? buffer : null;
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const cancelForAbort = () => {
|
||||
void reader.cancel(signal.reason).catch(() => undefined);
|
||||
};
|
||||
signal.addEventListener("abort", cancelForAbort, { once: true });
|
||||
if (signal.aborted) cancelForAbort();
|
||||
const chunks: Buffer[] = [];
|
||||
let byteLength = 0;
|
||||
try {
|
||||
while (true) {
|
||||
const next = await reader.read();
|
||||
if (next.done) return Buffer.concat(chunks, byteLength);
|
||||
byteLength += next.value.byteLength;
|
||||
if (byteLength > MAX_FAVICON_RESPONSE_BYTES) {
|
||||
await reader.cancel();
|
||||
return null;
|
||||
}
|
||||
chunks.push(Buffer.from(next.value));
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener("abort", cancelForAbort);
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
function isSupportedFaviconUrl(url: string): boolean {
|
||||
if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return false;
|
||||
if (/^data:/i.test(url)) return /^data:image\/[a-z0-9.+-]+(?:;[^,]*)?,/i.test(url);
|
||||
try {
|
||||
const protocol = new URL(url).protocol;
|
||||
return (
|
||||
(protocol === "http:" || protocol === "https:") && url.length <= MAX_FAVICON_HTTP_URL_LENGTH
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function decodeInlineFaviconPayload(payload: string): Buffer | null {
|
||||
const decoded = Buffer.allocUnsafe(Buffer.byteLength(payload));
|
||||
let inputOffset = 0;
|
||||
let outputOffset = 0;
|
||||
while (inputOffset < payload.length) {
|
||||
const escapeOffset = payload.indexOf("%", inputOffset);
|
||||
const literalEnd = escapeOffset === -1 ? payload.length : escapeOffset;
|
||||
outputOffset += decoded.write(payload.slice(inputOffset, literalEnd), outputOffset, "utf8");
|
||||
if (escapeOffset === -1) break;
|
||||
const hex = payload.slice(escapeOffset + 1, escapeOffset + 3);
|
||||
if (!/^[0-9a-f]{2}$/i.test(hex)) return null;
|
||||
decoded[outputOffset] = Number.parseInt(hex, 16);
|
||||
outputOffset += 1;
|
||||
inputOffset = escapeOffset + 3;
|
||||
}
|
||||
return decoded.subarray(0, outputOffset);
|
||||
}
|
||||
|
||||
function parseInlineFavicon(
|
||||
url: string,
|
||||
): { readonly buffer: Buffer; readonly mime: string } | null {
|
||||
if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return null;
|
||||
const match = /^data:(image\/[a-z0-9.+-]+)((?:;[^,]*)?),(.*)$/is.exec(url);
|
||||
if (!match) return null;
|
||||
const mime = match[1]?.toLowerCase();
|
||||
const parameters = match[2]
|
||||
?.split(";")
|
||||
.filter(Boolean)
|
||||
.map((parameter) => parameter.toLowerCase());
|
||||
const payload = match[3];
|
||||
if (!mime || !parameters || !payload) return null;
|
||||
const base64 = parameters.at(-1) === "base64";
|
||||
if (parameters.includes("base64") && !base64) return null;
|
||||
|
||||
let buffer: Buffer;
|
||||
try {
|
||||
if (base64) {
|
||||
if (!/^[a-z0-9+/]*={0,2}$/i.test(payload) || payload.length % 4 === 1) return null;
|
||||
buffer = Buffer.from(payload, "base64");
|
||||
if (buffer.toString("base64").replace(/=+$/, "") !== payload.replace(/=+$/, "")) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
const decoded = decodeInlineFaviconPayload(payload);
|
||||
if (!decoded) return null;
|
||||
buffer = decoded;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
return buffer.byteLength > 0 && buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES
|
||||
? { buffer, mime }
|
||||
: null;
|
||||
}
|
||||
|
||||
interface ImageDimensions {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
function safeDimensions(dimensions: ImageDimensions | null): dimensions is ImageDimensions {
|
||||
return (
|
||||
dimensions !== null &&
|
||||
Number.isSafeInteger(dimensions.width) &&
|
||||
Number.isSafeInteger(dimensions.height) &&
|
||||
dimensions.width > 0 &&
|
||||
dimensions.height > 0 &&
|
||||
dimensions.width * dimensions.height <= MAX_FAVICON_SOURCE_PIXELS
|
||||
);
|
||||
}
|
||||
|
||||
function pngDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (!buffer.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) || buffer.byteLength < 24) {
|
||||
return null;
|
||||
}
|
||||
return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
|
||||
}
|
||||
|
||||
function skipGifSubBlocks(buffer: Buffer, startOffset: number): number | null {
|
||||
let offset = startOffset;
|
||||
while (offset < buffer.byteLength) {
|
||||
const blockLength = buffer[offset]!;
|
||||
offset += 1;
|
||||
if (blockLength === 0) return offset;
|
||||
if (offset + blockLength > buffer.byteLength) return null;
|
||||
offset += blockLength;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function gifDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (buffer.byteLength < 13 || !/^GIF8[79]a$/u.test(buffer.subarray(0, 6).toString("ascii"))) {
|
||||
return null;
|
||||
}
|
||||
const logicalWidth = buffer.readUInt16LE(6);
|
||||
const logicalHeight = buffer.readUInt16LE(8);
|
||||
if (!safeDimensions({ width: logicalWidth, height: logicalHeight })) return null;
|
||||
const packed = buffer[10]!;
|
||||
let offset = 13 + ((packed & 0x80) === 0 ? 0 : 3 * 2 ** ((packed & 0x07) + 1));
|
||||
if (offset > buffer.byteLength) return null;
|
||||
let width = logicalWidth;
|
||||
let height = logicalHeight;
|
||||
let frameCount = 0;
|
||||
let framePixels = 0;
|
||||
while (offset < buffer.byteLength) {
|
||||
const marker = buffer[offset];
|
||||
if (marker === 0x3b) return frameCount > 0 ? { width, height } : null;
|
||||
if (marker === 0x2c) {
|
||||
if (offset + 10 > buffer.byteLength) return null;
|
||||
const left = buffer.readUInt16LE(offset + 1);
|
||||
const top = buffer.readUInt16LE(offset + 3);
|
||||
const frameWidth = buffer.readUInt16LE(offset + 5);
|
||||
const frameHeight = buffer.readUInt16LE(offset + 7);
|
||||
if (frameWidth === 0 || frameHeight === 0) return null;
|
||||
framePixels += frameWidth * frameHeight;
|
||||
if (framePixels > MAX_FAVICON_SOURCE_PIXELS) return null;
|
||||
width = Math.max(width, left + frameWidth);
|
||||
height = Math.max(height, top + frameHeight);
|
||||
if (!safeDimensions({ width, height })) return null;
|
||||
const framePacked = buffer[offset + 9]!;
|
||||
offset += 10;
|
||||
if ((framePacked & 0x80) !== 0) {
|
||||
offset += 3 * 2 ** ((framePacked & 0x07) + 1);
|
||||
}
|
||||
if (offset >= buffer.byteLength) return null;
|
||||
const minimumCodeSize = buffer[offset]!;
|
||||
if (minimumCodeSize < 2 || minimumCodeSize > 8) return null;
|
||||
offset += 1;
|
||||
const nextOffset = skipGifSubBlocks(buffer, offset);
|
||||
if (nextOffset === null) return null;
|
||||
offset = nextOffset;
|
||||
frameCount += 1;
|
||||
continue;
|
||||
}
|
||||
if (marker !== 0x21 || offset + 2 > buffer.byteLength) return null;
|
||||
const nextOffset = skipGifSubBlocks(buffer, offset + 2);
|
||||
if (nextOffset === null) return null;
|
||||
offset = nextOffset;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
interface JpegExifMetadata {
|
||||
readonly complete: boolean;
|
||||
readonly orientation: number | null;
|
||||
}
|
||||
|
||||
function jpegExifMetadata(segment: Buffer): JpegExifMetadata | null {
|
||||
if (segment.byteLength <= 6 || segment.subarray(0, 5).toString("binary") !== "Exif\0") {
|
||||
return null;
|
||||
}
|
||||
const metadataWithoutOrientation = (): JpegExifMetadata => ({
|
||||
complete: true,
|
||||
orientation: null,
|
||||
});
|
||||
if (segment.byteLength < 14) return metadataWithoutOrientation();
|
||||
const tiffOffset = 6;
|
||||
const littleEndian = segment[tiffOffset] === 0x49 && segment[tiffOffset + 1] === 0x49;
|
||||
const bigEndian = segment[tiffOffset] === 0x4d && segment[tiffOffset + 1] === 0x4d;
|
||||
if (!littleEndian && !bigEndian) return metadataWithoutOrientation();
|
||||
const readUInt16 = (offset: number): number | null => {
|
||||
if (offset < 0 || offset + 2 > segment.byteLength) return null;
|
||||
return littleEndian ? segment.readUInt16LE(offset) : segment.readUInt16BE(offset);
|
||||
};
|
||||
const readUInt32 = (offset: number): number | null => {
|
||||
if (offset < 0 || offset + 4 > segment.byteLength) return null;
|
||||
return littleEndian ? segment.readUInt32LE(offset) : segment.readUInt32BE(offset);
|
||||
};
|
||||
const relativeIfdOffset = readUInt32(tiffOffset + 4);
|
||||
if (relativeIfdOffset === null) return metadataWithoutOrientation();
|
||||
// Keep untrusted metadata parsing linear even when IFD pointers overlap.
|
||||
let remainingIfdEntryVisits = Math.ceil(segment.byteLength / 12);
|
||||
const budgetExhausted = Symbol("ifd-entry-budget-exhausted");
|
||||
type IfdOrientation = number | null | typeof budgetExhausted;
|
||||
const subIfdOrientationByOffset = new Map<number, number | null>();
|
||||
const readIfdOrientation = (ifdOffset: number, isRoot: boolean): IfdOrientation => {
|
||||
if (!isRoot && subIfdOrientationByOffset.has(ifdOffset)) {
|
||||
return subIfdOrientationByOffset.get(ifdOffset) ?? null;
|
||||
}
|
||||
const entryCount = readUInt16(ifdOffset);
|
||||
if (entryCount === null) return null;
|
||||
let result: IfdOrientation = null;
|
||||
for (let index = 0; index < entryCount; index += 1) {
|
||||
if (remainingIfdEntryVisits === 0) return budgetExhausted;
|
||||
remainingIfdEntryVisits -= 1;
|
||||
const entryOffset = ifdOffset + 2 + index * 12;
|
||||
if (entryOffset + 12 > segment.byteLength) break;
|
||||
const tag = readUInt16(entryOffset);
|
||||
const type = readUInt16(entryOffset + 2);
|
||||
const count = readUInt32(entryOffset + 4);
|
||||
if (tag === 0x0112 && type === 3 && count === 1) {
|
||||
const orientation = readUInt16(entryOffset + 8);
|
||||
if (orientation !== null && orientation >= 1 && orientation <= 8) {
|
||||
result = orientation;
|
||||
break;
|
||||
}
|
||||
} else if (isRoot && tag === 0x8769 && type === 4 && count === 1) {
|
||||
const relativeSubIfdOffset = readUInt32(entryOffset + 8);
|
||||
if (relativeSubIfdOffset !== null) {
|
||||
const orientation = readIfdOrientation(tiffOffset + relativeSubIfdOffset, false);
|
||||
if (orientation === budgetExhausted) return budgetExhausted;
|
||||
if (orientation !== null) {
|
||||
result = orientation;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isRoot) subIfdOrientationByOffset.set(ifdOffset, result);
|
||||
return result;
|
||||
};
|
||||
const orientation = readIfdOrientation(tiffOffset + relativeIfdOffset, true);
|
||||
return orientation === budgetExhausted
|
||||
? { complete: false, orientation: null }
|
||||
: { complete: true, orientation };
|
||||
}
|
||||
|
||||
function jpegDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (buffer.byteLength < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null;
|
||||
const startOfFrameMarkers = new Set([
|
||||
0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,
|
||||
]);
|
||||
let offset = 2;
|
||||
let dimensions: ImageDimensions | null = null;
|
||||
let exifMetadata: JpegExifMetadata | null = null;
|
||||
while (offset + 3 < buffer.byteLength) {
|
||||
if (buffer[offset] !== 0xff) {
|
||||
offset += 1;
|
||||
continue;
|
||||
}
|
||||
while (buffer[offset] === 0xff) offset += 1;
|
||||
const marker = buffer[offset];
|
||||
offset += 1;
|
||||
if (marker === undefined || marker === 0xd9 || marker === 0xda) break;
|
||||
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue;
|
||||
if (offset + 1 >= buffer.byteLength) return null;
|
||||
const length = buffer.readUInt16BE(offset);
|
||||
if (length < 2 || offset + length > buffer.byteLength) return null;
|
||||
if (marker === 0xe1 && exifMetadata === null) {
|
||||
exifMetadata = jpegExifMetadata(buffer.subarray(offset + 2, offset + length));
|
||||
}
|
||||
if (startOfFrameMarkers.has(marker)) {
|
||||
if (length < 7) return null;
|
||||
if (dimensions !== null) return null;
|
||||
dimensions = {
|
||||
height: buffer.readUInt16BE(offset + 3),
|
||||
width: buffer.readUInt16BE(offset + 5),
|
||||
};
|
||||
}
|
||||
offset += length;
|
||||
}
|
||||
if (!dimensions) return null;
|
||||
if (exifMetadata?.complete === false) return null;
|
||||
const orientation = exifMetadata?.orientation;
|
||||
return orientation !== undefined && orientation !== null && orientation >= 5 && orientation <= 8
|
||||
? { width: dimensions.height, height: dimensions.width }
|
||||
: dimensions;
|
||||
}
|
||||
|
||||
function webpDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (
|
||||
buffer.byteLength < 30 ||
|
||||
buffer.subarray(0, 4).toString("ascii") !== "RIFF" ||
|
||||
buffer.subarray(8, 12).toString("ascii") !== "WEBP"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const kind = buffer.subarray(12, 16).toString("ascii");
|
||||
if (kind === "VP8X") {
|
||||
return {
|
||||
width: 1 + buffer.readUIntLE(24, 3),
|
||||
height: 1 + buffer.readUIntLE(27, 3),
|
||||
};
|
||||
}
|
||||
if (kind === "VP8 " && buffer.subarray(23, 26).equals(Buffer.from([0x9d, 0x01, 0x2a]))) {
|
||||
return {
|
||||
width: buffer.readUInt16LE(26) & 0x3fff,
|
||||
height: buffer.readUInt16LE(28) & 0x3fff,
|
||||
};
|
||||
}
|
||||
if (kind === "VP8L" && buffer[20] === 0x2f) {
|
||||
return {
|
||||
width: 1 + buffer[21]! + ((buffer[22]! & 0x3f) << 8),
|
||||
height: 1 + (buffer[22]! >> 6) + (buffer[23]! << 2) + ((buffer[24]! & 0x0f) << 10),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function dibDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (buffer.byteLength < 12) return null;
|
||||
const headerSize = buffer.readUInt32LE(0);
|
||||
if (headerSize === 12) {
|
||||
return {
|
||||
width: buffer.readUInt16LE(4),
|
||||
height: buffer.readUInt16LE(6),
|
||||
};
|
||||
}
|
||||
if (headerSize < 40 || buffer.byteLength < 12) return null;
|
||||
return {
|
||||
width: Math.abs(buffer.readInt32LE(4)),
|
||||
height: Math.abs(buffer.readInt32LE(8)),
|
||||
};
|
||||
}
|
||||
|
||||
function icoDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
if (
|
||||
buffer.byteLength < 22 ||
|
||||
buffer.readUInt16LE(0) !== 0 ||
|
||||
(buffer.readUInt16LE(2) !== 1 && buffer.readUInt16LE(2) !== 2)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const count = buffer.readUInt16LE(4);
|
||||
if (count === 0 || count > 256 || buffer.byteLength < 6 + count * 16) return null;
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const offset = 6 + index * 16;
|
||||
width = Math.max(width, buffer[offset] === 0 ? 256 : buffer[offset]!);
|
||||
height = Math.max(height, buffer[offset + 1] === 0 ? 256 : buffer[offset + 1]!);
|
||||
if (!safeDimensions({ width, height })) return null;
|
||||
const byteLength = buffer.readUInt32LE(offset + 8);
|
||||
const imageOffset = buffer.readUInt32LE(offset + 12);
|
||||
if (
|
||||
byteLength === 0 ||
|
||||
imageOffset < 6 + count * 16 ||
|
||||
imageOffset > buffer.byteLength ||
|
||||
byteLength > buffer.byteLength - imageOffset
|
||||
)
|
||||
return null;
|
||||
const embedded = buffer.subarray(imageOffset, imageOffset + byteLength);
|
||||
const embeddedDimensions = pngDimensions(embedded) ?? dibDimensions(embedded);
|
||||
if (!safeDimensions(embeddedDimensions)) return null;
|
||||
}
|
||||
return { width, height };
|
||||
}
|
||||
|
||||
function sourceDimensions(buffer: Buffer): ImageDimensions | null {
|
||||
return (
|
||||
pngDimensions(buffer) ??
|
||||
gifDimensions(buffer) ??
|
||||
jpegDimensions(buffer) ??
|
||||
webpDimensions(buffer) ??
|
||||
icoDimensions(buffer)
|
||||
);
|
||||
}
|
||||
|
||||
async function normalizeFaviconBuffer(
|
||||
webContents: Electron.WebContents,
|
||||
mime: string | null,
|
||||
buffer: Buffer,
|
||||
signal: AbortSignal,
|
||||
): Promise<FaviconCaptureResult> {
|
||||
const declaredMime = mime?.trim().toLowerCase() || null;
|
||||
const normalizedMime =
|
||||
declaredMime === "application/x-icon"
|
||||
? "image/x-icon"
|
||||
: declaredMime === "application/octet-stream" || declaredMime === "binary/octet-stream"
|
||||
? null
|
||||
: declaredMime;
|
||||
const dimensions = sourceDimensions(buffer);
|
||||
if (
|
||||
(normalizedMime !== null && !/^image\/[a-z0-9.+-]+$/i.test(normalizedMime)) ||
|
||||
normalizedMime === "image/svg+xml" ||
|
||||
buffer.byteLength > MAX_FAVICON_RESPONSE_BYTES ||
|
||||
!safeDimensions(dimensions)
|
||||
) {
|
||||
return { kind: "none" };
|
||||
}
|
||||
|
||||
const rasterized = await rasterizeFavicon(
|
||||
webContents,
|
||||
normalizedMime,
|
||||
buffer,
|
||||
dimensions,
|
||||
signal,
|
||||
);
|
||||
if (rasterized.kind === "timed-out") return rasterized;
|
||||
return typeof rasterized.value === "string" &&
|
||||
rasterized.value.startsWith("data:image/png;base64,") &&
|
||||
rasterized.value.length <= FAVICON_DATA_URL_MAX_LENGTH
|
||||
? { kind: "captured", dataUrl: rasterized.value }
|
||||
: { kind: "none" };
|
||||
}
|
||||
|
||||
async function rasterizeFavicon(
|
||||
webContents: Electron.WebContents,
|
||||
mime: string | null,
|
||||
buffer: Buffer,
|
||||
dimensions: ImageDimensions,
|
||||
signal: AbortSignal,
|
||||
): Promise<RasterizationResult> {
|
||||
const gate = rasterizationGates.get(webContents) ?? { generation: 0 };
|
||||
rasterizationGates.set(webContents, gate);
|
||||
const generation = ++gate.generation;
|
||||
const previousLaunchAllowed = gate.launchAllowed;
|
||||
if (previousLaunchAllowed) {
|
||||
await waitForRasterLaunch(previousLaunchAllowed, signal);
|
||||
}
|
||||
if (signal.aborted || generation !== gate.generation) {
|
||||
return { kind: "completed", value: null };
|
||||
}
|
||||
|
||||
const payload = buffer.toString("base64");
|
||||
const blobType = mime ?? "";
|
||||
const scale = Math.min(32 / dimensions.width, 32 / dimensions.height);
|
||||
const decodeWidth = Math.max(1, Math.round(dimensions.width * scale));
|
||||
const decodeHeight = Math.max(1, Math.round(dimensions.height * scale));
|
||||
const drawX = (32 - decodeWidth) / 2;
|
||||
const drawY = (32 - decodeHeight) / 2;
|
||||
const code = `
|
||||
(() => {
|
||||
const rasterize = async () => {
|
||||
try {
|
||||
const source = Uint8Array.from(atob("${payload}"), (char) => char.charCodeAt(0));
|
||||
const bitmap = await createImageBitmap(new Blob([source], { type: "${blobType}" }), {
|
||||
resizeWidth: ${decodeWidth},
|
||||
resizeHeight: ${decodeHeight},
|
||||
resizeQuality: "high",
|
||||
});
|
||||
try {
|
||||
if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.width * bitmap.height > ${MAX_FAVICON_SOURCE_PIXELS}) {
|
||||
return null;
|
||||
}
|
||||
const canvas = new OffscreenCanvas(32, 32);
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return null;
|
||||
context.drawImage(bitmap, ${drawX}, ${drawY}, ${decodeWidth}, ${decodeHeight});
|
||||
const blob = await canvas.convertToBlob({ type: "image/png" });
|
||||
const output = new Uint8Array(await blob.arrayBuffer());
|
||||
let binary = "";
|
||||
for (const byte of output) binary += String.fromCharCode(byte);
|
||||
return "data:image/png;base64," + btoa(binary);
|
||||
} finally {
|
||||
bitmap.close();
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
return rasterize();
|
||||
})()
|
||||
`;
|
||||
|
||||
const execution = webContents.executeJavaScriptInIsolatedWorld(FAVICON_RASTER_WORLD_ID, [
|
||||
{ code },
|
||||
]);
|
||||
|
||||
const result = new Promise<RasterizationResult>((resolve, reject) => {
|
||||
// Electron cannot cancel isolated-world execution. This timeout ends only
|
||||
// the logical attempt; renderer work may finish after a newer attempt starts.
|
||||
const timeout = AbortSignal.timeout(FAVICON_RASTER_TIMEOUT_MS);
|
||||
let settled = false;
|
||||
const finish = (complete: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
timeout.removeEventListener("abort", onTimeout);
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
complete();
|
||||
};
|
||||
const onTimeout = () => {
|
||||
finish(() => resolve({ kind: "timed-out" }));
|
||||
};
|
||||
const onAbort = () => {
|
||||
finish(() => resolve({ kind: "completed", value: null }));
|
||||
};
|
||||
timeout.addEventListener("abort", onTimeout, { once: true });
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
void execution.then(
|
||||
(value) => {
|
||||
finish(() => resolve({ kind: "completed", value }));
|
||||
},
|
||||
(cause: unknown) => {
|
||||
finish(() => reject(cause));
|
||||
},
|
||||
);
|
||||
if (signal.aborted) onAbort();
|
||||
});
|
||||
// The logical timeout does not cancel Electron's renderer work. Keep the
|
||||
// gate closed until that physical execution actually settles.
|
||||
const launchAllowed = execution.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
gate.launchAllowed = launchAllowed;
|
||||
void launchAllowed.then(() => {
|
||||
if (gate.launchAllowed === launchAllowed) delete gate.launchAllowed;
|
||||
});
|
||||
return await result;
|
||||
}
|
||||
@@ -4,4 +4,3 @@ export const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
|
||||
export const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
|
||||
export const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
|
||||
export const HUMAN_INPUT_CHANNEL = "preview:human-input";
|
||||
export const MOUSE_NAVIGATE_CHANNEL = "preview:mouse-navigate";
|
||||
@@ -186,102 +186,6 @@ const makeTestPreviewWebContents = (
|
||||
capturePage,
|
||||
}) as never;
|
||||
|
||||
const TEST_FAVICON = "data:image/png;base64,cG5n";
|
||||
|
||||
const makeSourcePng = (width = 1, height = 1): Buffer => {
|
||||
const buffer = Buffer.alloc(24);
|
||||
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(buffer);
|
||||
buffer.writeUInt32BE(width, 16);
|
||||
buffer.writeUInt32BE(height, 20);
|
||||
return buffer;
|
||||
};
|
||||
|
||||
const makeFaviconWebContents = (options?: {
|
||||
readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
|
||||
readonly id?: number;
|
||||
readonly rasterize?: (code: string) => Promise<unknown>;
|
||||
readonly url?: string;
|
||||
}) => {
|
||||
const sourcePng = makeSourcePng();
|
||||
const listeners = new Map<string, (...args: never[]) => void>();
|
||||
let currentUrl = options?.url ?? "http://localhost:3200/";
|
||||
let destroyed = false;
|
||||
let loading = false;
|
||||
const fetch = vi.fn(
|
||||
options?.fetch ??
|
||||
(async () =>
|
||||
new Response(new Uint8Array(sourcePng), {
|
||||
headers: { "content-type": "image/png" },
|
||||
})),
|
||||
);
|
||||
const executeJavaScriptInIsolatedWorld = vi.fn(
|
||||
async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
|
||||
options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : TEST_FAVICON,
|
||||
);
|
||||
const reload = vi.fn();
|
||||
const loadURL = vi.fn(async (url: string) => {
|
||||
currentUrl = url;
|
||||
});
|
||||
const off = vi.fn();
|
||||
const debuggerOff = vi.fn();
|
||||
const webContents = {
|
||||
id: options?.id ?? 42,
|
||||
isDestroyed: () => destroyed,
|
||||
getType: () => "webview",
|
||||
getURL: () => currentUrl,
|
||||
getTitle: () => "Preview",
|
||||
isLoading: () => loading,
|
||||
isDevToolsOpened: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
reload,
|
||||
reloadIgnoringCache: vi.fn(),
|
||||
loadURL,
|
||||
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
|
||||
listeners.set(event, listener);
|
||||
}),
|
||||
off,
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
session: { fetch },
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: debuggerOff,
|
||||
},
|
||||
};
|
||||
return {
|
||||
executeJavaScriptInIsolatedWorld,
|
||||
fetch,
|
||||
debuggerOff,
|
||||
listeners,
|
||||
loadURL,
|
||||
off,
|
||||
reload,
|
||||
setDestroyed: (value: boolean) => {
|
||||
destroyed = value;
|
||||
},
|
||||
setLoading: (value: boolean) => {
|
||||
loading = value;
|
||||
},
|
||||
setUrl: (url: string) => {
|
||||
currentUrl = url;
|
||||
},
|
||||
webContents: webContents as never,
|
||||
};
|
||||
};
|
||||
|
||||
const settle = function* (until: () => boolean) {
|
||||
for (let attempt = 0; attempt < 30 && !until(); attempt++) {
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
}
|
||||
};
|
||||
|
||||
const makeTestPictureInPictureWindow = (loadURL: () => Promise<void> = async () => undefined) => {
|
||||
const listeners = new Map<string, () => void>();
|
||||
const send = vi.fn();
|
||||
@@ -353,32 +257,6 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("rejects a destroyed webview during registration", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const getType = vi.fn(() => "webview" as const);
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => true,
|
||||
getType,
|
||||
} as never);
|
||||
yield* manager.createTab("tab_destroyed_registration");
|
||||
|
||||
const exit = yield* Effect.exit(manager.registerWebview("tab_destroyed_registration", 42));
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({
|
||||
_tag: "PreviewWebContentsNotFoundError",
|
||||
tabId: "tab_destroyed_registration",
|
||||
webContentsId: 42,
|
||||
});
|
||||
}
|
||||
expect(getType).not.toHaveBeenCalled();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("isolates failed state listeners and continues delivery", () => {
|
||||
const loggedErrors: Array<unknown> = [];
|
||||
const logger = Logger.make(({ message }) => {
|
||||
@@ -497,492 +375,7 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("detaches a destroyed webview instead of navigating it", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_destroyed_navigation");
|
||||
yield* manager.registerWebview("tab_destroyed_navigation", 42);
|
||||
yield* manager.setColorScheme("tab_destroyed_navigation", "dark");
|
||||
preview.setDestroyed(true);
|
||||
|
||||
yield* manager.navigate("tab_destroyed_navigation", "https://example.com/");
|
||||
|
||||
expect(preview.loadURL).not.toHaveBeenCalled();
|
||||
expect(preview.reload).not.toHaveBeenCalled();
|
||||
expect(preview.off).toHaveBeenCalled();
|
||||
expect(preview.debuggerOff).toHaveBeenCalled();
|
||||
expect(states.at(-1)).toMatchObject({
|
||||
webContentsId: null,
|
||||
navStatus: { kind: "Loading", url: "https://example.com/" },
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not let destroyed-webview cleanup detach a same-id replacement", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const previous = makeFaviconWebContents();
|
||||
const replacement = makeFaviconWebContents({ url: "https://example.com/" });
|
||||
let current = previous.webContents;
|
||||
let startReplacementRegistration: () => void = () => void 0;
|
||||
const replacementReady = new Promise<void>((resolve) => {
|
||||
startReplacementRegistration = resolve;
|
||||
});
|
||||
fromId.mockImplementation(() => current);
|
||||
yield* manager.createTab("tab_destroyed_replacement_race");
|
||||
yield* manager.registerWebview("tab_destroyed_replacement_race", 42);
|
||||
yield* manager.setColorScheme("tab_destroyed_replacement_race", "dark");
|
||||
const replacementRegistration = yield* Effect.promise(() => replacementReady).pipe(
|
||||
Effect.flatMap(() => manager.registerWebview("tab_destroyed_replacement_race", 42)),
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
);
|
||||
previous.setDestroyed(true);
|
||||
previous.debuggerOff.mockImplementationOnce(() => {
|
||||
current = replacement.webContents;
|
||||
startReplacementRegistration();
|
||||
});
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
|
||||
yield* manager.navigate("tab_destroyed_replacement_race", "https://example.com/");
|
||||
const registrationExit = yield* Fiber.await(replacementRegistration);
|
||||
|
||||
expect(Exit.isSuccess(registrationExit)).toBe(true);
|
||||
expect(previous.off).toHaveBeenCalled();
|
||||
expect(replacement.off).not.toHaveBeenCalled();
|
||||
expect(states.at(-1)).toMatchObject({
|
||||
webContentsId: 42,
|
||||
navStatus: { kind: "Loading", url: "https://example.com/" },
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("publishes a canonical favicon origin while the page is loading", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents({
|
||||
url: `http://localhost:3200/${"x".repeat(3_000)}`,
|
||||
});
|
||||
preview.setLoading(true);
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_loading");
|
||||
yield* manager.registerWebview("tab_favicon_loading", 42);
|
||||
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
expect(states.at(-1)?.favicon).toMatchObject({
|
||||
dataUrl: TEST_FAVICON,
|
||||
pageUrl: "http://localhost:3200",
|
||||
});
|
||||
expect(states.at(-1)?.favicon?.capturedAt).toEqual(expect.any(Number));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("shares an identical in-flight event and lets a changed event win", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFirst!: (response: Response) => void;
|
||||
const firstResponse = new Promise<Response>((resolve) => {
|
||||
resolveFirst = resolve;
|
||||
});
|
||||
const preview = makeFaviconWebContents({
|
||||
fetch: (url) =>
|
||||
url.endsWith("first.png")
|
||||
? firstResponse
|
||||
: Promise.resolve(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
),
|
||||
});
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_latest");
|
||||
yield* manager.registerWebview("tab_favicon_latest", 42);
|
||||
|
||||
const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
|
||||
faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
|
||||
faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
|
||||
yield* settle(() => preview.fetch.mock.calls.length === 1);
|
||||
faviconUpdated({} as never, ["http://localhost:3200/second.png"] as never);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
resolveFirst(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
);
|
||||
yield* settle(() => false);
|
||||
|
||||
expect(preview.fetch).toHaveBeenCalledTimes(2);
|
||||
expect(states.filter((state) => state.favicon !== undefined)).toHaveLength(1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("allows an identical retry after an undecodable capture", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let rasterizations = 0;
|
||||
const preview = makeFaviconWebContents({
|
||||
rasterize: async () => (++rasterizations === 1 ? null : TEST_FAVICON),
|
||||
});
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_retry");
|
||||
yield* manager.registerWebview("tab_favicon_retry", 42);
|
||||
const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
|
||||
|
||||
faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
|
||||
yield* settle(() => rasterizations === 1);
|
||||
yield* settle(() => false);
|
||||
faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
expect(rasterizations).toBe(2);
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not publish a capture invalidated by navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFetch!: (response: Response) => void;
|
||||
const preview = makeFaviconWebContents({
|
||||
fetch: () =>
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
}),
|
||||
});
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_navigation");
|
||||
yield* manager.registerWebview("tab_favicon_navigation", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => preview.fetch.mock.calls.length === 1);
|
||||
preview.listeners.get("did-start-navigation")?.({
|
||||
isMainFrame: true,
|
||||
isSameDocument: false,
|
||||
} as never);
|
||||
preview.setUrl("https://example.com/");
|
||||
resolveFetch(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
);
|
||||
yield* settle(() => false);
|
||||
|
||||
expect(states.some((state) => state.favicon !== undefined)).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("retains a favicon when reloading the current URL without a new event", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_reload");
|
||||
yield* manager.registerWebview("tab_favicon_reload", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
yield* manager.navigate("tab_favicon_reload", "http://localhost:3200/");
|
||||
|
||||
expect(preview.reload).toHaveBeenCalledOnce();
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("clears a published favicon after a confirmed cross-origin navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_origin");
|
||||
yield* manager.registerWebview("tab_favicon_origin", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
preview.setUrl("https://example.com/");
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
|
||||
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect(
|
||||
"retains the previous document icon across a failed cross-origin navigation",
|
||||
() =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_failed_origin");
|
||||
yield* manager.registerWebview("tab_favicon_failed_origin", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
preview.listeners.get("did-fail-load")?.(
|
||||
{} as never,
|
||||
-105 as never,
|
||||
"Name not resolved" as never,
|
||||
"https://unreachable.example/" as never,
|
||||
true as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "LoadFailed");
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("does not resurrect an icon after a confirmed about:blank document", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_blank");
|
||||
yield* manager.registerWebview("tab_favicon_blank", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
preview.setUrl("about:blank");
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Idle");
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
|
||||
preview.setUrl("http://localhost:3200/");
|
||||
preview.listeners.get("did-navigate")?.({} as never);
|
||||
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("clears a published favicon when a replacement webview attaches", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const initial = makeFaviconWebContents({ id: 42 });
|
||||
const replacement = makeFaviconWebContents({ id: 43 });
|
||||
fromId.mockImplementation((id?: number) => {
|
||||
if (id === 42) return initial.webContents;
|
||||
if (id === 43) return replacement.webContents;
|
||||
return null;
|
||||
});
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_replace");
|
||||
yield* manager.registerWebview("tab_favicon_replace", 42);
|
||||
initial.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
yield* manager.registerWebview("tab_favicon_replace", 43);
|
||||
|
||||
expect(states.at(-1)?.webContentsId).toBe(43);
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("ignores an old capture that completes after webview replacement", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let resolveFetch!: (response: Response) => void;
|
||||
const initial = makeFaviconWebContents({
|
||||
id: 42,
|
||||
fetch: () =>
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveFetch = resolve;
|
||||
}),
|
||||
});
|
||||
const replacement = makeFaviconWebContents({ id: 43 });
|
||||
fromId.mockImplementation((id?: number) =>
|
||||
id === 42 ? initial.webContents : id === 43 ? replacement.webContents : null,
|
||||
);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_late_replace");
|
||||
yield* manager.registerWebview("tab_favicon_late_replace", 42);
|
||||
initial.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => initial.fetch.mock.calls.length === 1);
|
||||
|
||||
yield* manager.registerWebview("tab_favicon_late_replace", 43);
|
||||
resolveFetch(
|
||||
new Response(new Uint8Array(makeSourcePng()), {
|
||||
headers: { "content-type": "image/png" },
|
||||
}),
|
||||
);
|
||||
yield* settle(() => false);
|
||||
|
||||
expect(states.at(-1)?.webContentsId).toBe(43);
|
||||
expect(
|
||||
states.some((state) => state.webContentsId === 43 && state.favicon !== undefined),
|
||||
).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("treats a reused WebContents id as a new attachment", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const initial = makeFaviconWebContents({ id: 42 });
|
||||
const replacement = makeFaviconWebContents({ id: 42 });
|
||||
let active = initial.webContents;
|
||||
fromId.mockImplementation(() => active);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_reused_id");
|
||||
yield* manager.registerWebview("tab_favicon_reused_id", 42);
|
||||
initial.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
active = replacement.webContents;
|
||||
yield* manager.registerWebview("tab_favicon_reused_id", 42);
|
||||
|
||||
expect(states.at(-1)?.favicon).toBeUndefined();
|
||||
expect(initial.off).toHaveBeenCalled();
|
||||
expect(replacement.listeners.has("page-favicon-updated")).toBe(true);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("preserves a favicon when the active attachment registers again", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const preview = makeFaviconWebContents();
|
||||
fromId.mockReturnValue(preview.webContents);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
yield* manager.createTab("tab_favicon_reregister");
|
||||
yield* manager.registerWebview("tab_favicon_reregister", 42);
|
||||
preview.listeners.get("page-favicon-updated")?.(
|
||||
{} as never,
|
||||
["http://localhost:3200/favicon.png"] as never,
|
||||
);
|
||||
yield* settle(() => states.at(-1)?.favicon !== undefined);
|
||||
|
||||
yield* manager.registerWebview("tab_favicon_reregister", 42);
|
||||
|
||||
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// The guest reports whatever zoom level Chromium handed it from the app
|
||||
// window, so the tab's own zoom is the source of truth in both directions:
|
||||
// asserted onto every guest, never read back off one.
|
||||
effectIt.effect("keeps the tab's own zoom instead of the guest's reported zoom", () =>
|
||||
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let effectiveZoom = 0.9;
|
||||
@@ -1028,13 +421,18 @@ describe("PreviewManager", () => {
|
||||
yield* manager.createTab("tab_zoom");
|
||||
yield* manager.registerWebview("tab_zoom", 42);
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1);
|
||||
expect(setZoomFactor).toHaveBeenCalledWith(1);
|
||||
expect(states.at(-1)?.zoomFactor).toBe(0.9);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
// An app zoom leaves the guest reporting the inherited level. Navigating
|
||||
// must not adopt it as the preview's zoom.
|
||||
effectiveZoom = 0.8;
|
||||
url = "https://example.com/after-app-zoom";
|
||||
effectiveZoom = 1.25;
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
expect(setZoomFactor).not.toHaveBeenCalled();
|
||||
|
||||
zoomReadable = false;
|
||||
url = "https://example.com/after-zoom-read-failed";
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
@@ -1043,18 +441,7 @@ describe("PreviewManager", () => {
|
||||
url,
|
||||
title: "Example",
|
||||
});
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1);
|
||||
|
||||
// Only the preview's own zoom controls move it.
|
||||
yield* manager.zoomIn("tab_zoom");
|
||||
expect(setZoomFactor).toHaveBeenCalledWith(1.1);
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.1);
|
||||
|
||||
zoomReadable = false;
|
||||
listeners.get("did-navigate")?.();
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.1);
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
|
||||
const replacementSetZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
@@ -1083,103 +470,8 @@ describe("PreviewManager", () => {
|
||||
|
||||
yield* manager.registerWebview("tab_zoom", 43);
|
||||
|
||||
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.1);
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// Zooming the app UI pushes the window's zoom level onto every guest, so the
|
||||
// preview has to be put back at the zoom the user gave it.
|
||||
effectIt.effect("re-applies each tab's own zoom when the app window zooms", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const setZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_reapply");
|
||||
yield* manager.registerWebview("tab_reapply", 42);
|
||||
yield* manager.zoomIn("tab_reapply");
|
||||
setZoomFactor.mockClear();
|
||||
|
||||
yield* manager.reapplyZoom();
|
||||
|
||||
expect(setZoomFactor).toHaveBeenCalledTimes(1);
|
||||
expect(setZoomFactor).toHaveBeenCalledWith(1.1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// did-attach and dom-ready both re-register the guest that is already
|
||||
// attached, and a guest that just inherited the app window's zoom needs its
|
||||
// own back — without that round trip republishing tab state.
|
||||
effectIt.effect("re-asserts the tab's zoom when the active guest registers again", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
const setZoomFactor = vi.fn();
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor,
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: { on: vi.fn(), off: vi.fn() },
|
||||
send: webviewSend,
|
||||
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
const states: PreviewManager.PreviewTabState[] = [];
|
||||
yield* manager.subscribeStateChanges((_tabId, state) =>
|
||||
Effect.sync(() => {
|
||||
states.push(state);
|
||||
}),
|
||||
);
|
||||
|
||||
yield* manager.createTab("tab_reregister_zoom");
|
||||
yield* manager.registerWebview("tab_reregister_zoom", 42);
|
||||
yield* manager.zoomIn("tab_reregister_zoom");
|
||||
setZoomFactor.mockClear();
|
||||
const publishedBefore = states.length;
|
||||
|
||||
yield* manager.registerWebview("tab_reregister_zoom", 42);
|
||||
|
||||
expect(setZoomFactor).toHaveBeenCalledWith(1.1);
|
||||
expect(states.length).toBe(publishedBefore);
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.1);
|
||||
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
|
||||
expect(states.at(-1)?.zoomFactor).toBe(1.25);
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -2239,69 +1531,6 @@ describe("PreviewManager", () => {
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("navigates the guest history when the thumb-button ipc fires", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
let mouseNavigate: ((event: unknown, payload: unknown) => void) | undefined;
|
||||
const goBack = vi.fn();
|
||||
const goForward = vi.fn();
|
||||
let canGoBack = true;
|
||||
fromId.mockReturnValue({
|
||||
id: 42,
|
||||
isDestroyed: () => false,
|
||||
getType: () => "webview",
|
||||
getURL: () => "https://example.com",
|
||||
getTitle: () => "Example",
|
||||
isLoading: () => false,
|
||||
getZoomFactor: () => 1,
|
||||
setZoomFactor: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
ipc: {
|
||||
on: vi.fn((channel: string, listener: typeof mouseNavigate) => {
|
||||
if (channel === "preview:mouse-navigate") mouseNavigate = listener;
|
||||
}),
|
||||
off: vi.fn(),
|
||||
},
|
||||
send: webviewSend,
|
||||
navigationHistory: {
|
||||
canGoBack: () => canGoBack,
|
||||
canGoForward: () => true,
|
||||
goBack,
|
||||
goForward,
|
||||
},
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
debugger: {
|
||||
isAttached: () => false,
|
||||
attach: vi.fn(),
|
||||
sendCommand: vi.fn(async () => undefined),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
},
|
||||
} as never);
|
||||
|
||||
yield* manager.createTab("tab_nav");
|
||||
yield* manager.registerWebview("tab_nav", 42);
|
||||
expect(mouseNavigate).toBeDefined();
|
||||
|
||||
mouseNavigate?.({}, { direction: "back" });
|
||||
yield* Effect.yieldNow;
|
||||
expect(goBack).toHaveBeenCalledOnce();
|
||||
|
||||
mouseNavigate?.({}, { direction: "forward" });
|
||||
yield* Effect.yieldNow;
|
||||
expect(goForward).toHaveBeenCalledOnce();
|
||||
|
||||
// Ignores unknown payloads and never navigates when history is exhausted.
|
||||
mouseNavigate?.({}, { direction: "sideways" });
|
||||
canGoBack = false;
|
||||
mouseNavigate?.({}, { direction: "back" });
|
||||
yield* Effect.yieldNow;
|
||||
expect(goBack).toHaveBeenCalledOnce();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
effectIt.effect("reveals only files inside the configured browser artifact directory", () =>
|
||||
withManager((manager) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
import type {
|
||||
DesktopPreviewAnnotationTheme,
|
||||
DesktopPreviewColorScheme,
|
||||
DesktopPreviewFavicon,
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
@@ -16,7 +15,6 @@ import type {
|
||||
DesktopPreviewRecordingArtifact,
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewScreenshotArtifact,
|
||||
DesktopPreviewTabDefaults,
|
||||
PreviewAutomationClickInput,
|
||||
PreviewAutomationActionEvent,
|
||||
PreviewAutomationConsoleEntry,
|
||||
@@ -59,13 +57,11 @@ import {
|
||||
CANCEL_PICK_CHANNEL,
|
||||
ELEMENT_PICKED_CHANNEL,
|
||||
HUMAN_INPUT_CHANNEL,
|
||||
MOUSE_NAVIGATE_CHANNEL,
|
||||
START_PICK_CHANNEL,
|
||||
} from "./GuestProtocol.ts";
|
||||
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
|
||||
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
|
||||
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
|
||||
import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts";
|
||||
|
||||
export type PreviewNavStatus =
|
||||
| { kind: "Idle" }
|
||||
@@ -89,7 +85,6 @@ export interface PreviewTabState {
|
||||
pictureInPicture: boolean;
|
||||
colorScheme: DesktopPreviewColorScheme;
|
||||
controller: "human" | "agent" | "none";
|
||||
favicon?: DesktopPreviewFavicon;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
@@ -335,21 +330,6 @@ const findZoomStep = (current: number): number => {
|
||||
return Math.abs(ZOOM_LEVELS[index]! - current) < ZOOM_EPSILON ? index : index - 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Clamp a client-supplied zoom factor onto the discrete ladder. The setting is
|
||||
* chosen from the same ladder, but it arrives over IPC from a schema that only
|
||||
* guarantees a positive number, so an out-of-band value snaps to the nearest
|
||||
* step rather than leaving the guest at a zoom the zoom controls can't reach.
|
||||
*/
|
||||
const normalizeZoomFactor = (value: number | undefined): number => {
|
||||
if (value === undefined || !Number.isFinite(value)) return DEFAULT_ZOOM_FACTOR;
|
||||
let closest = ZOOM_LEVELS[0]!;
|
||||
for (const level of ZOOM_LEVELS) {
|
||||
if (Math.abs(level - value) < Math.abs(closest - value)) closest = level;
|
||||
}
|
||||
return closest;
|
||||
};
|
||||
|
||||
const nextZoomLevel = (current: number, direction: "in" | "out"): number => {
|
||||
const step = findZoomStep(current);
|
||||
if (direction === "in") {
|
||||
@@ -366,10 +346,7 @@ type PreviewInputSignal =
|
||||
| { readonly kind: "key"; readonly key: string; readonly code: string };
|
||||
|
||||
interface ManagedListeners {
|
||||
readonly attachmentId: symbol;
|
||||
readonly cancelFaviconCapture: () => void;
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly webContents: Electron.WebContents;
|
||||
}
|
||||
|
||||
type FrameCaptureConsumer = "picture-in-picture" | "recording";
|
||||
@@ -636,15 +613,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
|
||||
const emitIfCurrent = Effect.fn("PreviewManager.emitIfCurrent")(function* (
|
||||
tabId: string,
|
||||
state: PreviewTabState,
|
||||
) {
|
||||
if ((yield* SynchronizedRef.get(tabsRef)).get(tabId) === state) {
|
||||
yield* emit(tabId, state);
|
||||
}
|
||||
});
|
||||
|
||||
const update = Effect.fn("PreviewManager.update")(function* (
|
||||
tabId: string,
|
||||
patch: Partial<PreviewTabState>,
|
||||
@@ -664,22 +632,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
if (Option.isSome(next)) yield* emit(tabId, next.value);
|
||||
});
|
||||
|
||||
/**
|
||||
* Pushes a tab's zoom factor onto whichever guest it currently owns, reading
|
||||
* both at call time. Anything that applies zoom after an await goes through
|
||||
* here: a snapshot taken before the await can be older than a zoom action that
|
||||
* landed in between, and re-applying it would roll that action back.
|
||||
*/
|
||||
const assertTabZoom = Effect.fn("PreviewManager.assertTabZoom")(function* (tabId: string) {
|
||||
const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
if (!tab || tab.webContentsId == null) return;
|
||||
const wc = webContents.fromId(tab.webContentsId);
|
||||
if (!wc || wc.isDestroyed()) return;
|
||||
yield* attempt({ operation: "assertTabZoom", tabId, webContentsId: wc.id }, () =>
|
||||
wc.setZoomFactor(tab.zoomFactor),
|
||||
).pipe(Effect.ignore);
|
||||
});
|
||||
|
||||
const requireWebContents = Effect.fn("PreviewManager.requireWebContents")(function* (
|
||||
tabId: string,
|
||||
) {
|
||||
@@ -1252,10 +1204,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
copy.delete(webContentsId);
|
||||
}),
|
||||
]);
|
||||
if (managed) {
|
||||
managed.cancelFaviconCapture();
|
||||
yield* Scope.close(managed.scope, Exit.void).pipe(Effect.ignore);
|
||||
}
|
||||
if (managed) yield* Scope.close(managed.scope, Exit.void).pipe(Effect.ignore);
|
||||
});
|
||||
|
||||
const isAppShortcut = (input: Electron.Input): boolean =>
|
||||
@@ -1319,34 +1268,21 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
wc: Electron.WebContents,
|
||||
) {
|
||||
const scope = yield* Scope.fork(parentScope, "sequential");
|
||||
const attachmentId = Symbol();
|
||||
let documentId = 0;
|
||||
let nextRequestId = 0;
|
||||
let activeCapture: {
|
||||
readonly controller: AbortController;
|
||||
readonly documentId: number;
|
||||
readonly eventKey: string;
|
||||
readonly requestId: number;
|
||||
} | null = null;
|
||||
const cancelFaviconCapture = () => {
|
||||
documentId += 1;
|
||||
activeCapture?.controller.abort();
|
||||
activeCapture = null;
|
||||
};
|
||||
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
|
||||
preserveLoadFailure: boolean,
|
||||
confirmedNavigation = false,
|
||||
) {
|
||||
if (wc.isDestroyed()) return;
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "syncWebContentsState.getZoomFactor", tabId, webContentsId: wc.id },
|
||||
() => wc.getZoomFactor(),
|
||||
).pipe(Effect.option);
|
||||
const computedNavStatus = computeNavStatus(wc);
|
||||
const canGoBack = wc.navigationHistory.canGoBack();
|
||||
const canGoForward = wc.navigationHistory.canGoForward();
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (!current || current.webContentsId !== wc.id || webContents.fromId(wc.id) !== wc) {
|
||||
return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
}
|
||||
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
// Electron emits did-stop-loading after did-fail-load. At that point the
|
||||
// failed guest is no longer "loading", but it has not successfully
|
||||
// navigated anywhere. Keep the failure until a new load actually starts.
|
||||
@@ -1356,20 +1292,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
computedNavStatus.kind === "Success"
|
||||
? current.navStatus
|
||||
: computedNavStatus;
|
||||
const clearFavicon =
|
||||
confirmedNavigation &&
|
||||
current.favicon !== undefined &&
|
||||
safeHttpOrigin(current.favicon.pageUrl) !==
|
||||
safeHttpOrigin(navStatus.kind === "Idle" ? wc.getURL() : navStatus.url);
|
||||
const { favicon: _favicon, ...currentWithoutFavicon } = current;
|
||||
const state: PreviewTabState = {
|
||||
...(clearFavicon ? currentWithoutFavicon : current),
|
||||
...current,
|
||||
navStatus,
|
||||
canGoBack,
|
||||
canGoForward,
|
||||
// zoomFactor is deliberately not read back from the guest: Chromium
|
||||
// reports the level it inherited from the app window, so mirroring it
|
||||
// would turn an app zoom into the preview's own zoom.
|
||||
...(Option.isSome(zoomFactor) ? { zoomFactor: zoomFactor.value } : {}),
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
@@ -1379,109 +1307,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value);
|
||||
if (Option.isSome(next)) yield* emit(tabId, next.value);
|
||||
});
|
||||
const sync = () => runFork(syncState(true));
|
||||
const syncNavigation = () => runFork(syncState(false, true));
|
||||
const syncInPageNavigation = () => runFork(syncState(false));
|
||||
const navigationStarted = (
|
||||
event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
|
||||
) => {
|
||||
if (event.isMainFrame && !event.isSameDocument) cancelFaviconCapture();
|
||||
};
|
||||
const publishFavicon = Effect.fn("PreviewManager.publishFavicon")(function* (input: {
|
||||
readonly captureDocumentId: number;
|
||||
readonly dataUrl: string;
|
||||
readonly pageUrl: string;
|
||||
readonly requestId: number;
|
||||
}) {
|
||||
const pageOrigin = safeHttpOrigin(input.pageUrl);
|
||||
const managed = (yield* Ref.get(attachedRef)).get(wc.id);
|
||||
if (
|
||||
!pageOrigin ||
|
||||
wc.isDestroyed() ||
|
||||
webContents.fromId(wc.id) !== wc ||
|
||||
managed?.attachmentId !== attachmentId ||
|
||||
activeCapture?.documentId !== input.captureDocumentId ||
|
||||
activeCapture.requestId !== input.requestId ||
|
||||
safeHttpOrigin(wc.getURL()) !== pageOrigin
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const capturedAt = yield* currentMillis;
|
||||
const updatedAt = yield* currentIso;
|
||||
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (
|
||||
!current ||
|
||||
current.webContentsId !== wc.id ||
|
||||
webContents.fromId(wc.id) !== wc ||
|
||||
activeCapture?.documentId !== input.captureDocumentId ||
|
||||
activeCapture.requestId !== input.requestId
|
||||
) {
|
||||
return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
}
|
||||
const state: PreviewTabState = {
|
||||
...current,
|
||||
favicon: { dataUrl: input.dataUrl, pageUrl: pageOrigin, capturedAt },
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
Option.some(state),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, state);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value);
|
||||
});
|
||||
const faviconUpdated = (_event: Event, rawCandidates: ReadonlyArray<string>): void => {
|
||||
const pageUrl = wc.getURL();
|
||||
if (!safeHttpOrigin(pageUrl)) return;
|
||||
const candidates = selectFaviconCandidates(rawCandidates);
|
||||
if (candidates.length === 0) return;
|
||||
const eventKey = JSON.stringify([pageUrl, ...candidates]);
|
||||
if (activeCapture?.eventKey === eventKey) return;
|
||||
activeCapture?.controller.abort();
|
||||
const captureDocumentId = documentId;
|
||||
const requestId = ++nextRequestId;
|
||||
const controller = new AbortController();
|
||||
activeCapture = { controller, documentId: captureDocumentId, eventKey, requestId };
|
||||
runFork(
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
captureFavicon({ webContents: wc, pageUrl, candidates, signal: controller.signal }),
|
||||
catch: (cause) =>
|
||||
new PreviewOperationError({
|
||||
operation: "captureFavicon",
|
||||
tabId,
|
||||
webContentsId: wc.id,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.kind === "captured"
|
||||
? publishFavicon({
|
||||
captureDocumentId,
|
||||
dataUrl: result.dataUrl,
|
||||
pageUrl,
|
||||
requestId,
|
||||
})
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.catch((error) =>
|
||||
controller.signal.aborted
|
||||
? Effect.void
|
||||
: Effect.logDebug("Favicon capture failed.", { error, tabId, webContentsId: wc.id }),
|
||||
),
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
if (activeCapture?.requestId === requestId) activeCapture = null;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
const syncNavigation = () => runFork(syncState(false));
|
||||
const failed = (
|
||||
_event: Event,
|
||||
code: number,
|
||||
@@ -1523,22 +1352,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const humanInput = (_event: unknown, rawSignal?: unknown): void => {
|
||||
runFork(handleHumanInput(rawSignal));
|
||||
};
|
||||
const mouseNavigate = (_event: unknown, payload?: unknown): void => {
|
||||
const direction =
|
||||
typeof payload === "object" && payload !== null && "direction" in payload
|
||||
? (payload as { direction?: unknown }).direction
|
||||
: undefined;
|
||||
if (direction !== "back" && direction !== "forward") return;
|
||||
runFork(
|
||||
attempt({ operation: "mouseNavigate", tabId, webContentsId: wc.id }, () => {
|
||||
if (direction === "back") {
|
||||
if (wc.navigationHistory.canGoBack()) wc.navigationHistory.goBack();
|
||||
} else if (wc.navigationHistory.canGoForward()) {
|
||||
wc.navigationHistory.goForward();
|
||||
}
|
||||
}).pipe(Effect.ignore),
|
||||
);
|
||||
};
|
||||
const forwardShortcut = Effect.fn("PreviewManager.forwardShortcut")(function* (
|
||||
event: Electron.Event,
|
||||
input: Electron.Input,
|
||||
@@ -1574,32 +1387,25 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
cancelFaviconCapture();
|
||||
wc.off("did-start-navigation", navigationStarted);
|
||||
wc.off("did-navigate", syncNavigation);
|
||||
wc.off("did-navigate-in-page", syncInPageNavigation);
|
||||
wc.off("did-navigate-in-page", syncNavigation);
|
||||
wc.off("page-title-updated", sync);
|
||||
wc.off("page-favicon-updated", faviconUpdated as never);
|
||||
wc.off("did-start-loading", sync);
|
||||
wc.off("did-stop-loading", sync);
|
||||
wc.off("did-fail-load", failed as never);
|
||||
wc.off("before-input-event", beforeInput);
|
||||
wc.ipc.off(HUMAN_INPUT_CHANNEL, humanInput);
|
||||
wc.ipc.off(MOUSE_NAVIGATE_CHANNEL, mouseNavigate);
|
||||
}).pipe(Effect.ignore),
|
||||
);
|
||||
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
|
||||
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
|
||||
wc.on("did-start-navigation", navigationStarted);
|
||||
wc.on("did-navigate", syncNavigation);
|
||||
wc.on("did-navigate-in-page", syncInPageNavigation);
|
||||
wc.on("did-navigate-in-page", syncNavigation);
|
||||
wc.on("page-title-updated", sync);
|
||||
wc.on("page-favicon-updated", faviconUpdated as never);
|
||||
wc.on("did-start-loading", sync);
|
||||
wc.on("did-stop-loading", sync);
|
||||
wc.on("did-fail-load", failed as never);
|
||||
wc.ipc.on(HUMAN_INPUT_CHANNEL, humanInput);
|
||||
wc.ipc.on(MOUSE_NAVIGATE_CHANNEL, mouseNavigate);
|
||||
wc.setWindowOpenHandler(({ url }) => {
|
||||
runFork(
|
||||
attemptPromise({ operation: "openPreviewWindow", tabId, webContentsId: wc.id }, () =>
|
||||
@@ -1612,7 +1418,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
yield* Ref.update(attachedRef, (attached) =>
|
||||
replaceMap(attached, (copy) => {
|
||||
copy.set(wc.id, { attachmentId, cancelFaviconCapture, scope, webContents: wc });
|
||||
copy.set(wc.id, { scope });
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1630,7 +1436,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
|
||||
const createTabUnlocked = Effect.fn("PreviewManager.createTabUnlocked")(function* (
|
||||
tabId: string,
|
||||
defaults?: DesktopPreviewTabDefaults,
|
||||
) {
|
||||
const updatedAt = yield* currentIso;
|
||||
const result = yield* SynchronizedRef.modify(
|
||||
@@ -1649,9 +1454,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
navStatus: { kind: "Idle" },
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
zoomFactor: normalizeZoomFactor(defaults?.zoomFactor),
|
||||
zoomFactor: DEFAULT_ZOOM_FACTOR,
|
||||
pictureInPicture: false,
|
||||
colorScheme: defaults?.colorScheme ?? "system",
|
||||
colorScheme: "system",
|
||||
controller: "none",
|
||||
updatedAt,
|
||||
};
|
||||
@@ -1670,11 +1475,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return result.state;
|
||||
});
|
||||
|
||||
const createTab = Effect.fn("PreviewManager.createTab")(function* (
|
||||
tabId: string,
|
||||
defaults?: DesktopPreviewTabDefaults,
|
||||
) {
|
||||
return yield* withTabLifecycleLock(tabId, createTabUnlocked(tabId, defaults));
|
||||
const createTab = Effect.fn("PreviewManager.createTab")(function* (tabId: string) {
|
||||
return yield* withTabLifecycleLock(tabId, createTabUnlocked(tabId));
|
||||
});
|
||||
|
||||
const closeTabUnlocked = Effect.fn("PreviewManager.closeTabUnlocked")(function* (tabId: string) {
|
||||
@@ -1759,7 +1561,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const mainWindow = yield* Ref.get(mainWindowRef);
|
||||
if (
|
||||
!wc ||
|
||||
wc.isDestroyed() ||
|
||||
wc.getType() !== "webview" ||
|
||||
(Option.isSome(mainWindow) && wc.hostWebContents !== mainWindow.value.webContents)
|
||||
) {
|
||||
@@ -1767,22 +1568,19 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
}
|
||||
const attached = yield* Ref.get(attachedRef);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
const currentAttachment = attached.get(webContentsId);
|
||||
if (tab.webContentsId === webContentsId && currentAttachment?.webContents === wc) {
|
||||
// The guest we already own re-announced itself, so nothing about the tab
|
||||
// changed. Only push its zoom back down — Chromium may have just handed
|
||||
// this guest the app window's zoom level.
|
||||
yield* assertTabZoom(tabId);
|
||||
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
|
||||
const zoomFactor = yield* attempt(
|
||||
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
|
||||
() => wc.getZoomFactor(),
|
||||
);
|
||||
yield* update(tabId, { zoomFactor });
|
||||
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
|
||||
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const replacedWebContentsId =
|
||||
tab.webContentsId != null &&
|
||||
(tab.webContentsId !== webContentsId || currentAttachment?.webContents !== wc)
|
||||
? tab.webContentsId
|
||||
: null;
|
||||
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
|
||||
if (replacedWebContentsId !== null) {
|
||||
yield* Effect.all(
|
||||
[
|
||||
@@ -1801,13 +1599,18 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
) {
|
||||
return yield* new PreviewTabNotFoundError({ tabId });
|
||||
}
|
||||
// Always assert the tab's own zoom rather than reading the guest's: a guest
|
||||
// attaching while the app UI is zoomed starts at the embedder's inherited
|
||||
// zoom level, which is not the preview's zoom. Done before the guest is
|
||||
// published so it never paints a frame at the inherited zoom.
|
||||
yield* attempt({ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId }, () =>
|
||||
wc.setZoomFactor(currentTab.zoomFactor),
|
||||
);
|
||||
const zoomFactor =
|
||||
replacedWebContentsId !== null
|
||||
? yield* attempt(
|
||||
{ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId },
|
||||
() => {
|
||||
wc.setZoomFactor(currentTab.zoomFactor);
|
||||
return currentTab.zoomFactor;
|
||||
},
|
||||
)
|
||||
: yield* attempt({ operation: "registerWebview.getZoomFactor", tabId, webContentsId }, () =>
|
||||
wc.getZoomFactor(),
|
||||
);
|
||||
yield* attachListeners(tabId, wc);
|
||||
const registeredAt = yield* currentIso;
|
||||
const registration = yield* SynchronizedRef.modifyEffect(tabsRef, (tabs) =>
|
||||
@@ -1824,13 +1627,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
] as const;
|
||||
}
|
||||
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
|
||||
const { favicon: _favicon, ...currentWithoutFavicon } = current;
|
||||
const next: PreviewTabState = {
|
||||
...currentWithoutFavicon,
|
||||
...current,
|
||||
webContentsId,
|
||||
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
|
||||
canGoBack: wc.navigationHistory.canGoBack(),
|
||||
canGoForward: wc.navigationHistory.canGoForward(),
|
||||
zoomFactor,
|
||||
updatedAt: registeredAt,
|
||||
};
|
||||
return [
|
||||
@@ -1852,9 +1655,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return yield* new PreviewTabNotFoundError({ tabId });
|
||||
}
|
||||
const { state: registered, pendingUrl } = registration.value;
|
||||
// A zoom action that landed while this attach was in flight addressed the
|
||||
// guest this one replaced, so settle the new guest on the committed factor.
|
||||
yield* assertTabZoom(tabId);
|
||||
runFork(restoreControlSession(tabId, wc));
|
||||
yield* emit(tabId, registered);
|
||||
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
|
||||
@@ -1907,7 +1707,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
pictureInPicture: current?.pictureInPicture ?? false,
|
||||
colorScheme: current?.colorScheme ?? "system",
|
||||
controller: current?.controller ?? "none",
|
||||
...(current?.favicon ? { favicon: current.favicon } : {}),
|
||||
updatedAt,
|
||||
};
|
||||
return [
|
||||
@@ -1919,48 +1718,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
yield* emit(tabId, pending);
|
||||
if (pending.webContentsId == null) return;
|
||||
const webContentsId = pending.webContentsId;
|
||||
const wc = webContents.fromId(webContentsId);
|
||||
if (!wc || wc.isDestroyed()) {
|
||||
const expectedAttachment = (yield* Ref.get(attachedRef)).get(webContentsId);
|
||||
yield* withTabLifecycleLock(
|
||||
tabId,
|
||||
Effect.gen(function* () {
|
||||
const currentTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
|
||||
const currentAttachment = (yield* Ref.get(attachedRef)).get(webContentsId);
|
||||
const currentWebContents = webContents.fromId(webContentsId);
|
||||
if (
|
||||
currentTab?.webContentsId !== webContentsId ||
|
||||
currentAttachment !== expectedAttachment ||
|
||||
(currentWebContents && !currentWebContents.isDestroyed())
|
||||
) {
|
||||
return;
|
||||
}
|
||||
yield* Effect.all(
|
||||
[
|
||||
detachControlSession(webContentsId),
|
||||
detachListeners(webContentsId),
|
||||
cancelPickElement(tabId),
|
||||
],
|
||||
{ concurrency: 3, discard: true },
|
||||
);
|
||||
const detached = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
|
||||
const current = tabs.get(tabId);
|
||||
if (current?.webContentsId !== webContentsId) {
|
||||
return [Option.none<PreviewTabState>(), tabs] as const;
|
||||
}
|
||||
const { favicon: _favicon, ...currentWithoutFavicon } = current;
|
||||
const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId: null };
|
||||
return [
|
||||
Option.some(next),
|
||||
replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, next);
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
if (Option.isSome(detached)) yield* emitIfCurrent(tabId, detached.value);
|
||||
}),
|
||||
const wc = webContents.fromId(pending.webContentsId);
|
||||
if (!wc) {
|
||||
const detached = { ...pending, webContentsId: null };
|
||||
yield* SynchronizedRef.update(tabsRef, (tabs) =>
|
||||
tabs.get(tabId)?.webContentsId !== pending.webContentsId
|
||||
? tabs
|
||||
: replaceMap(tabs, (copy) => {
|
||||
copy.set(tabId, detached);
|
||||
}),
|
||||
);
|
||||
yield* emit(tabId, detached);
|
||||
return;
|
||||
}
|
||||
if (wc.getURL() === url) {
|
||||
@@ -2148,17 +1916,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Chromium hands every guest `<webview>` the embedder's zoom level, so zooming
|
||||
* the app UI drags the previewed page along with it. The preview browser owns
|
||||
* its own zoom factor, so re-assert it on each attached guest whenever the main
|
||||
* window's zoom changes (see DesktopWindow.zoomMain).
|
||||
*/
|
||||
const reapplyZoom = Effect.fn("PreviewManager.reapplyZoom")(function* () {
|
||||
const tabIds = Array.from((yield* SynchronizedRef.get(tabsRef)).keys());
|
||||
yield* Effect.forEach(tabIds, assertTabZoom, { discard: true });
|
||||
});
|
||||
|
||||
const applyZoom = Effect.fn("PreviewManager.applyZoom")(function* (
|
||||
tabId: string,
|
||||
transform: (current: number) => number,
|
||||
@@ -3536,7 +3293,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
openPictureInPicture,
|
||||
openDevTools,
|
||||
pickElement,
|
||||
reapplyZoom,
|
||||
refresh,
|
||||
registerWebview,
|
||||
resetZoom: (tabId: string) => applyZoom(tabId, () => DEFAULT_ZOOM_FACTOR),
|
||||
@@ -3822,10 +3578,7 @@ export class PreviewManager extends Context.Service<
|
||||
readonly setMainWindow: (window: BrowserWindow) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly getBrowserSession: (scope?: string) => Effect.Effect<Session, PreviewManagerError>;
|
||||
readonly isBrowserPartition: (partition: string) => boolean;
|
||||
readonly createTab: (
|
||||
tabId: string,
|
||||
defaults?: DesktopPreviewTabDefaults,
|
||||
) => Effect.Effect<PreviewTabState, PreviewManagerError>;
|
||||
readonly createTab: (tabId: string) => Effect.Effect<PreviewTabState, PreviewManagerError>;
|
||||
readonly closeTab: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly registerWebview: (
|
||||
tabId: string,
|
||||
@@ -3838,9 +3591,6 @@ export class PreviewManager extends Context.Service<
|
||||
readonly zoomIn: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
// Re-applies every attached guest's own zoom factor, undoing the zoom level
|
||||
// Chromium inherits from the embedder when the app UI zooms.
|
||||
readonly reapplyZoom: () => Effect.Effect<void>;
|
||||
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly setColorScheme: (
|
||||
tabId: string,
|
||||
@@ -3941,7 +3691,6 @@ export const make = Effect.gen(function* PreviewManagerMake() {
|
||||
zoomIn: operations.zoomIn,
|
||||
zoomOut: operations.zoomOut,
|
||||
resetZoom: operations.resetZoom,
|
||||
reapplyZoom: operations.reapplyZoom,
|
||||
hardReload: operations.hardReload,
|
||||
setColorScheme: operations.setColorScheme,
|
||||
openDevTools: operations.openDevTools,
|
||||
|
||||
@@ -22,7 +22,6 @@ import {
|
||||
CANCEL_PICK_CHANNEL,
|
||||
ELEMENT_PICKED_CHANNEL,
|
||||
HUMAN_INPUT_CHANNEL,
|
||||
MOUSE_NAVIGATE_CHANNEL,
|
||||
START_PICK_CHANNEL,
|
||||
} from "./GuestProtocol.ts";
|
||||
const OVERLAY_ATTRIBUTE = "data-t3code-annotation-ui";
|
||||
@@ -103,40 +102,6 @@ const reportHumanKeyInput = (event: KeyboardEvent): void => {
|
||||
window.addEventListener("pointerdown", reportHumanPointerInput, true);
|
||||
window.addEventListener("keydown", reportHumanKeyInput, true);
|
||||
|
||||
// Mouse thumb buttons: `button === 3` is Back, `button === 4` is Forward.
|
||||
const MOUSE_BUTTON_BACK = 3;
|
||||
const MOUSE_BUTTON_FORWARD = 4;
|
||||
|
||||
const navigationDirectionForButton = (button: number): "back" | "forward" | null => {
|
||||
if (button === MOUSE_BUTTON_BACK) return "back";
|
||||
if (button === MOUSE_BUTTON_FORWARD) return "forward";
|
||||
return null;
|
||||
};
|
||||
|
||||
// Chromium routes thumb-button history navigation to the *focused* WebContents,
|
||||
// so hovering this guest without focusing it sends the host app's router back
|
||||
// instead of the preview. Suppress Chromium's default here and drive this tab's
|
||||
// history explicitly so the buttons always navigate the browser the pointer is
|
||||
// over — never the host app.
|
||||
const suppressNavigationButton = (event: MouseEvent): void => {
|
||||
if (!event.isTrusted || navigationDirectionForButton(event.button) === null) return;
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
};
|
||||
|
||||
const requestNavigationForButton = (event: MouseEvent): void => {
|
||||
if (!event.isTrusted) return;
|
||||
const direction = navigationDirectionForButton(event.button);
|
||||
if (direction === null) return;
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
ipcRenderer.send(MOUSE_NAVIGATE_CHANNEL, { direction });
|
||||
};
|
||||
|
||||
window.addEventListener("mousedown", suppressNavigationButton, true);
|
||||
window.addEventListener("mouseup", requestNavigationForButton, true);
|
||||
window.addEventListener("auxclick", suppressNavigationButton, true);
|
||||
|
||||
const nextId = (prefix: string): string => {
|
||||
idSequence += 1;
|
||||
return `${prefix}_${idSequence.toString(36)}`;
|
||||
|
||||
@@ -13,11 +13,6 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
|
||||
|
||||
const clientSettings: ClientSettings = {
|
||||
browserDefaultViewport: { _tag: "preset", width: 1024, height: 600, presetId: "nest-hub" },
|
||||
browserDefaultZoomFactor: 1.25,
|
||||
browserDefaultAppearance: "dark",
|
||||
browserAutoShowFloatingPreview: false,
|
||||
confirmQuit: true,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
|
||||
@@ -152,108 +152,6 @@ describe("DesktopShellEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("hydrates the locale from the login shell on macOS", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "darwin",
|
||||
handler: () =>
|
||||
envOutput({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
LANG: "de_DE.UTF-8",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(env.LANG, "de_DE.UTF-8");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves an inherited locale over the login shell on macOS", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
LANG: "en_US.UTF-8",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "darwin",
|
||||
handler: () =>
|
||||
envOutput({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
LANG: "de_DE.UTF-8",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(env.LANG, "en_US.UTF-8");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not mix login-shell locale categories into an inherited locale", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
LANG: "en_US.UTF-8",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "darwin",
|
||||
handler: () =>
|
||||
envOutput({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
LC_ALL: "de_DE.UTF-8",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(env.LANG, "en_US.UTF-8");
|
||||
assert.equal(env.LC_ALL, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to a UTF-8 LC_CTYPE when no locale is available on macOS", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "darwin",
|
||||
handler: () => envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" }),
|
||||
});
|
||||
|
||||
assert.equal(env.LANG, undefined);
|
||||
assert.equal(env.LC_ALL, undefined);
|
||||
assert.equal(env.LC_CTYPE, "en_US.UTF-8");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not apply the locale fallback on linux", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "linux",
|
||||
handler: () => envOutput({ PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin" }),
|
||||
});
|
||||
|
||||
assert.equal(env.LANG, undefined);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
|
||||
@@ -71,9 +71,6 @@ const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
"DBUS_SESSION_BUS_ADDRESS",
|
||||
"DISPLAY",
|
||||
"LANG",
|
||||
"LC_ALL",
|
||||
"LC_CTYPE",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
@@ -87,8 +84,6 @@ const LOGIN_SHELL_ENV_NAMES = [
|
||||
"WAYLAND_DISPLAY",
|
||||
] as const;
|
||||
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
|
||||
const LOCALE_ENV_NAMES = ["LANG", "LC_ALL", "LC_CTYPE"] as const;
|
||||
const FALLBACK_LC_CTYPE = "en_US.UTF-8";
|
||||
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
|
||||
const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
|
||||
const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
|
||||
@@ -477,29 +472,6 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
|
||||
}
|
||||
}
|
||||
|
||||
// Locale variables form one precedence group: LC_ALL can override an inherited
|
||||
// LANG or LC_CTYPE, so only hydrate the group when the process has none of them.
|
||||
if (
|
||||
config.platform === "darwin" &&
|
||||
LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))
|
||||
) {
|
||||
for (const name of LOCALE_ENV_NAMES) {
|
||||
const value = trimNonEmpty(shellEnvironment[name]);
|
||||
if (Option.isSome(value)) {
|
||||
config.env[name] = value.value;
|
||||
}
|
||||
}
|
||||
|
||||
// GUI launches inherit no locale from launchd, so spawned agents land in the C
|
||||
// locale and pbcopy decodes their UTF-8 output as MacRoman. Older supported
|
||||
// macOS releases do not provide C.UTF-8, so set only LC_CTYPE to a UTF-8 locale
|
||||
// available on those releases. Leaving LANG unset keeps C-stable collation and
|
||||
// formatting, so output parsing is unaffected.
|
||||
if (LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
|
||||
config.env.LC_CTYPE = FALLBACK_LC_CTYPE;
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
config.platform === "linux" &&
|
||||
Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
|
||||
|
||||
@@ -26,7 +26,6 @@ function makeElectronAppLayer(
|
||||
return Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
systemLocale: Effect.succeed("en-US"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
@@ -157,8 +156,11 @@ describe("DesktopTelemetryPublisher", () => {
|
||||
decodeMessage(decoder.decode(bytes).trim()),
|
||||
);
|
||||
|
||||
assert.equal(messages[0]?.type, "desktopTelemetryHello");
|
||||
assert.equal(messages[0]?.electronPid, process.pid);
|
||||
const hello = messages[0];
|
||||
if (hello?.type !== "desktopTelemetryHello") {
|
||||
return assert.fail("Expected the first telemetry message to be the hello.");
|
||||
}
|
||||
assert.equal(hello.electronPid, process.pid);
|
||||
const initialSnapshot = messages[1];
|
||||
if (initialSnapshot?.type !== "desktopTelemetry") {
|
||||
return assert.fail("Expected the second telemetry message to be a snapshot.");
|
||||
@@ -386,4 +388,80 @@ describe("DesktopTelemetryPublisher", () => {
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes requestDesktopUpdate control messages and replays update reports", () =>
|
||||
Effect.gen(function* () {
|
||||
const powerLayer = Layer.succeed(
|
||||
ElectronPowerMonitor.ElectronPowerMonitor,
|
||||
ElectronPowerMonitor.ElectronPowerMonitor.of({
|
||||
isOnBatteryPower: Effect.succeed(false),
|
||||
getSystemIdleTime: Effect.succeed(0),
|
||||
getSystemIdleState: () => Effect.succeed("active"),
|
||||
getCurrentThermalState: Effect.succeed("nominal"),
|
||||
onSimpleEvent: () => Effect.void,
|
||||
onThermalStateChange: () => Effect.void,
|
||||
onSpeedLimitChange: () => Effect.void,
|
||||
}),
|
||||
);
|
||||
const layer = DesktopTelemetryPublisher.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(makeElectronAppLayer([]), powerLayer)),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
|
||||
const requestFiber = yield* Stream.runHead(publisher.updateRequests).pipe(Effect.forkChild);
|
||||
yield* Effect.yieldNow;
|
||||
yield* publisher.handleControlForSource("test", {
|
||||
version: 1,
|
||||
type: "requestDesktopUpdate",
|
||||
requestId: "req-9",
|
||||
});
|
||||
const received = yield* Fiber.join(requestFiber);
|
||||
assert.equal(Option.getOrThrow(received).requestId, "req-9");
|
||||
|
||||
const report = {
|
||||
version: 1,
|
||||
type: "desktopUpdateStatus",
|
||||
outcome: "up-to-date",
|
||||
state: {
|
||||
enabled: true,
|
||||
status: "up-to-date",
|
||||
channel: "latest",
|
||||
currentVersion: "1.2.3",
|
||||
hostArch: "arm64",
|
||||
appArch: "arm64",
|
||||
runningUnderArm64Translation: false,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
},
|
||||
} as const;
|
||||
yield* publisher.publishUpdateReport(report);
|
||||
|
||||
// A subscriber that attaches after the publish (the backend spawned
|
||||
// by a relaunch) still sees the latest report replayed.
|
||||
const decoder = new TextDecoder();
|
||||
const decodeMessage = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(DesktopHostTelemetryMessage),
|
||||
);
|
||||
const replayed = yield* publisher.encoded.pipe(
|
||||
Stream.mapEffect((bytes) => decodeMessage(decoder.decode(bytes).trim())),
|
||||
Stream.filter((message) => message.type === "desktopUpdateStatus"),
|
||||
Stream.runHead,
|
||||
);
|
||||
const replayedReport = Option.getOrThrow(replayed);
|
||||
if (replayedReport.type !== "desktopUpdateStatus") {
|
||||
return assert.fail("Expected a desktop update status report.");
|
||||
}
|
||||
assert.equal(replayedReport.outcome, "up-to-date");
|
||||
assert.equal(replayedReport.state.currentVersion, "1.2.3");
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2,6 +2,8 @@ import {
|
||||
DesktopHostTelemetryMessage,
|
||||
type DesktopHostTelemetrySnapshot,
|
||||
type DesktopTelemetryControlMessage,
|
||||
type DesktopTelemetryRequestDesktopUpdate,
|
||||
type DesktopUpdateStatusReport,
|
||||
type HostPowerSnapshot,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
@@ -65,6 +67,12 @@ export class DesktopTelemetryPublisher extends Context.Service<
|
||||
message: DesktopTelemetryControlMessage,
|
||||
) => Effect.Effect<void>;
|
||||
readonly removeControlSource: (sourceId: string) => Effect.Effect<void>;
|
||||
/** Sends the report to the attached backend and replays the latest one
|
||||
to backends that attach later (including the one spawned after a
|
||||
relaunch). */
|
||||
readonly publishUpdateReport: (report: DesktopUpdateStatusReport) => Effect.Effect<void>;
|
||||
/** Update requests received over the control channel. Single consumer. */
|
||||
readonly updateRequests: Stream.Stream<DesktopTelemetryRequestDesktopUpdate>;
|
||||
}
|
||||
>()("@t3tools/desktop/telemetry/DesktopTelemetryPublisher") {}
|
||||
|
||||
@@ -160,6 +168,9 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());
|
||||
const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);
|
||||
const sequence = yield* Ref.make(0);
|
||||
const latestUpdateReport = yield* Ref.make(Option.none<DesktopUpdateStatusReport>());
|
||||
const updateReportChanges = yield* PubSub.sliding<DesktopUpdateStatusReport>(16);
|
||||
const updateRequestQueue = yield* Queue.unbounded<DesktopTelemetryRequestDesktopUpdate>();
|
||||
|
||||
const offer = (event: PowerEvent): void => {
|
||||
Queue.offerUnsafe(powerEvents, event);
|
||||
@@ -324,6 +335,8 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
active: Duration.millis(message.activeIntervalMs),
|
||||
idle: Duration.millis(message.idleIntervalMs),
|
||||
}).pipe(Effect.andThen(Queue.offer(sampleTriggers, undefined)), Effect.asVoid);
|
||||
case "requestDesktopUpdate":
|
||||
return Queue.offer(updateRequestQueue, message).pipe(Effect.asVoid);
|
||||
}
|
||||
};
|
||||
const removeControlSource: DesktopTelemetryPublisher["Service"]["removeControlSource"] = (
|
||||
@@ -357,15 +370,36 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
);
|
||||
}),
|
||||
);
|
||||
const updateReports = Stream.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(updateReportChanges);
|
||||
const initial = yield* Ref.get(latestUpdateReport);
|
||||
return Stream.concat(
|
||||
Option.match(initial, {
|
||||
onNone: () => Stream.empty,
|
||||
onSome: Stream.make,
|
||||
}),
|
||||
Stream.fromSubscription(subscription),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const encoded = Stream.concat(
|
||||
Stream.make({
|
||||
version: 1,
|
||||
type: "desktopTelemetryHello",
|
||||
electronPid: process.pid,
|
||||
} as const),
|
||||
snapshots,
|
||||
Stream.merge(snapshots, updateReports),
|
||||
).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`)));
|
||||
|
||||
const publishUpdateReport: DesktopTelemetryPublisher["Service"]["publishUpdateReport"] = (
|
||||
report,
|
||||
) =>
|
||||
Ref.set(latestUpdateReport, Option.some(report)).pipe(
|
||||
Effect.andThen(PubSub.publish(updateReportChanges, report)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
return DesktopTelemetryPublisher.of({
|
||||
latest: Ref.get(latest),
|
||||
changes: Stream.fromPubSub(changes),
|
||||
@@ -373,6 +407,8 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () {
|
||||
handleControl,
|
||||
handleControlForSource,
|
||||
removeControlSource,
|
||||
publishUpdateReport,
|
||||
updateRequests: Stream.fromQueue(updateRequestQueue),
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import type {
|
||||
DesktopTelemetryRequestDesktopUpdate,
|
||||
DesktopUpdateStatusReport,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopRemoteUpdates from "./DesktopRemoteUpdates.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
import { makeHarness } from "./updatesTestHarness.ts";
|
||||
|
||||
// The remote flow hops between the test runtime's fibers and the updater's
|
||||
// runPromise-driven event handlers, so settling needs real microtask turns,
|
||||
// not just fiber yields.
|
||||
const settle = Effect.gen(function* () {
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.promise(() => Promise.resolve());
|
||||
}
|
||||
});
|
||||
|
||||
const request = (requestId: string): DesktopTelemetryRequestDesktopUpdate => ({
|
||||
version: 1,
|
||||
type: "requestDesktopUpdate",
|
||||
requestId,
|
||||
});
|
||||
|
||||
function runRemoteUpdatesTest(
|
||||
harness: ReturnType<typeof makeHarness>,
|
||||
body: (context: {
|
||||
readonly reports: DesktopUpdateStatusReport[];
|
||||
readonly requests: Queue.Queue<DesktopTelemetryRequestDesktopUpdate>;
|
||||
}) => Effect.Effect<void, never, DesktopUpdates.DesktopUpdates>,
|
||||
) {
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const requests = yield* Queue.unbounded<DesktopTelemetryRequestDesktopUpdate>();
|
||||
const reports: DesktopUpdateStatusReport[] = [];
|
||||
const publisher = DesktopTelemetryPublisher.DesktopTelemetryPublisher.of({
|
||||
latest: Effect.succeedNone,
|
||||
changes: Stream.empty,
|
||||
encoded: Stream.empty,
|
||||
handleControl: () => Effect.void,
|
||||
handleControlForSource: () => Effect.void,
|
||||
removeControlSource: () => Effect.void,
|
||||
publishUpdateReport: (report) =>
|
||||
Effect.sync(() => {
|
||||
reports.push(report);
|
||||
}),
|
||||
updateRequests: Stream.fromQueue(requests),
|
||||
});
|
||||
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
yield* DesktopRemoteUpdates.listen.pipe(
|
||||
Effect.provideService(DesktopTelemetryPublisher.DesktopTelemetryPublisher, publisher),
|
||||
);
|
||||
yield* settle;
|
||||
yield* body({ reports, requests });
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
}
|
||||
|
||||
function terminalReports(reports: DesktopUpdateStatusReport[]): DesktopUpdateStatusReport[] {
|
||||
return reports.filter((report) => report.outcome !== undefined);
|
||||
}
|
||||
|
||||
describe("DesktopRemoteUpdates", () => {
|
||||
it.effect("drives check, download, and install with no local confirmation", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-1"));
|
||||
yield* settle;
|
||||
assert.equal(harness.checkCount(), 1);
|
||||
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
|
||||
const terminals = terminalReports(reports);
|
||||
assert.equal(terminals.length, 1);
|
||||
assert.equal(terminals[0]?.outcome, "installing");
|
||||
assert.equal(terminals[0]?.requestId, "req-1");
|
||||
assert.equal(harness.quitAndInstalls(), 1);
|
||||
|
||||
// The mirror stamped the in-run state changes with the request id.
|
||||
const statuses = reports
|
||||
.filter((report) => report.requestId === "req-1")
|
||||
.map((report) => report.state.status);
|
||||
assert.include(statuses, "available");
|
||||
assert.include(statuses, "downloaded");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports a failed outcome when quitAndInstall fails", () => {
|
||||
const harness = makeHarness({
|
||||
quitAndInstall: Effect.fail(
|
||||
new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
|
||||
channel: "latest",
|
||||
isSilent: true,
|
||||
isForceRunAfter: true,
|
||||
cause: new Error("spawn failed"),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-4"));
|
||||
yield* settle;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
|
||||
// Install failures reduce to status "downloaded" + errorContext
|
||||
// "install"; the run must still end with a failed report after the
|
||||
// premature "installing" one.
|
||||
const terminals = terminalReports(reports);
|
||||
assert.deepEqual(
|
||||
terminals.map((report) => report.outcome),
|
||||
["installing", "failed"],
|
||||
);
|
||||
assert.equal(terminals[1]?.state.errorContext, "install");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("does not misread a lingering install error as a failed retry", () => {
|
||||
let installAttempts = 0;
|
||||
const harness = makeHarness({
|
||||
quitAndInstall: Effect.suspend(() => {
|
||||
installAttempts += 1;
|
||||
return installAttempts === 1
|
||||
? Effect.fail(
|
||||
new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
|
||||
channel: "latest",
|
||||
isSilent: true,
|
||||
isForceRunAfter: true,
|
||||
cause: new Error("first attempt failed"),
|
||||
}),
|
||||
)
|
||||
: Effect.void;
|
||||
}),
|
||||
});
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-5"));
|
||||
yield* settle;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
harness.emit("update-downloaded", { version: "1.2.4" });
|
||||
yield* settle;
|
||||
// First run failed; state is "downloaded" with a lingering
|
||||
// errorContext "install". The retry succeeds and must not report
|
||||
// that leftover as a fresh failure.
|
||||
yield* Queue.offer(requests, request("req-6"));
|
||||
yield* settle;
|
||||
|
||||
const retryTerminals = terminalReports(reports).filter(
|
||||
(report) => report.requestId === "req-6",
|
||||
);
|
||||
assert.deepEqual(
|
||||
retryTerminals.map((report) => report.outcome),
|
||||
["installing"],
|
||||
);
|
||||
assert.equal(harness.quitAndInstalls(), 2);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("reports up-to-date without installing when there is no update", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-2"));
|
||||
yield* settle;
|
||||
harness.emit("update-not-available");
|
||||
yield* settle;
|
||||
|
||||
const terminals = terminalReports(reports);
|
||||
assert.equal(terminals.length, 1);
|
||||
assert.equal(terminals[0]?.outcome, "up-to-date");
|
||||
assert.equal(terminals[0]?.requestId, "req-2");
|
||||
assert.equal(harness.quitAndInstalls(), 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("fails fast with the disabled reason when updates are off", () => {
|
||||
const harness = makeHarness({ env: { T3CODE_DISABLE_AUTO_UPDATE: "true" } });
|
||||
|
||||
return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Queue.offer(requests, request("req-3"));
|
||||
yield* settle;
|
||||
|
||||
const terminals = terminalReports(reports);
|
||||
assert.equal(terminals.length, 1);
|
||||
assert.equal(terminals[0]?.outcome, "failed");
|
||||
assert.equal(
|
||||
terminals[0]?.reason,
|
||||
"Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.",
|
||||
);
|
||||
assert.equal(harness.quitAndInstalls(), 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import type {
|
||||
DesktopTelemetryRequestDesktopUpdate,
|
||||
DesktopUpdateRemoteOutcome,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import type * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
import {
|
||||
nextRemoteDesktopUpdateStep,
|
||||
type RemoteDesktopUpdateAttempts,
|
||||
} from "./remoteUpdateFlow.ts";
|
||||
|
||||
const { logInfo, logError } = DesktopObservability.makeComponentLogger("desktop-remote-updates");
|
||||
|
||||
/**
|
||||
* Server-triggered desktop updates. Forks two fibers into the surrounding
|
||||
* scope: one mirrors every updater state change to the attached backend (so
|
||||
* the server always knows the desktop's update state), one consumes
|
||||
* requestDesktopUpdate control messages and drives check -> download ->
|
||||
* quit-and-install with no local confirmation. The remote click that caused
|
||||
* the request is the consent.
|
||||
*/
|
||||
export const listen: Effect.Effect<
|
||||
void,
|
||||
never,
|
||||
DesktopUpdates.DesktopUpdates | DesktopTelemetryPublisher.DesktopTelemetryPublisher | Scope.Scope
|
||||
> = Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher;
|
||||
const activeRequestIdRef = yield* Ref.make(Option.none<string>());
|
||||
|
||||
const publishReport = (
|
||||
state: DesktopUpdateState,
|
||||
terminal?: { readonly outcome: DesktopUpdateRemoteOutcome; readonly reason?: string },
|
||||
): Effect.Effect<void> =>
|
||||
Ref.get(activeRequestIdRef).pipe(
|
||||
Effect.flatMap((requestId) =>
|
||||
publisher.publishUpdateReport({
|
||||
version: 1,
|
||||
type: "desktopUpdateStatus",
|
||||
...(Option.isSome(requestId) ? { requestId: requestId.value } : {}),
|
||||
...(terminal === undefined ? {} : { outcome: terminal.outcome }),
|
||||
...(terminal?.reason === undefined ? {} : { reason: terminal.reason }),
|
||||
state,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const { latest, changes } = yield* updates.subscribe;
|
||||
yield* publishReport(latest);
|
||||
yield* Stream.runForEach(changes, (state) => publishReport(state));
|
||||
}),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
const handleRequest = (request: DesktopTelemetryRequestDesktopUpdate): Effect.Effect<void> =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
yield* Ref.set(activeRequestIdRef, Option.some(request.requestId));
|
||||
yield* logInfo("remote update requested", { requestId: request.requestId });
|
||||
const { latest, changes } = yield* updates.subscribe;
|
||||
const disabledReason = Option.getOrNull(yield* updates.disabledReason);
|
||||
let attempts: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
|
||||
|
||||
// Returns true when the run reached a terminal outcome.
|
||||
const step = (state: DesktopUpdateState): Effect.Effect<boolean, never, Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason);
|
||||
switch (next.action) {
|
||||
case "wait":
|
||||
return false;
|
||||
case "check":
|
||||
attempts = { ...attempts, checks: attempts.checks + 1 };
|
||||
yield* Effect.forkScoped(updates.check("remote-update"));
|
||||
return false;
|
||||
case "download":
|
||||
attempts = { ...attempts, downloads: attempts.downloads + 1 };
|
||||
yield* Effect.forkScoped(updates.download);
|
||||
return false;
|
||||
case "install": {
|
||||
// The terminal report must go out BEFORE installing:
|
||||
// install stops the backend server first, so anything
|
||||
// published after this point never reaches the requester.
|
||||
yield* publishReport(state, { outcome: "installing" });
|
||||
yield* logInfo("remote update installing", { requestId: request.requestId });
|
||||
const before = yield* updates.getState;
|
||||
const result = yield* updates.install;
|
||||
if (!result.accepted) {
|
||||
yield* publishReport(result.state, {
|
||||
outcome: "failed",
|
||||
reason: "The desktop app could not start the install.",
|
||||
});
|
||||
} else if (result.state !== before) {
|
||||
// During an accepted install the only state writes are the
|
||||
// failure reducers, so a transition means this attempt
|
||||
// failed. Field checks cannot tell a fresh failure from a
|
||||
// lingering errorContext left by a previous attempt, which
|
||||
// success does not clear.
|
||||
yield* publishReport(result.state, {
|
||||
outcome: "failed",
|
||||
reason: result.state.message ?? "The desktop app failed to install the update.",
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
case "done":
|
||||
yield* publishReport(state, {
|
||||
outcome: next.outcome,
|
||||
...(next.reason === undefined ? {} : { reason: next.reason }),
|
||||
});
|
||||
yield* logInfo("remote update finished", {
|
||||
requestId: request.requestId,
|
||||
outcome: next.outcome,
|
||||
reason: next.reason ?? null,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
if (yield* step(latest)) return;
|
||||
yield* changes.pipe(
|
||||
Stream.mapEffect(step),
|
||||
Stream.takeUntil((done) => done),
|
||||
Stream.runDrain,
|
||||
);
|
||||
}),
|
||||
).pipe(
|
||||
Effect.ensuring(Ref.set(activeRequestIdRef, Option.none())),
|
||||
Effect.catchCause((cause) =>
|
||||
logError("remote update request failed unexpectedly", {
|
||||
requestId: request.requestId,
|
||||
cause: String(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
// Sequential by construction: a second remote request queued mid-run is
|
||||
// handled after the current one, when the state machine resolves it fast.
|
||||
yield* Stream.runForEach(publisher.updateRequests, handleRequest).pipe(Effect.forkScoped);
|
||||
});
|
||||
@@ -1,6 +1,4 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
@@ -11,201 +9,14 @@ import * as Logger from "effect/Logger";
|
||||
import * as Option from "effect/Option";
|
||||
import * as References from "effect/References";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
|
||||
interface UpdatesHarnessOptions {
|
||||
readonly checkForUpdates?: Effect.Effect<
|
||||
void,
|
||||
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
|
||||
>;
|
||||
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
|
||||
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
|
||||
readonly stopBackend?: Effect.Effect<void>;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
}
|
||||
|
||||
const flushCallbacks = Effect.yieldNow;
|
||||
|
||||
function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
let checkCount = 0;
|
||||
let allowDowngrade = false;
|
||||
let fullChangelog = false;
|
||||
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
|
||||
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
|
||||
const sentStates: DesktopUpdateState[] = [];
|
||||
|
||||
const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName) ?? new Set();
|
||||
eventListeners.add(listener);
|
||||
listeners.set(eventName, eventListeners);
|
||||
};
|
||||
|
||||
const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName);
|
||||
if (!eventListeners) {
|
||||
return;
|
||||
}
|
||||
eventListeners.delete(listener);
|
||||
if (eventListeners.size === 0) {
|
||||
listeners.delete(eventName);
|
||||
}
|
||||
};
|
||||
|
||||
const updaterLayer = Layer.succeed(ElectronUpdater.ElectronUpdater, {
|
||||
setFeedURL: (options) =>
|
||||
Effect.sync(() => {
|
||||
feedUrls.push(options);
|
||||
}),
|
||||
setAutoDownload: () => Effect.void,
|
||||
setAutoInstallOnAppQuit: () => Effect.void,
|
||||
setChannel: () => Effect.void,
|
||||
setAllowPrerelease: () => Effect.void,
|
||||
allowDowngrade: Effect.sync(() => allowDowngrade),
|
||||
setAllowDowngrade: (value) =>
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.sync(() => {
|
||||
fullChangelog = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
|
||||
downloadUpdate: Effect.void,
|
||||
quitAndInstall: () => Effect.void,
|
||||
on: (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
} satisfies ElectronUpdater.ElectronUpdater["Service"]);
|
||||
|
||||
const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
|
||||
create: () => Effect.die("unexpected BrowserWindow creation"),
|
||||
main: Effect.succeed(Option.none()),
|
||||
currentMainOrFirst: Effect.succeed(Option.none()),
|
||||
focusedMainOrFirst: Effect.succeed(Option.none()),
|
||||
setMain: () => Effect.void,
|
||||
clearMain: () => Effect.void,
|
||||
reveal: () => Effect.void,
|
||||
sendAll: (_channel, state) =>
|
||||
Effect.sync(() => {
|
||||
sentStates.push(state as DesktopUpdateState);
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
|
||||
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
start: Effect.void,
|
||||
stop: () => options.stopBackend ?? Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none()),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const setUpdateChannelError = options.setUpdateChannelError;
|
||||
const settingsLayer = setUpdateChannelError
|
||||
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
|
||||
: DesktopAppSettings.layer;
|
||||
|
||||
const layer = DesktopUpdates.layer.pipe(
|
||||
Layer.provideMerge(updaterLayer),
|
||||
Layer.provideMerge(windowLayer),
|
||||
Layer.provideMerge(backendLayer),
|
||||
Layer.provideMerge(DesktopState.layer),
|
||||
Layer.provideMerge(settingsLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return {
|
||||
layer,
|
||||
checkCount: () => checkCount,
|
||||
feedUrls: () => feedUrls,
|
||||
fullChangelog: () => fullChangelog,
|
||||
listenerCount: () =>
|
||||
Array.from(listeners.values()).reduce(
|
||||
(total, eventListeners) => total + eventListeners.size,
|
||||
0,
|
||||
),
|
||||
sentStates,
|
||||
emit: (eventName: string, payload?: unknown) => {
|
||||
for (const listener of listeners.get(eventName) ?? []) {
|
||||
listener(payload);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts";
|
||||
|
||||
describe("DesktopUpdates", () => {
|
||||
it("preserves complete causes for update poller and event failures", () => {
|
||||
@@ -274,6 +85,29 @@ describe("DesktopUpdates", () => {
|
||||
}).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("subscribe delivers the latest state plus subsequent changes", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
return Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
yield* updates.configure;
|
||||
|
||||
const { latest, changes } = yield* updates.subscribe;
|
||||
assert.equal(latest.status, "idle");
|
||||
|
||||
const nextState = yield* Stream.runHead(changes).pipe(Effect.forkChild);
|
||||
yield* flushCallbacks;
|
||||
harness.emit("update-available", { version: "1.2.4" });
|
||||
yield* flushCallbacks;
|
||||
|
||||
const observed = yield* Fiber.join(nextState);
|
||||
assert.equal(Option.getOrThrow(observed).status, "available");
|
||||
assert.equal(Option.getOrThrow(observed).availableVersion, "1.2.4");
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
|
||||
});
|
||||
|
||||
it.effect("updates and broadcasts state from updater events", () => {
|
||||
const harness = makeHarness();
|
||||
|
||||
|
||||
@@ -14,9 +14,12 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
@@ -150,6 +153,15 @@ export class DesktopUpdates extends Context.Service<
|
||||
DesktopUpdates,
|
||||
{
|
||||
readonly getState: Effect.Effect<DesktopUpdateState>;
|
||||
/** Current state plus a stream of every later state change. */
|
||||
readonly subscribe: Effect.Effect<
|
||||
{
|
||||
readonly latest: DesktopUpdateState;
|
||||
readonly changes: Stream.Stream<DesktopUpdateState>;
|
||||
},
|
||||
never,
|
||||
Scope.Scope
|
||||
>;
|
||||
readonly emitState: Effect.Effect<void>;
|
||||
readonly disabledReason: Effect.Effect<Option.Option<string>>;
|
||||
readonly configure: Effect.Effect<void, DesktopUpdateConfigureError, Scope.Scope>;
|
||||
@@ -268,12 +280,21 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const stateChanges = yield* PubSub.sliding<DesktopUpdateState>(16);
|
||||
// Makes ref writes + publishes atomic against subscribe, so a snapshot
|
||||
// never overlaps with the first change a subscriber receives.
|
||||
const stateMutex = yield* Semaphore.make(1);
|
||||
|
||||
const emitState = Ref.get(updateStateRef).pipe(
|
||||
Effect.flatMap((state) => electronWindow.sendAll(IpcChannels.UPDATE_STATE_CHANNEL, state)),
|
||||
);
|
||||
|
||||
const setState = (state: DesktopUpdateState): Effect.Effect<void> =>
|
||||
Ref.set(updateStateRef, state).pipe(Effect.andThen(emitState));
|
||||
stateMutex
|
||||
.withPermits(1)(
|
||||
Ref.set(updateStateRef, state).pipe(Effect.andThen(PubSub.publish(stateChanges, state))),
|
||||
)
|
||||
.pipe(Effect.andThen(emitState));
|
||||
|
||||
const updateState = (
|
||||
f: (state: DesktopUpdateState) => DesktopUpdateState,
|
||||
@@ -705,6 +726,13 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
return DesktopUpdates.of({
|
||||
getState: Ref.get(updateStateRef),
|
||||
subscribe: stateMutex.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const subscription = yield* PubSub.subscribe(stateChanges);
|
||||
const latest = yield* Ref.get(updateStateRef);
|
||||
return { latest, changes: Stream.fromSubscription(subscription) };
|
||||
}),
|
||||
),
|
||||
emitState,
|
||||
disabledReason: resolveDisabledReason,
|
||||
configure: Effect.gen(function* () {
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
MAX_REMOTE_UPDATE_CHECKS,
|
||||
MAX_REMOTE_UPDATE_DOWNLOADS,
|
||||
nextRemoteDesktopUpdateStep,
|
||||
type RemoteDesktopUpdateAttempts,
|
||||
} from "./remoteUpdateFlow.ts";
|
||||
|
||||
const NO_ATTEMPTS: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 };
|
||||
|
||||
function makeState(overrides: Partial<DesktopUpdateState> = {}): DesktopUpdateState {
|
||||
return {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
channel: "latest",
|
||||
currentVersion: "1.2.3",
|
||||
hostArch: "arm64",
|
||||
appArch: "arm64",
|
||||
runningUnderArm64Translation: false,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
releaseNotes: [],
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("nextRemoteDesktopUpdateStep", () => {
|
||||
it("fails immediately when updates are disabled, preferring the known reason", () => {
|
||||
const state = makeState({ enabled: false, status: "disabled" });
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(state, NO_ATTEMPTS, "dev build"), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "dev build",
|
||||
});
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(state, NO_ATTEMPTS, null), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "Automatic updates are disabled on this machine.",
|
||||
});
|
||||
});
|
||||
|
||||
it("installs only from the downloaded status the updater will accept", () => {
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "downloaded", downloadedVersion: "1.2.4" }),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "install" },
|
||||
);
|
||||
// A previous install failure keeps status "downloaded", so a remote run
|
||||
// retries the install.
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({
|
||||
status: "downloaded",
|
||||
downloadedVersion: "1.2.4",
|
||||
errorContext: "install",
|
||||
message: "quitAndInstall failed",
|
||||
}),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "install" },
|
||||
);
|
||||
// A leftover downloadedVersion on an error state (background updater
|
||||
// error) must not report an install the updater refuses: fresh runs
|
||||
// re-check, and post-check it fails.
|
||||
const staleError = makeState({
|
||||
status: "error",
|
||||
downloadedVersion: "1.2.4",
|
||||
message: "background updater error",
|
||||
});
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(staleError, NO_ATTEMPTS, null), {
|
||||
action: "check",
|
||||
});
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(staleError, { checks: 1, downloads: 0 }, null), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "background updater error",
|
||||
});
|
||||
});
|
||||
|
||||
it("rides along while a check or download is already in flight", () => {
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(makeState({ status: "checking" }), NO_ATTEMPTS, null),
|
||||
{
|
||||
action: "wait",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "downloading", availableVersion: "1.2.4", downloadPercent: 40 }),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "wait" },
|
||||
);
|
||||
});
|
||||
|
||||
it("downloads an available update until the attempt cap, then fails", () => {
|
||||
const available = makeState({ status: "available", availableVersion: "1.2.4" });
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(available, NO_ATTEMPTS, null), {
|
||||
action: "download",
|
||||
});
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
available,
|
||||
{ checks: 1, downloads: MAX_REMOTE_UPDATE_DOWNLOADS },
|
||||
null,
|
||||
),
|
||||
{
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app failed to download the update.",
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({
|
||||
status: "available",
|
||||
availableVersion: "1.2.4",
|
||||
message: "network blipped",
|
||||
}),
|
||||
{ checks: 1, downloads: MAX_REMOTE_UPDATE_DOWNLOADS },
|
||||
null,
|
||||
),
|
||||
{ action: "done", outcome: "failed", reason: "network blipped" },
|
||||
);
|
||||
});
|
||||
|
||||
it("re-checks stale up-to-date and error states before trusting them", () => {
|
||||
// These states are retained from earlier/background checks; a remote
|
||||
// request must look again instead of replaying them.
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(makeState({ status: "up-to-date" }), NO_ATTEMPTS, null),
|
||||
{ action: "check" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "error", message: "feed unreachable" }),
|
||||
NO_ATTEMPTS,
|
||||
null,
|
||||
),
|
||||
{ action: "check" },
|
||||
);
|
||||
});
|
||||
|
||||
it("reports up-to-date and error states as terminal after this run's check", () => {
|
||||
const checked = { checks: 1, downloads: 0 };
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(makeState({ status: "up-to-date" }), checked, null),
|
||||
{ action: "done", outcome: "up-to-date" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState({ status: "error", message: "feed unreachable" }),
|
||||
checked,
|
||||
null,
|
||||
),
|
||||
{ action: "done", outcome: "failed", reason: "feed unreachable" },
|
||||
);
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(makeState({ status: "error" }), checked, null), {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app update failed.",
|
||||
});
|
||||
});
|
||||
|
||||
it("checks from idle until the attempt cap, then fails", () => {
|
||||
assert.deepEqual(nextRemoteDesktopUpdateStep(makeState(), NO_ATTEMPTS, null), {
|
||||
action: "check",
|
||||
});
|
||||
assert.deepEqual(
|
||||
nextRemoteDesktopUpdateStep(
|
||||
makeState(),
|
||||
{ checks: MAX_REMOTE_UPDATE_CHECKS, downloads: 0 },
|
||||
null,
|
||||
),
|
||||
{
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app did not report an update result.",
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { DesktopUpdateRemoteOutcome, DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* What a server-triggered update run should do next, given the updater's
|
||||
* current state. "wait" means an action (possibly started locally) is in
|
||||
* flight and the run should ride along until the next state change.
|
||||
*/
|
||||
export type RemoteDesktopUpdateStep =
|
||||
| { readonly action: "check" }
|
||||
| { readonly action: "download" }
|
||||
| { readonly action: "install" }
|
||||
| { readonly action: "wait" }
|
||||
| {
|
||||
readonly action: "done";
|
||||
readonly outcome: DesktopUpdateRemoteOutcome;
|
||||
readonly reason?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* How many times this run already issued each action. The caps are what stop
|
||||
* a check -> up-to-date -> check loop and endless download retries; they are
|
||||
* counts rather than booleans because a state event raced by the local
|
||||
* 4-minute poller can re-show an already-handled status once.
|
||||
*/
|
||||
export interface RemoteDesktopUpdateAttempts {
|
||||
readonly checks: number;
|
||||
readonly downloads: number;
|
||||
}
|
||||
|
||||
export const MAX_REMOTE_UPDATE_CHECKS = 2;
|
||||
export const MAX_REMOTE_UPDATE_DOWNLOADS = 3;
|
||||
|
||||
export function nextRemoteDesktopUpdateStep(
|
||||
state: DesktopUpdateState,
|
||||
attempts: RemoteDesktopUpdateAttempts,
|
||||
disabledReason: string | null,
|
||||
): RemoteDesktopUpdateStep {
|
||||
if (!state.enabled || state.status === "disabled") {
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: disabledReason ?? "Automatic updates are disabled on this machine.",
|
||||
};
|
||||
}
|
||||
// Only "downloaded" is installable: installDownloadedUpdate rejects any
|
||||
// other status. A leftover downloadedVersion on an "error" state (e.g. a
|
||||
// background updater error) must fall through to the error branch instead
|
||||
// of reporting an install that the updater will refuse.
|
||||
if (state.status === "downloaded") {
|
||||
return { action: "install" };
|
||||
}
|
||||
if (state.status === "downloading" || state.status === "checking") {
|
||||
return { action: "wait" };
|
||||
}
|
||||
if (state.status === "available") {
|
||||
if (attempts.downloads >= MAX_REMOTE_UPDATE_DOWNLOADS) {
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: state.message ?? "The desktop app failed to download the update.",
|
||||
};
|
||||
}
|
||||
return { action: "download" };
|
||||
}
|
||||
// "up-to-date" and "error" are retained from earlier/background checks,
|
||||
// so before this run has issued its own check they are stale, not
|
||||
// terminal: the whole point of a remote request is to look again.
|
||||
if (state.status === "up-to-date") {
|
||||
if (attempts.checks === 0) {
|
||||
return { action: "check" };
|
||||
}
|
||||
return { action: "done", outcome: "up-to-date" };
|
||||
}
|
||||
if (state.status === "error") {
|
||||
if (attempts.checks === 0) {
|
||||
return { action: "check" };
|
||||
}
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: state.message ?? "The desktop app update failed.",
|
||||
};
|
||||
}
|
||||
// status === "idle"
|
||||
if (attempts.checks >= MAX_REMOTE_UPDATE_CHECKS) {
|
||||
return {
|
||||
action: "done",
|
||||
outcome: "failed",
|
||||
reason: "The desktop app did not report an update result.",
|
||||
};
|
||||
}
|
||||
return { action: "check" };
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopUpdates from "./DesktopUpdates.ts";
|
||||
|
||||
/** Shared DesktopUpdates test harness: a fully stubbed updater layer whose
|
||||
electron-updater events are driven by hand via `emit`. Used by
|
||||
DesktopUpdates.test.ts and DesktopRemoteUpdates.test.ts. */
|
||||
|
||||
export const flushCallbacks = Effect.yieldNow;
|
||||
|
||||
export interface UpdatesHarnessOptions {
|
||||
readonly checkForUpdates?: Effect.Effect<
|
||||
void,
|
||||
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
|
||||
>;
|
||||
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
|
||||
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
|
||||
readonly quitAndInstall?: Effect.Effect<void, ElectronUpdater.ElectronUpdaterQuitAndInstallError>;
|
||||
readonly stopBackend?: Effect.Effect<void>;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
}
|
||||
|
||||
export function makeHarness(options: UpdatesHarnessOptions = {}) {
|
||||
let checkCount = 0;
|
||||
let quitAndInstallCount = 0;
|
||||
let allowDowngrade = false;
|
||||
let fullChangelog = false;
|
||||
const feedUrls: ElectronUpdater.ElectronUpdaterFeedUrl[] = [];
|
||||
const listeners = new Map<string, Set<(...args: readonly unknown[]) => void>>();
|
||||
const sentStates: DesktopUpdateState[] = [];
|
||||
|
||||
const addListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName) ?? new Set();
|
||||
eventListeners.add(listener);
|
||||
listeners.set(eventName, eventListeners);
|
||||
};
|
||||
|
||||
const removeListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
const eventListeners = listeners.get(eventName);
|
||||
if (!eventListeners) {
|
||||
return;
|
||||
}
|
||||
eventListeners.delete(listener);
|
||||
if (eventListeners.size === 0) {
|
||||
listeners.delete(eventName);
|
||||
}
|
||||
};
|
||||
|
||||
const updaterLayer = Layer.succeed(ElectronUpdater.ElectronUpdater, {
|
||||
setFeedURL: (options) =>
|
||||
Effect.sync(() => {
|
||||
feedUrls.push(options);
|
||||
}),
|
||||
setAutoDownload: () => Effect.void,
|
||||
setAutoInstallOnAppQuit: () => Effect.void,
|
||||
setChannel: () => Effect.void,
|
||||
setAllowPrerelease: () => Effect.void,
|
||||
allowDowngrade: Effect.sync(() => allowDowngrade),
|
||||
setAllowDowngrade: (value) =>
|
||||
Effect.sync(() => {
|
||||
allowDowngrade = value;
|
||||
}),
|
||||
setFullChangelog: (value) =>
|
||||
Effect.sync(() => {
|
||||
fullChangelog = value;
|
||||
}),
|
||||
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
|
||||
checkForUpdates: Effect.sync(() => {
|
||||
checkCount += 1;
|
||||
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
|
||||
downloadUpdate: Effect.void,
|
||||
quitAndInstall: () =>
|
||||
Effect.sync(() => {
|
||||
quitAndInstallCount += 1;
|
||||
}).pipe(Effect.andThen(options.quitAndInstall ?? Effect.void)),
|
||||
on: (eventName, listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
addListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
removeListener(eventName, listener as unknown as (...args: readonly unknown[]) => void);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
} satisfies ElectronUpdater.ElectronUpdater["Service"]);
|
||||
|
||||
const windowLayer = Layer.succeed(ElectronWindow.ElectronWindow, {
|
||||
create: () => Effect.die("unexpected BrowserWindow creation"),
|
||||
main: Effect.succeed(Option.none()),
|
||||
currentMainOrFirst: Effect.succeed(Option.none()),
|
||||
focusedMainOrFirst: Effect.succeed(Option.none()),
|
||||
setMain: () => Effect.void,
|
||||
clearMain: () => Effect.void,
|
||||
reveal: () => Effect.void,
|
||||
sendAll: (_channel, state) =>
|
||||
Effect.sync(() => {
|
||||
sentStates.push(state as DesktopUpdateState);
|
||||
}),
|
||||
destroyAll: Effect.void,
|
||||
syncAllAppearance: () => Effect.void,
|
||||
} satisfies ElectronWindow.ElectronWindow["Service"]);
|
||||
|
||||
const stubBackendInstance: DesktopBackendPool.DesktopBackendInstance = {
|
||||
id: DesktopBackendPool.PRIMARY_INSTANCE_ID,
|
||||
label: Effect.succeed("Windows"),
|
||||
start: Effect.void,
|
||||
stop: () => options.stopBackend ?? Effect.void,
|
||||
currentConfig: Effect.succeed(Option.none()),
|
||||
snapshot: Effect.succeed({
|
||||
desiredRunning: false,
|
||||
ready: false,
|
||||
activePid: Option.none(),
|
||||
restartAttempt: 0,
|
||||
restartScheduled: false,
|
||||
}),
|
||||
waitForReady: () => Effect.succeed(true),
|
||||
};
|
||||
const backendLayer = DesktopBackendPool.layerTest([stubBackendInstance]);
|
||||
|
||||
const environmentLayer = DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: `/tmp/t3-desktop-updates-home-${process.pid}`,
|
||||
platform: "darwin",
|
||||
processArch: "x64",
|
||||
appVersion: "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: true,
|
||||
resourcesPath: "/missing/resources",
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const setUpdateChannelError = options.setUpdateChannelError;
|
||||
const settingsLayer = setUpdateChannelError
|
||||
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
|
||||
setMainWindowBounds: () => Effect.die("unexpected main window bounds update"),
|
||||
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
|
||||
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
|
||||
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
|
||||
setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"),
|
||||
setWslDistro: () => Effect.die("unexpected WSL distro change"),
|
||||
setWslOnly: () => Effect.die("unexpected WSL-only toggle"),
|
||||
applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"),
|
||||
applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"),
|
||||
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
|
||||
: DesktopAppSettings.layer;
|
||||
|
||||
const layer = DesktopUpdates.layer.pipe(
|
||||
Layer.provideMerge(updaterLayer),
|
||||
Layer.provideMerge(windowLayer),
|
||||
Layer.provideMerge(backendLayer),
|
||||
Layer.provideMerge(DesktopState.layer),
|
||||
Layer.provideMerge(settingsLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
|
||||
T3CODE_DESKTOP_MOCK_UPDATES: "true",
|
||||
T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT: "4141",
|
||||
...options.env,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return {
|
||||
layer,
|
||||
checkCount: () => checkCount,
|
||||
quitAndInstalls: () => quitAndInstallCount,
|
||||
feedUrls: () => feedUrls,
|
||||
fullChangelog: () => fullChangelog,
|
||||
listenerCount: () =>
|
||||
Array.from(listeners.values()).reduce(
|
||||
(total, eventListeners) => total + eventListeners.size,
|
||||
0,
|
||||
),
|
||||
sentStates,
|
||||
emit: (eventName: string, payload?: unknown) => {
|
||||
for (const listener of listeners.get(eventName) ?? []) {
|
||||
listener(payload);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -31,7 +31,6 @@ const environmentInput = {
|
||||
const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
metadata: Effect.die("unexpected metadata read"),
|
||||
name: Effect.succeed("T3 Code"),
|
||||
systemLocale: Effect.succeed("en-US"),
|
||||
whenReady: Effect.void,
|
||||
quit: Effect.void,
|
||||
exit: () => Effect.void,
|
||||
@@ -60,6 +59,7 @@ const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
|
||||
|
||||
const desktopUpdatesLayer = Layer.succeed(DesktopUpdates.DesktopUpdates, {
|
||||
getState: Effect.die("unexpected getState"),
|
||||
subscribe: Effect.die("unexpected subscribe"),
|
||||
emitState: Effect.void,
|
||||
disabledReason: Effect.succeed(Option.none()),
|
||||
configure: Effect.void,
|
||||
|
||||
@@ -37,8 +37,6 @@ import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
@@ -63,14 +61,9 @@ const environmentInput = {
|
||||
function makeFakeBrowserWindow() {
|
||||
const windowListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
|
||||
let zoomLevel = 0;
|
||||
const webContents = {
|
||||
copyImageAt: vi.fn(),
|
||||
getURL: vi.fn(() => "t3code-dev://app/"),
|
||||
getZoomLevel: vi.fn(() => zoomLevel),
|
||||
setZoomLevel: vi.fn((level: number) => {
|
||||
zoomLevel = level;
|
||||
}),
|
||||
isLoadingMainFrame: vi.fn(() => false),
|
||||
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
|
||||
webContentsListeners.set(eventName, listener);
|
||||
@@ -123,21 +116,12 @@ function makeFakeBrowserWindow() {
|
||||
openDevTools: webContents.openDevTools,
|
||||
reload: webContents.reload,
|
||||
send: webContents.send,
|
||||
setZoomLevel: webContents.setZoomLevel,
|
||||
setAutoHideCursor: window.setAutoHideCursor,
|
||||
webContentsListeners,
|
||||
windowListeners,
|
||||
};
|
||||
}
|
||||
|
||||
const desktopClientSettingsLayer = Layer.mock(DesktopClientSettings.DesktopClientSettings)({
|
||||
get: Effect.succeed(Option.none()),
|
||||
});
|
||||
|
||||
const electronAppLayer = Layer.mock(ElectronApp.ElectronApp)({
|
||||
quit: Effect.void,
|
||||
});
|
||||
|
||||
const desktopAssetsLayer = Layer.succeed(DesktopAssets.DesktopAssets, {
|
||||
iconPaths: Effect.succeed({
|
||||
ico: Option.none<string>(),
|
||||
@@ -202,7 +186,6 @@ function makeTestLayer(input: {
|
||||
bounds: DesktopAppSettings.DesktopWindowBounds,
|
||||
) => Effect.Effect<void>;
|
||||
readonly openedExternalUrls?: unknown[];
|
||||
readonly previewZoomReapplies?: number[];
|
||||
}) {
|
||||
let desktopSettings = input.desktopSettings ?? DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS;
|
||||
const desktopAppSettingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
|
||||
@@ -263,10 +246,8 @@ function makeTestLayer(input: {
|
||||
desktopAssetsLayer,
|
||||
desktopEnvironmentLayer,
|
||||
desktopAppSettingsLayer,
|
||||
desktopClientSettingsLayer,
|
||||
desktopServerExposureLayer,
|
||||
DesktopState.layer,
|
||||
electronAppLayer,
|
||||
electronMenuLayer,
|
||||
Layer.succeed(ElectronShell.ElectronShell, {
|
||||
openExternal: (url) =>
|
||||
@@ -283,10 +264,6 @@ function makeTestLayer(input: {
|
||||
setMainWindow: () => Effect.void,
|
||||
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
|
||||
getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
|
||||
reapplyZoom: () =>
|
||||
Effect.sync(() => {
|
||||
input.previewZoomReapplies?.push(input.window.webContents.getZoomLevel());
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -368,9 +345,7 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
|
||||
desktopAssetsLayer,
|
||||
desktopEnvironmentLayer,
|
||||
DesktopAppSettings.layerTest(),
|
||||
desktopClientSettingsLayer,
|
||||
desktopServerExposureLayer,
|
||||
electronAppLayer,
|
||||
electronMenuLayer,
|
||||
Layer.succeed(ElectronShell.ElectronShell, {
|
||||
openExternal: () => Effect.succeed(true),
|
||||
@@ -508,42 +483,6 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
// Chromium hands the main window's zoom level down to embedded preview
|
||||
// guests, so every app zoom has to put the preview browser back at its own
|
||||
// zoom or zooming the UI drags the previewed page with it.
|
||||
it.effect("restores the preview browser's own zoom after zooming the app", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const previewZoomReapplies: number[] = [];
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
previewZoomReapplies,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
yield* desktopWindow.zoomMain("out");
|
||||
yield* desktopWindow.zoomMain("out");
|
||||
yield* desktopWindow.zoomMain("in");
|
||||
yield* desktopWindow.zoomMain("reset");
|
||||
|
||||
assert.deepEqual(
|
||||
fakeWindow.setZoomLevel.mock.calls.map(([level]) => level),
|
||||
[-0.5, -1, -0.5, 0],
|
||||
);
|
||||
// Recorded after the window level moved, so the preview is put back at
|
||||
// its own zoom on every step rather than left on the inherited one.
|
||||
assert.deepEqual(previewZoomReapplies, [-0.5, -1, -0.5, 0]);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses the persisted main window bounds when opening the window", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
@@ -8,8 +8,6 @@ import * as Ref from "effect/Ref";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";
|
||||
|
||||
import * as DesktopAssets from "../app/DesktopAssets.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "../app/DesktopObservability.ts";
|
||||
@@ -18,16 +16,9 @@ import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import {
|
||||
MENU_ACTION_CHANNEL,
|
||||
QUIT_SHORTCUT_CHANNEL,
|
||||
WINDOW_FULLSCREEN_STATE_CHANNEL,
|
||||
} from "../ipc/channels.ts";
|
||||
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import { makeQuitHoldHandler } from "./QuitHold.ts";
|
||||
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
@@ -60,8 +51,6 @@ type DesktopWindowRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopAssets.DesktopAssets
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
| DesktopClientSettings.DesktopClientSettings
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronMenu.ElectronMenu
|
||||
| ElectronShell.ElectronShell
|
||||
| ElectronTheme.ElectronTheme
|
||||
@@ -272,8 +261,6 @@ export const make = Effect.gen(function* () {
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
// Window-side latch for the primary backend's readiness. Set by
|
||||
// handleBackendReady (driven by the pool's onReady callback), cleared
|
||||
// by handleBackendNotReady (driven by onShutdown). Only consumed by
|
||||
@@ -546,32 +533,7 @@ export const make = Effect.gen(function* () {
|
||||
// close-terminal shortcut can outlive the terminal that handled its first
|
||||
// press, so reject repeats before they reach the native window accelerator.
|
||||
// Deliberate presses still flow through the renderer or native menu.
|
||||
// Chrome-style hold-to-quit: intercept the quit accelerator before the
|
||||
// native menu sees it and only quit after the shortcut is held. The
|
||||
// renderer shows the "Hold to Quit" hint via QUIT_SHORTCUT_CHANNEL.
|
||||
const quitHoldHandler = makeQuitHoldHandler({
|
||||
platform: environment.platform,
|
||||
isEnabled: () =>
|
||||
runPromise(
|
||||
Effect.map(
|
||||
clientSettings.get,
|
||||
Option.match({
|
||||
onNone: () => DEFAULT_CLIENT_SETTINGS.confirmQuit,
|
||||
onSome: (settings) => settings.confirmQuit,
|
||||
}),
|
||||
),
|
||||
),
|
||||
notify: (state) => {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(QUIT_SHORTCUT_CHANNEL, state);
|
||||
}
|
||||
},
|
||||
quit: () => {
|
||||
void runPromise(electronApp.quit);
|
||||
},
|
||||
});
|
||||
window.webContents.on("before-input-event", (event, input) => {
|
||||
quitHoldHandler(event, input);
|
||||
if (input.type !== "keyDown" || !input.isAutoRepeat) return;
|
||||
const modifier = environment.platform === "darwin" ? input.meta : input.control;
|
||||
if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
|
||||
@@ -893,10 +855,6 @@ export const make = Effect.gen(function* () {
|
||||
webContents.setZoomLevel(
|
||||
direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
|
||||
);
|
||||
// Chromium pushes the new level down to embedded guests, which would zoom
|
||||
// the previewed page along with the app UI. The preview browser keeps its
|
||||
// own zoom, so put each guest back where the preview left it.
|
||||
yield* previewManager.reapplyZoom();
|
||||
}),
|
||||
syncAppearance: Effect.gen(function* () {
|
||||
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
|
||||
|
||||
@@ -1,201 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
makeQuitHoldHandler,
|
||||
QUIT_DOUBLE_TAP_MS,
|
||||
QUIT_HOLD_DURATION_MS,
|
||||
QUIT_HOLD_RELEASE_GRACE_MS,
|
||||
} from "./QuitHold.ts";
|
||||
import type { QuitHoldKeyInput, QuitHoldState } from "./QuitHold.ts";
|
||||
|
||||
function makeInput(overrides: Partial<QuitHoldKeyInput>): QuitHoldKeyInput {
|
||||
return {
|
||||
type: "keyDown",
|
||||
key: "q",
|
||||
meta: true,
|
||||
control: false,
|
||||
alt: false,
|
||||
shift: false,
|
||||
isAutoRepeat: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeHarness(options?: {
|
||||
enabled?: boolean;
|
||||
platform?: NodeJS.Platform;
|
||||
isEnabled?: () => Promise<boolean>;
|
||||
}) {
|
||||
const notifications: Array<QuitHoldState> = [];
|
||||
const quit = vi.fn();
|
||||
const handler = makeQuitHoldHandler({
|
||||
platform: options?.platform ?? "darwin",
|
||||
isEnabled: options?.isEnabled ?? (() => Promise.resolve(options?.enabled ?? true)),
|
||||
notify: (state) => notifications.push(state),
|
||||
quit,
|
||||
});
|
||||
const preventDefault = vi.fn();
|
||||
const send = async (input: QuitHoldKeyInput) => {
|
||||
handler({ preventDefault }, input);
|
||||
// Let the isEnabled promise settle.
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
};
|
||||
// Simulates the OS auto-repeating the held shortcut every `intervalMs`.
|
||||
const holdFor = async (
|
||||
durationMs: number,
|
||||
repeatOverrides: Partial<QuitHoldKeyInput> = {},
|
||||
intervalMs = 100,
|
||||
) => {
|
||||
for (let elapsed = 0; elapsed < durationMs; elapsed += intervalMs) {
|
||||
vi.advanceTimersByTime(intervalMs);
|
||||
await send(makeInput({ isAutoRepeat: true, ...repeatOverrides }));
|
||||
}
|
||||
};
|
||||
return { notifications, quit, preventDefault, send, holdFor };
|
||||
}
|
||||
|
||||
describe("makeQuitHoldHandler", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("shows the hint on a tap without quitting, even when the release is never seen", async () => {
|
||||
// macOS suppresses the letter's keyUp while Cmd is held, so a tap may
|
||||
// produce no keyUp at all. Quit must still not fire.
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.preventDefault).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual(["down"]);
|
||||
|
||||
vi.advanceTimersByTime(QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
// The watchdog dismisses the hint once the press is clearly over.
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
});
|
||||
|
||||
it("quits once the shortcut auto-repeats past the hold duration", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS - 200);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
await harness.holdFor(400);
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
// Exactly one hint cycle for the whole hold.
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
});
|
||||
|
||||
it("does not quit when the hold stops before the duration", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.holdFor(500);
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
vi.advanceTimersByTime((QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS) * 2);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels the hold when the modifier is released first", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false }));
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
vi.advanceTimersByTime((QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS) * 2);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("quits immediately on a single press when disabled", async () => {
|
||||
const harness = makeHarness({ enabled: false });
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
// The hint is dismissed in case the quit gets cancelled downstream.
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
});
|
||||
|
||||
it("discards a stale isEnabled resolution from a superseded press", async () => {
|
||||
// Press #1's isEnabled is still pending when the user releases and
|
||||
// presses again; its late resolution must not act for press #2.
|
||||
const resolvers: Array<(enabled: boolean) => void> = [];
|
||||
const harness = makeHarness({
|
||||
isEnabled: () => new Promise((resolve) => resolvers.push(resolve)),
|
||||
});
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
// Outside the double-tap window, so the second press starts a new hold.
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_TAP_MS + 100);
|
||||
await harness.send(makeInput({}));
|
||||
expect(resolvers).toHaveLength(2);
|
||||
|
||||
// Press #1 resolves late with "disabled" — it must not quit press #2.
|
||||
resolvers[0]?.(false);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
|
||||
// Press #2 resolves enabled and completes a full hold.
|
||||
resolvers[1]?.(true);
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS + 200);
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("quits on a quick double tap, even when the first release was never seen", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_TAP_MS - 100);
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("treats two slow taps as separate presses", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_TAP_MS + 100);
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
expect(harness.notifications).toEqual(["down", "up", "down"]);
|
||||
});
|
||||
|
||||
it("cancels the hold when another key interrupts it", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.holdFor(500);
|
||||
// Shift pressed mid-hold breaks the gesture...
|
||||
await harness.send(makeInput({ shift: true }));
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
// ...so later repeats past the threshold must not quit.
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not count an interrupted press toward a double tap", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ shift: true }));
|
||||
// A fresh press right after the interruption starts a new hold, not a
|
||||
// double-tap quit.
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
expect(harness.notifications).toEqual(["down", "up", "down"]);
|
||||
});
|
||||
|
||||
it("ignores other shortcuts", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({ key: "w" }));
|
||||
await harness.send(makeInput({ shift: true }));
|
||||
await harness.send(makeInput({ meta: false }));
|
||||
expect(harness.preventDefault).not.toHaveBeenCalled();
|
||||
expect(harness.notifications).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses control on non-mac platforms", async () => {
|
||||
const harness = makeHarness({ platform: "linux" });
|
||||
await harness.send(makeInput({ meta: false, control: true }));
|
||||
expect(harness.preventDefault).toHaveBeenCalledTimes(1);
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS + 200, { meta: false, control: true });
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -1,148 +0,0 @@
|
||||
// @effect-diagnostics globalDate:off globalTimers:off -- Synchronous before-input-event handler; key events must be timed and the watchdog scheduled outside any Effect runtime.
|
||||
|
||||
// Chrome-style hold-to-quit. The quit accelerator is intercepted in
|
||||
// before-input-event (which runs before the native menu accelerator), and the
|
||||
// app only quits once the shortcut has been held for QUIT_HOLD_DURATION_MS.
|
||||
// A quick tap just shows the renderer's "Hold to Quit" hint, and a second tap
|
||||
// within QUIT_DOUBLE_TAP_MS quits immediately. Quitting from the application
|
||||
// menu itself is untouched and quits immediately.
|
||||
export const QUIT_HOLD_DURATION_MS = 1200;
|
||||
// A second quick tap of the shortcut is the user insisting: quit immediately.
|
||||
export const QUIT_DOUBLE_TAP_MS = 500;
|
||||
// "Still held" is proven by auto-repeat keydowns, not by the absence of a
|
||||
// release: macOS suppresses a letter's keyUp while the command key is down, so
|
||||
// a tap's release can go completely unseen and a release-based timer would
|
||||
// quit anyway. The press is treated as released once no key event has arrived
|
||||
// for QUIT_HOLD_RELEASE_GRACE_MS past the hold duration. Keyboards with
|
||||
// auto-repeat disabled cannot hold-to-quit and fall back to the menu's Quit.
|
||||
export const QUIT_HOLD_RELEASE_GRACE_MS = 600;
|
||||
|
||||
export type QuitHoldState = "down" | "up";
|
||||
|
||||
export interface QuitHoldKeyInput {
|
||||
readonly type: string;
|
||||
readonly key: string;
|
||||
readonly meta: boolean;
|
||||
readonly control: boolean;
|
||||
readonly alt: boolean;
|
||||
readonly shift: boolean;
|
||||
readonly isAutoRepeat: boolean;
|
||||
}
|
||||
|
||||
export interface QuitHoldOptions {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly isEnabled: () => Promise<boolean>;
|
||||
readonly notify: (state: QuitHoldState) => void;
|
||||
readonly quit: () => void;
|
||||
}
|
||||
|
||||
export function makeQuitHoldHandler(
|
||||
options: QuitHoldOptions,
|
||||
): (event: { preventDefault: () => void }, input: QuitHoldKeyInput) => void {
|
||||
const modifierKey = options.platform === "darwin" ? "meta" : "control";
|
||||
let watchdog: NodeJS.Timeout | undefined;
|
||||
let holding = false;
|
||||
// Set once isEnabled resolves true; auto-repeats may only quit when armed.
|
||||
let armed = false;
|
||||
let heldSince = 0;
|
||||
let lastPressAt = 0;
|
||||
// Incremented on every new press and every release/quit so a pending
|
||||
// isEnabled() resolution from a superseded press cannot arm (or quit for)
|
||||
// the current one.
|
||||
let generation = 0;
|
||||
|
||||
const clearWatchdog = () => {
|
||||
if (watchdog !== undefined) {
|
||||
clearTimeout(watchdog);
|
||||
watchdog = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const release = () => {
|
||||
if (!holding) return;
|
||||
generation += 1;
|
||||
holding = false;
|
||||
armed = false;
|
||||
clearWatchdog();
|
||||
options.notify("up");
|
||||
};
|
||||
|
||||
// Dismisses the overlay first: if the quit is cancelled downstream the
|
||||
// renderer must not be left with a stuck "Hold to Quit" hint.
|
||||
const quitNow = () => {
|
||||
release();
|
||||
options.quit();
|
||||
};
|
||||
|
||||
return (event, input) => {
|
||||
const key = input.key.toLowerCase();
|
||||
if (input.type === "keyUp") {
|
||||
if (key === "q" || key === modifierKey) release();
|
||||
return;
|
||||
}
|
||||
if (input.type !== "keyDown") return;
|
||||
|
||||
const modifierDown = options.platform === "darwin" ? input.meta : input.control;
|
||||
if (!modifierDown || input.alt || input.shift || key !== "q") {
|
||||
// Any other key (or an extra modifier) pressed mid-hold breaks the
|
||||
// gesture; without this the hold timer keeps running through the
|
||||
// interruption and the next qualifying repeat would quit early. The
|
||||
// interrupted press also stops counting toward a double tap — but only
|
||||
// here, not in release(), which runs mid-restart on an unseen-release
|
||||
// re-press and must not wipe that press's own tap timestamp.
|
||||
if (holding && !input.isAutoRepeat) {
|
||||
lastPressAt = 0;
|
||||
release();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
if (input.isAutoRepeat) {
|
||||
if (armed && Date.now() - heldSince >= QUIT_HOLD_DURATION_MS) {
|
||||
quitNow();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const previousPressAt = lastPressAt;
|
||||
lastPressAt = now;
|
||||
// A fresh keydown while "holding" means the key came back down after a
|
||||
// release macOS never delivered — so both branches below see real taps.
|
||||
if (previousPressAt !== 0 && now - previousPressAt <= QUIT_DOUBLE_TAP_MS) {
|
||||
quitNow();
|
||||
return;
|
||||
}
|
||||
if (holding) release();
|
||||
|
||||
generation += 1;
|
||||
const pressGeneration = generation;
|
||||
holding = true;
|
||||
heldSince = now;
|
||||
options.notify("down");
|
||||
void options.isEnabled().then(
|
||||
(enabled) => {
|
||||
if (generation !== pressGeneration) return;
|
||||
if (!enabled) {
|
||||
// Hold-to-quit disabled: a single press quits immediately.
|
||||
quitNow();
|
||||
return;
|
||||
}
|
||||
armed = true;
|
||||
// No auto-repeat by then means the key was released (possibly with a
|
||||
// suppressed keyUp) or repeat is disabled; either way, don't quit.
|
||||
watchdog = setTimeout(() => {
|
||||
watchdog = undefined;
|
||||
release();
|
||||
}, QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS);
|
||||
},
|
||||
// A failed settings read must never strand the quit request.
|
||||
() => {
|
||||
if (generation !== pressGeneration) return;
|
||||
quitNow();
|
||||
},
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -77,7 +77,6 @@ const backendConfigurationLayer = Layer.succeed(
|
||||
const netLayer = Layer.succeed(NetService.NetService, {
|
||||
canListenOnHost: () => Effect.succeed(true),
|
||||
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||
hasListenerOnHost: () => Effect.succeed(false),
|
||||
reserveLoopbackPort: () => Effect.succeed(41773),
|
||||
findAvailablePort: (preferred) => Effect.succeed(preferred),
|
||||
} satisfies NetService.NetService["Service"]);
|
||||
|
||||
@@ -229,18 +229,15 @@ const NODE_PTY_PROBE_SCRIPT = (
|
||||
printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
|
||||
printf 'resolvedPath:%s\\n' "$PATH"
|
||||
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
|
||||
// The WSL Node can't read inside app.asar, so confirm what the server needs is
|
||||
// unpacked on the real filesystem before reporting the backend healthy. Exit 3
|
||||
// marks this distinct from a node-pty prebuild problem so the caller can report
|
||||
// it accurately instead of letting the server crash on ERR_MODULE_NOT_FOUND at
|
||||
// launch (which, in wsl-only mode, would just fail to launch with no fallback).
|
||||
//
|
||||
// The sentinel must be a package the CLI bundle leaves external. It used to be
|
||||
// "effect", back when the bundle externalized its runtime deps and the whole
|
||||
// node_modules tree was unpacked. The bundle now inlines its JS dependencies,
|
||||
// so "effect" no longer exists on disk and only the native packages do —
|
||||
// resolving node-pty is what actually validates the unpacked tree.
|
||||
try { require.resolve("node-pty/package.json"); } catch (_e) { process.exit(3); }
|
||||
// The server bundle externalizes its deps to node_modules, and the WSL Node
|
||||
// can't read inside app.asar, so confirm those deps are unpacked on the real
|
||||
// filesystem before reporting the backend healthy. "effect" is the framework
|
||||
// every server module imports; resolving it validates the whole node_modules
|
||||
// tree. Exit 3 marks this distinct from a node-pty problem so the caller can
|
||||
// report it accurately instead of letting the server crash on
|
||||
// ERR_MODULE_NOT_FOUND at launch (which, in wsl-only mode, would just fail to
|
||||
// launch with no fallback).
|
||||
try { require.resolve("effect"); } catch (_e) { process.exit(3); }
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const pkgDir = path.dirname(require.resolve("node-pty/package.json"));
|
||||
@@ -465,17 +462,16 @@ const ensureNodePtyImpl = (
|
||||
} as const;
|
||||
}
|
||||
|
||||
// The packages the server bundle leaves external (node-pty and the other
|
||||
// native addons) couldn't be resolved on the WSL filesystem — a packaging
|
||||
// regression, since those must be unpacked from the asar. Fatal so wsl-only
|
||||
// mode falls back to Windows and dual mode surfaces the reason inline,
|
||||
// instead of the server crash-looping on ERR_MODULE_NOT_FOUND once it
|
||||
// actually launches.
|
||||
// Server dependencies (e.g. "effect") couldn't be resolved on the WSL
|
||||
// filesystem — a packaging regression, since the server bundle needs its
|
||||
// node_modules unpacked from the asar. Fatal so wsl-only mode falls back to
|
||||
// Windows and dual mode surfaces the reason inline, instead of the server
|
||||
// crash-looping on ERR_MODULE_NOT_FOUND once it actually launches.
|
||||
if (probe.exitCode === 3) {
|
||||
return {
|
||||
ok: false,
|
||||
reason:
|
||||
'WSL server dependencies could not be loaded (for example "node-pty"). The native packages the server needs are not unpacked where the WSL distro\'s Node can read them — this is a packaging problem with this build. Please report it.',
|
||||
"WSL server dependencies could not be loaded (for example \"effect\"). The server's bundled node_modules is not readable by the WSL distro's Node — this is a packaging problem with this build. Please report it.",
|
||||
fatal: true,
|
||||
} as const;
|
||||
}
|
||||
|
||||
@@ -1,323 +0,0 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopWslServerTree from "./DesktopWslServerTree.ts";
|
||||
|
||||
// The service reads packaged Windows roots through the (asar-aware, in
|
||||
// Electron) fs, so a plain directory named server.asar exercises the full
|
||||
// extraction path under plain Node.
|
||||
|
||||
const environmentLayer = (input: {
|
||||
readonly baseDir: string;
|
||||
readonly resourcesPath: string;
|
||||
readonly appVersion?: string;
|
||||
readonly isPackaged?: boolean;
|
||||
}) =>
|
||||
DesktopEnvironment.layer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
homeDirectory: input.baseDir,
|
||||
platform: "win32",
|
||||
processArch: "x64",
|
||||
appVersion: input.appVersion ?? "1.2.3",
|
||||
appPath: "/repo",
|
||||
isPackaged: input.isPackaged ?? true,
|
||||
resourcesPath: input.resourcesPath,
|
||||
runningUnderArm64Translation: false,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
DesktopConfig.layerTest({
|
||||
T3CODE_HOME: input.baseDir,
|
||||
T3CODE_MODE: "desktop",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const withTempDir = <A, E, R>(
|
||||
run: (tempDir: string) => Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<
|
||||
A,
|
||||
E | PlatformError.PlatformError,
|
||||
FileSystem.FileSystem | Exclude<R, Scope.Scope>
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-wsl-server-tree-test-",
|
||||
});
|
||||
return yield* run(tempDir);
|
||||
}).pipe(Effect.scoped);
|
||||
|
||||
const ensureWith = (input: {
|
||||
readonly baseDir: string;
|
||||
readonly resourcesPath: string;
|
||||
readonly appVersion?: string;
|
||||
readonly isPackaged?: boolean;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const tree = yield* DesktopWslServerTree.DesktopWslServerTree;
|
||||
return yield* tree.ensure;
|
||||
}).pipe(
|
||||
Effect.provide(DesktopWslServerTree.layer.pipe(Layer.provideMerge(environmentLayer(input)))),
|
||||
);
|
||||
|
||||
describe("DesktopWslServerTree", () => {
|
||||
it.effect("bounds entry work across an eight-way nested tree", () =>
|
||||
Effect.gen(function* () {
|
||||
const active = yield* Ref.make(0);
|
||||
const maxActive = yield* Ref.make(0);
|
||||
const visited = yield* Ref.make(0);
|
||||
|
||||
yield* DesktopWslServerTree.forEachBoundedTree([{ depth: 0, id: "root" }], (node) =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* Ref.updateAndGet(active, (count) => count + 1);
|
||||
yield* Ref.update(maxActive, (maximum) => Math.max(maximum, current));
|
||||
yield* Ref.update(visited, (count) => count + 1);
|
||||
}),
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
// Give every task in the current batch a chance to overlap.
|
||||
yield* Effect.yieldNow;
|
||||
if (node.depth === 4) return [];
|
||||
return Array.from({ length: 8 }, (_, index) => ({
|
||||
depth: node.depth + 1,
|
||||
id: `${node.id}.${String(index)}`,
|
||||
}));
|
||||
}),
|
||||
() => Ref.update(active, (count) => count - 1),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(yield* Ref.get(active), 0);
|
||||
assert.equal(yield* Ref.get(maxActive), 8);
|
||||
assert.equal(yield* Ref.get(visited), 4_681);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the server root unchanged when it is a plain directory (dev)", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: tempDir,
|
||||
isPackaged: false,
|
||||
});
|
||||
assert.isTrue(result.ok);
|
||||
assert.isFalse(result.ok && result.root.endsWith(".asar"));
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("extracts an archive root into a version-keyed state directory", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverRoot = path.join(tempDir, "resources", "server.asar");
|
||||
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(serverRoot, "apps/server/dist/bin.mjs"),
|
||||
"server-entry",
|
||||
);
|
||||
yield* fileSystem.makeDirectory(path.join(serverRoot, "node_modules/effect"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(serverRoot, "node_modules/effect/package.json"),
|
||||
"{}",
|
||||
);
|
||||
|
||||
const result = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
});
|
||||
|
||||
assert.isTrue(result.ok);
|
||||
const root = result.ok ? result.root : "";
|
||||
assert.include(root, path.join("wsl-server-tree", "1.2.3"));
|
||||
const entry = yield* fileSystem.readFileString(path.join(root, "apps/server/dist/bin.mjs"));
|
||||
assert.equal(entry, "server-entry");
|
||||
const dep = yield* fileSystem.exists(path.join(root, "node_modules/effect/package.json"));
|
||||
assert.isTrue(dep);
|
||||
const marker = yield* fileSystem.readFileString(
|
||||
path.join(root, "t3code-wsl-server-tree.json"),
|
||||
);
|
||||
assert.include(marker, '"version":"1.2.3"');
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("serializes concurrent extraction callers and publishes one complete tree", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const resourcesPath = path.join(tempDir, "resources");
|
||||
const serverRoot = path.join(resourcesPath, "server.asar");
|
||||
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(serverRoot, "apps/server/dist/bin.mjs"),
|
||||
"server-entry",
|
||||
);
|
||||
|
||||
const results = yield* Effect.gen(function* () {
|
||||
const tree = yield* DesktopWslServerTree.DesktopWslServerTree;
|
||||
return yield* Effect.all([tree.ensure, tree.ensure], { concurrency: "unbounded" });
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopWslServerTree.layer.pipe(
|
||||
Layer.provideMerge(environmentLayer({ baseDir: tempDir, resourcesPath })),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
assert.isTrue(results.every((result) => result.ok));
|
||||
const roots = results.flatMap((result) => (result.ok ? [result.root] : []));
|
||||
assert.lengthOf(new Set(roots), 1);
|
||||
assert.equal(
|
||||
yield* fileSystem.readFileString(path.join(roots[0] ?? "", "apps/server/dist/bin.mjs")),
|
||||
"server-entry",
|
||||
);
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reuses a completed extraction instead of copying again", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverRoot = path.join(tempDir, "resources", "server.asar");
|
||||
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "v1");
|
||||
|
||||
const first = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
});
|
||||
assert.isTrue(first.ok);
|
||||
|
||||
// Mutate the source; a reused tree must keep the first copy.
|
||||
yield* fileSystem.writeFileString(
|
||||
path.join(serverRoot, "apps/server/dist/bin.mjs"),
|
||||
"v2-should-not-appear",
|
||||
);
|
||||
const second = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
});
|
||||
assert.isTrue(second.ok);
|
||||
const root = second.ok ? second.root : "";
|
||||
const entry = yield* fileSystem.readFileString(path.join(root, "apps/server/dist/bin.mjs"));
|
||||
assert.equal(entry, "v1");
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("sweeps stale version directories and leftover partials after extraction", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverRoot = path.join(tempDir, "resources", "server.asar");
|
||||
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "x");
|
||||
|
||||
// T3CODE_HOME is set to tempDir, so the desktop state dir resolves to
|
||||
// <tempDir>/userdata (no .t3 segment).
|
||||
const treeRoot = path.join(tempDir, "userdata", "wsl-server-tree");
|
||||
yield* fileSystem.makeDirectory(path.join(treeRoot, "1.0.0"), { recursive: true });
|
||||
yield* fileSystem.makeDirectory(path.join(treeRoot, "1.2.3.partial"), { recursive: true });
|
||||
|
||||
const result = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
});
|
||||
assert.isTrue(result.ok);
|
||||
assert.isFalse(yield* fileSystem.exists(path.join(treeRoot, "1.0.0")));
|
||||
assert.isFalse(yield* fileSystem.exists(path.join(treeRoot, "1.2.3.partial")));
|
||||
assert.isTrue(yield* fileSystem.exists(path.join(treeRoot, "1.2.3")));
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("re-extracts when the app version changes", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const serverRoot = path.join(tempDir, "resources", "server.asar");
|
||||
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "old");
|
||||
|
||||
const first = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
appVersion: "1.2.3",
|
||||
});
|
||||
assert.isTrue(first.ok);
|
||||
|
||||
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "new");
|
||||
const second = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
appVersion: "1.2.4",
|
||||
});
|
||||
assert.isTrue(second.ok);
|
||||
const root = second.ok ? second.root : "";
|
||||
assert.include(root, "1.2.4");
|
||||
const entry = yield* fileSystem.readFileString(path.join(root, "apps/server/dist/bin.mjs"));
|
||||
assert.equal(entry, "new");
|
||||
// The previous version's tree is gone.
|
||||
const treeRoot = path.dirname(root);
|
||||
assert.isFalse(yield* fileSystem.exists(path.join(treeRoot, "1.2.3")));
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports a retryable failure when the archive cannot be read", () =>
|
||||
withTempDir((tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const result = yield* ensureWith({
|
||||
baseDir: tempDir,
|
||||
// resources dir exists but server.asar does not
|
||||
resourcesPath: path.join(tempDir, "resources"),
|
||||
});
|
||||
assert.isFalse(result.ok);
|
||||
if (!result.ok) {
|
||||
assert.include(result.reason, "could not be extracted");
|
||||
assert.isFalse(result.fatal);
|
||||
}
|
||||
const treeRoot = path.join(tempDir, "userdata", "wsl-server-tree");
|
||||
const leftovers = yield* fileSystem
|
||||
.readDirectory(treeRoot)
|
||||
.pipe(Effect.orElseSucceed(() => []));
|
||||
assert.deepStrictEqual(leftovers, []);
|
||||
}),
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -1,226 +0,0 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
|
||||
// Packaged Windows builds ship the server tree inside resources/server.asar
|
||||
// (see scripts/build-desktop-artifact.ts). The Windows primary reads it in
|
||||
// place through the asar-aware ELECTRON_RUN_AS_NODE runtime, but the WSL
|
||||
// backend launches plain `wsl.exe -- node`, which cannot read an asar
|
||||
// archive. This service materializes the archive into a real, version-keyed
|
||||
// directory the first time the WSL backend starts, and reuses it afterwards —
|
||||
// so only users who enable WSL ever pay for a loose copy of the server tree.
|
||||
//
|
||||
// Reading through Electron's patched fs also transparently returns the
|
||||
// contents of files that electron-builder/asar left in the server.asar.unpacked
|
||||
// sibling (native binaries), so a single walk of the archive yields the
|
||||
// complete tree.
|
||||
|
||||
export type WslServerTreeResult =
|
||||
| { readonly ok: true; readonly root: string }
|
||||
| { readonly ok: false; readonly reason: string; readonly fatal: boolean };
|
||||
|
||||
const MARKER_FILE_NAME = "t3code-wsl-server-tree.json";
|
||||
const COPY_CONCURRENCY = 8;
|
||||
|
||||
const Marker = Schema.Struct({ version: Schema.String });
|
||||
const decodeMarker = Schema.decodeUnknownEffect(Schema.fromJsonString(Marker));
|
||||
const encodeMarker = Schema.encodeEffect(Schema.fromJsonString(Marker));
|
||||
|
||||
export class DesktopWslServerTreeExtractError extends Schema.TaggedErrorClass<DesktopWslServerTreeExtractError>()(
|
||||
"DesktopWslServerTreeExtractError",
|
||||
{
|
||||
targetDir: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Failed to extract the WSL server tree to ${this.targetDir}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DesktopWslServerTree extends Context.Service<
|
||||
DesktopWslServerTree,
|
||||
{
|
||||
// Resolves the directory the WSL backend should treat as the app root
|
||||
// (the directory containing apps/server/dist and node_modules). In dev
|
||||
// the checkout already is that directory; packaged Windows builds extract
|
||||
// server.asar on first use.
|
||||
readonly ensure: Effect.Effect<WslServerTreeResult>;
|
||||
}
|
||||
>()("@t3tools/desktop/wsl/DesktopWslServerTree") {}
|
||||
|
||||
// Child scheduling stays here instead of inside `visit`, so nested directories
|
||||
// cannot create independent concurrency pools. The LIFO work list also keeps
|
||||
// traversal memory proportional to the remaining frontier rather than the
|
||||
// number of active fibers.
|
||||
export const forEachBoundedTree = <Node, E, R>(
|
||||
roots: ReadonlyArray<Node>,
|
||||
visit: (node: Node) => Effect.Effect<ReadonlyArray<Node>, E, R>,
|
||||
): Effect.Effect<void, E, R> =>
|
||||
Effect.gen(function* () {
|
||||
const pending = [...roots];
|
||||
while (pending.length > 0) {
|
||||
const batch = pending.splice(-COPY_CONCURRENCY);
|
||||
const children = yield* Effect.forEach(batch, visit, {
|
||||
concurrency: COPY_CONCURRENCY,
|
||||
});
|
||||
for (const entries of children) {
|
||||
pending.push(...entries);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
interface CopyTreeEntry {
|
||||
readonly sourcePath: string;
|
||||
readonly targetPath: string;
|
||||
}
|
||||
|
||||
// Copy using only operations supported by Electron's asar-patched fs. Symlinks
|
||||
// are not expected because the sidecar is installed with a hoisted, physical
|
||||
// layout; anything that is neither a file nor a directory is skipped.
|
||||
const copyTree = (
|
||||
fs: FileSystem.FileSystem,
|
||||
join: (first: string, ...rest: string[]) => string,
|
||||
from: string,
|
||||
to: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError> =>
|
||||
forEachBoundedTree<CopyTreeEntry, PlatformError.PlatformError, never>(
|
||||
[{ sourcePath: from, targetPath: to }],
|
||||
({ sourcePath, targetPath }) =>
|
||||
Effect.gen(function* () {
|
||||
const info = yield* fs.stat(sourcePath);
|
||||
if (info.type === "Directory") {
|
||||
yield* fs.makeDirectory(targetPath, { recursive: true });
|
||||
const entries = yield* fs.readDirectory(sourcePath);
|
||||
return entries.map((entry) => ({
|
||||
sourcePath: join(sourcePath, entry),
|
||||
targetPath: join(targetPath, entry),
|
||||
}));
|
||||
}
|
||||
if (info.type === "File") {
|
||||
// Read and write stay in the same bounded task, so at most eight file
|
||||
// buffers can be retained while their writes complete.
|
||||
const bytes = yield* fs.readFile(sourcePath);
|
||||
yield* fs.writeFile(targetPath, bytes);
|
||||
}
|
||||
return [];
|
||||
}),
|
||||
);
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const join = environment.path.join;
|
||||
|
||||
const serverRoot = environment.serverRoot;
|
||||
const needsExtraction = environment.isPackaged && environment.platform === "win32";
|
||||
const treeRoot = join(environment.stateDir, "wsl-server-tree");
|
||||
const version = environment.appVersion;
|
||||
const versionDir = join(treeRoot, version);
|
||||
|
||||
// Remove sibling trees left behind by previous app versions (and aborted
|
||||
// extractions). Best-effort: a locked file must not block the backend.
|
||||
const sweepStale = Effect.gen(function* () {
|
||||
const entries = yield* fs.readDirectory(treeRoot).pipe(Effect.orElseSucceed(() => []));
|
||||
yield* Effect.forEach(
|
||||
entries.filter((entry) => entry !== version),
|
||||
(entry) => fs.remove(join(treeRoot, entry), { recursive: true }).pipe(Effect.ignore),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
const markerMatches = Effect.gen(function* () {
|
||||
const raw = yield* fs.readFileString(join(versionDir, MARKER_FILE_NAME));
|
||||
const marker = yield* decodeMarker(raw);
|
||||
return marker.version === version;
|
||||
}).pipe(Effect.orElseSucceed(() => false));
|
||||
|
||||
const extract = Effect.gen(function* () {
|
||||
yield* Effect.log(`[wsl-server-tree] Extracting ${serverRoot} to ${versionDir}...`);
|
||||
yield* fs.makeDirectory(treeRoot, { recursive: true });
|
||||
// Keep the temporary tree beside the target so rename is atomic. Cleanup
|
||||
// is owned explicitly because a scoped temp-directory finalizer treats the
|
||||
// successful rename (and therefore missing original path) as an error.
|
||||
const partialDir = yield* fs.makeTempDirectory({
|
||||
directory: treeRoot,
|
||||
prefix: `.${version}.extract-`,
|
||||
});
|
||||
yield* Effect.gen(function* () {
|
||||
yield* copyTree(fs, join, serverRoot, partialDir);
|
||||
const markerJson = yield* encodeMarker({ version });
|
||||
yield* fs.writeFileString(join(partialDir, MARKER_FILE_NAME), `${markerJson}\n`);
|
||||
// The marker is written before the rename, so a directory named after
|
||||
// the version is complete by construction.
|
||||
yield* fs.remove(versionDir, { recursive: true }).pipe(Effect.ignore);
|
||||
yield* fs.rename(partialDir, versionDir);
|
||||
}).pipe(
|
||||
Effect.ensuring(fs.remove(partialDir, { recursive: true, force: true }).pipe(Effect.ignore)),
|
||||
);
|
||||
yield* Effect.log(`[wsl-server-tree] Extraction complete at ${versionDir}.`);
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new DesktopWslServerTreeExtractError({ targetDir: versionDir, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
// Serialize concurrent ensure calls (backend restarts can overlap): the
|
||||
// first caller extracts, later callers see the marker and reuse the tree.
|
||||
const gate = yield* Semaphore.make(1);
|
||||
|
||||
const ensure: Effect.Effect<WslServerTreeResult> = gate
|
||||
.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
if (!needsExtraction) {
|
||||
return { ok: true, root: serverRoot } as const;
|
||||
}
|
||||
if (yield* markerMatches) {
|
||||
yield* sweepStale;
|
||||
return { ok: true, root: versionDir } as const;
|
||||
}
|
||||
const result = yield* extract.pipe(
|
||||
Effect.map(() => ({ ok: true, root: versionDir }) as const),
|
||||
// Retryable: transient antivirus locks and slow disks are the common
|
||||
// causes, and the backend manager already bounds preflight retries.
|
||||
Effect.catch((error) =>
|
||||
Effect.succeed({
|
||||
ok: false,
|
||||
reason: `WSL server files could not be extracted to ${versionDir}: ${
|
||||
error.cause instanceof Error ? error.cause.message : String(error.cause)
|
||||
}`,
|
||||
fatal: false,
|
||||
} as const),
|
||||
),
|
||||
);
|
||||
if (result.ok) {
|
||||
yield* sweepStale;
|
||||
}
|
||||
return result;
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.withSpan("desktop.wslServerTree.ensure"));
|
||||
|
||||
return DesktopWslServerTree.of({ ensure });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopWslServerTree, make);
|
||||
|
||||
export interface DesktopWslServerTreeTestStub {
|
||||
readonly result?: WslServerTreeResult;
|
||||
}
|
||||
|
||||
export const layerTest = (stub: DesktopWslServerTreeTestStub = {}) =>
|
||||
Layer.effect(
|
||||
DesktopWslServerTree,
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
return DesktopWslServerTree.of({
|
||||
ensure: Effect.succeed(stub.result ?? { ok: true, root: environment.appRoot }),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,20 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { macArchFromGpuRenderer } from "./macArch";
|
||||
|
||||
describe("macArchFromGpuRenderer", () => {
|
||||
it("detects explicit Apple Silicon renderers", () => {
|
||||
expect(macArchFromGpuRenderer("Apple M4 Pro")).toBe("arm64");
|
||||
});
|
||||
|
||||
it("prefers an Intel GPU marker even when the renderer also mentions Apple", () => {
|
||||
expect(macArchFromGpuRenderer("ANGLE Metal Renderer: Apple, Intel Iris Plus Graphics")).toBe(
|
||||
"x64",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses x64 for ambiguous Safari and unavailable renderer values", () => {
|
||||
expect(macArchFromGpuRenderer("Apple GPU")).toBe("x64");
|
||||
expect(macArchFromGpuRenderer("")).toBe("x64");
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
const INTEL_GPU_PATTERN = /intel|amd|radeon|nvidia|geforce/i;
|
||||
const APPLE_SILICON_GPU_PATTERN = /\bapple\s+m\d/i;
|
||||
|
||||
export function macArchFromGpuRenderer(renderer: string): "arm64" | "x64" {
|
||||
if (INTEL_GPU_PATTERN.test(renderer)) {
|
||||
return "x64";
|
||||
}
|
||||
if (APPLE_SILICON_GPU_PATTERN.test(renderer)) {
|
||||
return "arm64";
|
||||
}
|
||||
|
||||
// Generic "Apple GPU" renderers are ambiguous on Safari. x64 is the safe
|
||||
// fallback because Apple Silicon can run it through Rosetta, while Intel
|
||||
// Macs cannot run an arm64 build.
|
||||
return "x64";
|
||||
}
|
||||
@@ -391,33 +391,14 @@ const mobileEndorsementRows = [
|
||||
|
||||
<script>
|
||||
import { fetchLatestRelease, RELEASES_URL, type ReleaseAsset } from "../lib/releases";
|
||||
import { macArchFromGpuRenderer } from "../lib/macArch";
|
||||
|
||||
type Platform = { os: "mac" | "win" | "linux"; label: string; arch?: string };
|
||||
|
||||
// navigator.userAgent reports "Intel Mac OS X" on both Intel and Apple Silicon
|
||||
// Macs, so probe the GPU renderer instead: Apple Silicon exposes an "Apple" GPU.
|
||||
function detectMacArch(): "arm64" | "x64" {
|
||||
try {
|
||||
const canvas = document.createElement("canvas");
|
||||
const gl = (canvas.getContext("webgl") ||
|
||||
canvas.getContext("experimental-webgl")) as WebGLRenderingContext | null;
|
||||
const debugInfo = gl?.getExtension("WEBGL_debug_renderer_info");
|
||||
if (gl && debugInfo) {
|
||||
const renderer = String(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) ?? "");
|
||||
return macArchFromGpuRenderer(renderer);
|
||||
}
|
||||
} catch {
|
||||
// fall through to the default below
|
||||
}
|
||||
return macArchFromGpuRenderer("");
|
||||
}
|
||||
|
||||
function detectPlatform(): Platform | null {
|
||||
const ua = navigator.userAgent;
|
||||
if (/Win/i.test(ua)) return { os: "win", label: "Download for Windows" };
|
||||
if (/Mac/i.test(ua)) {
|
||||
return { os: "mac", label: "Download for macOS", arch: detectMacArch() };
|
||||
return { os: "mac", label: "Download for macOS", arch: "arm64" };
|
||||
}
|
||||
if (/Linux/i.test(ua)) return { os: "linux", label: "Download for Linux" };
|
||||
return null;
|
||||
@@ -723,7 +704,7 @@ const mobileEndorsementRows = [
|
||||
height: 44px;
|
||||
}
|
||||
|
||||
/* Three above the headline, two beside the CTA — keeps the copy clear. */
|
||||
/* Three stacked on the left, two on the right — keeps the center CTA clear. */
|
||||
.hero-float-mark.hf-claude {
|
||||
top: 44px;
|
||||
left: 10px;
|
||||
@@ -731,8 +712,8 @@ const mobileEndorsementRows = [
|
||||
}
|
||||
|
||||
.hero-float-mark.hf-grok {
|
||||
top: 44px;
|
||||
left: calc(50% - 39px);
|
||||
top: 240px;
|
||||
left: 4px;
|
||||
right: auto;
|
||||
transform: rotate(-4deg);
|
||||
}
|
||||
@@ -760,8 +741,8 @@ const mobileEndorsementRows = [
|
||||
|
||||
@media (max-width: 340px) {
|
||||
.hero-float-mark.hf-grok {
|
||||
top: 57px;
|
||||
left: calc(50% - 26px);
|
||||
top: 220px;
|
||||
left: 0;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
border-radius: 14px;
|
||||
|
||||
@@ -4,10 +4,6 @@
|
||||
/* ─── Theme tokens ──────────────────────────────────────────────────── */
|
||||
@layer theme {
|
||||
:root {
|
||||
@variant android {
|
||||
--font-mono: "monospace";
|
||||
}
|
||||
|
||||
@variant light {
|
||||
/* Page backgrounds */
|
||||
--color-screen: #f2f2f7;
|
||||
|
||||
@@ -252,9 +252,6 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
|
||||
val textLength = editor.text?.length ?: 0
|
||||
val safeStart = start.coerceIn(0, textLength)
|
||||
val safeEnd = end.coerceIn(0, textLength)
|
||||
// Re-applying an unchanged selection resets the keyboard's suggestion
|
||||
// state, so a no-op assignment must be skipped.
|
||||
if (editor.selectionStart == safeStart && editor.selectionEnd == safeEnd) return
|
||||
editor.setSelection(safeStart, safeEnd)
|
||||
}
|
||||
|
||||
@@ -284,10 +281,6 @@ class T3ComposerEditorView(context: Context, appContext: AppContext) : ExpoView(
|
||||
)
|
||||
|
||||
private fun emitSelectionChange(start: Int, end: Int) {
|
||||
// Caret moves advance the revision counter like text edits do: a
|
||||
// controlled payload computed before this move is stale and must fail the
|
||||
// revision guard instead of yanking the caret back mid-typing.
|
||||
nativeEventCount += 1
|
||||
onComposerSelectionChange(
|
||||
mapOf(
|
||||
"value" to editor.text.toString(),
|
||||
|
||||
@@ -489,12 +489,6 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
|
||||
return
|
||||
}
|
||||
restoreBaseTypingAttributes()
|
||||
// UIKit moves the selection before textViewDidChange runs. Emitting here
|
||||
// would pair the post-edit text with a pre-edit revision counter, so let
|
||||
// the change event that follows carry both; only pure caret moves emit.
|
||||
guard self.textView.serializedText() == value else {
|
||||
return
|
||||
}
|
||||
emitSelection()
|
||||
}
|
||||
|
||||
@@ -780,12 +774,8 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
|
||||
}
|
||||
|
||||
private func emitSelection() {
|
||||
// Caret moves advance the revision counter like text edits do: a
|
||||
// controlled payload computed before this move is stale and must fail the
|
||||
// revision guard instead of yanking the caret back mid-typing.
|
||||
let currentValue = textView.serializedText()
|
||||
let selection = sourceSelection()
|
||||
nativeEventCount += 1
|
||||
onComposerSelectionChange([
|
||||
"value": currentValue,
|
||||
"selection": ["start": selection.start, "end": selection.end],
|
||||
@@ -827,16 +817,10 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro
|
||||
NSMaxRange(nextRange) <= textView.attributedText.length else {
|
||||
return
|
||||
}
|
||||
self.requestedSelection = nil
|
||||
// Programmatically assigning selectedRange resets the keyboard's
|
||||
// autocorrect and predictive-text context even when the range is
|
||||
// unchanged, so a no-op assignment must be skipped.
|
||||
guard !NSEqualRanges(nextRange, textView.selectedRange) else {
|
||||
return
|
||||
}
|
||||
isApplyingControlledValue = true
|
||||
textView.selectedRange = nextRange
|
||||
isApplyingControlledValue = false
|
||||
self.requestedSelection = nil
|
||||
}
|
||||
|
||||
private func updatePlaceholderVisibility() {
|
||||
|
||||
@@ -20,15 +20,12 @@ import {
|
||||
clearAgentAwarenessRegistrationRecord,
|
||||
loadAgentAwarenessRegistrationRecord,
|
||||
loadOrCreateAgentAwarenessDeviceId,
|
||||
loadPreferences,
|
||||
saveAgentAwarenessRegistrationRecord,
|
||||
} from "../../persistence/imperative";
|
||||
import type { Preferences } from "../../persistence/mobile-preferences";
|
||||
import { makeRelayDeviceRegistrationRequest, resolveApsEnvironment } from "./registrationPayload";
|
||||
import {
|
||||
AgentAwarenessOperationError,
|
||||
__resetAgentAwarenessRemoteRegistrationForTest,
|
||||
armAgentAwarenessLiveActivityForLocalWork,
|
||||
getAgentAwarenessRegistrationStatus,
|
||||
mergeAgentAwarenessRegistrationPreferences,
|
||||
refreshActiveLiveActivityRemoteRegistration,
|
||||
@@ -46,13 +43,6 @@ import * as Notifications from "expo-notifications";
|
||||
const secureStore = vi.hoisted(() => new Map<string, string>());
|
||||
const widgetMocks = vi.hoisted(() => ({
|
||||
getInstances: vi.fn(() => []),
|
||||
start: vi.fn(() => ({})),
|
||||
}));
|
||||
const environmentConfigsMock = vi.hoisted(() => ({
|
||||
configs: new Map<
|
||||
string,
|
||||
{ environment: { capabilities: { agentActivityPublishing?: boolean } } }
|
||||
>(),
|
||||
}));
|
||||
const backgroundRuntime = vi.hoisted(() => ({
|
||||
pending: [] as Array<{
|
||||
@@ -87,22 +77,9 @@ vi.mock("expo-widgets", () => ({
|
||||
vi.mock("../../widgets/AgentActivity", () => ({
|
||||
default: {
|
||||
getInstances: widgetMocks.getInstances,
|
||||
start: widgetMocks.start,
|
||||
},
|
||||
}));
|
||||
|
||||
// The state modules pull the whole connection stack (and native expo modules)
|
||||
// into the import graph; the arming gate only needs the configs map.
|
||||
vi.mock("../../state/atom-registry", () => ({
|
||||
appAtomRegistry: {
|
||||
get: () => environmentConfigsMock.configs,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../state/server", () => ({
|
||||
environmentServerConfigsAtom: Symbol("environmentServerConfigsAtom"),
|
||||
}));
|
||||
|
||||
vi.mock("expo-notifications", () => ({
|
||||
addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })),
|
||||
getDevicePushTokenAsync: vi.fn(() => Promise.resolve({ type: "ios", data: "apns-token" })),
|
||||
@@ -250,8 +227,6 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockResolvedValue("device-1");
|
||||
widgetMocks.getInstances.mockReset();
|
||||
widgetMocks.getInstances.mockReturnValue([]);
|
||||
widgetMocks.start.mockClear();
|
||||
environmentConfigsMock.configs.clear();
|
||||
});
|
||||
|
||||
it("preserves disabled Live Activity preferences in relay registrations", () => {
|
||||
@@ -881,55 +856,4 @@ describe("makeRelayDeviceRegistrationRequest", () => {
|
||||
}).pipe(Effect.provide(relayTestLayer));
|
||||
},
|
||||
);
|
||||
|
||||
it("skips the Live Activity seed when the environment reports publishing disabled", async () => {
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
vi.mocked(loadPreferences).mockResolvedValueOnce({
|
||||
liveActivitiesEnabled: true,
|
||||
} as Preferences);
|
||||
environmentConfigsMock.configs.set("env-1", {
|
||||
environment: { capabilities: { agentActivityPublishing: false } },
|
||||
});
|
||||
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
environmentId: "env-1" as EnvironmentId,
|
||||
threadTitle: "Fix the flaky test",
|
||||
projectTitle: "t3code",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
expect(widgetMocks.start).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("seeds the Live Activity for publishing and pre-capability environments", async () => {
|
||||
setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"));
|
||||
environmentConfigsMock.configs.set("env-publishing", {
|
||||
environment: { capabilities: { agentActivityPublishing: true } },
|
||||
});
|
||||
|
||||
vi.mocked(loadPreferences).mockResolvedValueOnce({
|
||||
liveActivitiesEnabled: true,
|
||||
} as Preferences);
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
environmentId: "env-publishing" as EnvironmentId,
|
||||
threadTitle: "Fix the flaky test",
|
||||
projectTitle: "t3code",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(widgetMocks.start).toHaveBeenCalledTimes(1);
|
||||
|
||||
// An environment without the capability may run an older server that
|
||||
// still publishes; only an explicit false skips the seed.
|
||||
widgetMocks.start.mockClear();
|
||||
vi.mocked(loadPreferences).mockResolvedValueOnce({
|
||||
liveActivitiesEnabled: true,
|
||||
} as Preferences);
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
environmentId: "env-pre-capability" as EnvironmentId,
|
||||
threadTitle: "Fix the flaky test",
|
||||
projectTitle: "t3code",
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(widgetMocks.start).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -20,8 +20,6 @@ import {
|
||||
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { runtime } from "../../lib/runtime";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import type { Preferences } from "../../persistence/mobile-preferences";
|
||||
import {
|
||||
clearAgentAwarenessRegistrationRecord,
|
||||
@@ -450,38 +448,18 @@ function unregisterDeviceWithRelay(input: {
|
||||
});
|
||||
}
|
||||
|
||||
// The environment descriptor advertises whether agent-activity publishes
|
||||
// currently leave that server (`capabilities.agentActivityPublishing`). Only
|
||||
// an explicit false skips the seed card: older servers omit the capability
|
||||
// but may still publish.
|
||||
function environmentPublishesAgentActivity(environmentId: EnvironmentId): boolean {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.agentActivityPublishing !== false
|
||||
);
|
||||
}
|
||||
|
||||
// Arms the lock-screen card the moment the user starts agent work from this
|
||||
// phone, while the app is still foregrounded and the fresh activity's token
|
||||
// can be registered immediately. The seeded row is a best-effort placeholder;
|
||||
// the relay's registration replay repaints it with the authoritative
|
||||
// aggregate within seconds. No-ops when a card is already armed, and skips
|
||||
// environments that report publishing disabled — the seed would sit on
|
||||
// "Connecting" forever with no update ever arriving to repaint or end it.
|
||||
// aggregate within seconds. No-ops when a card is already armed.
|
||||
export function armAgentAwarenessLiveActivityForLocalWork(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadTitle: string;
|
||||
readonly projectTitle: string;
|
||||
}): void {
|
||||
if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) {
|
||||
return;
|
||||
}
|
||||
if (!environmentPublishesAgentActivity(input.environmentId)) {
|
||||
logRegistrationDebug("live activity arming skipped; environment does not publish", {
|
||||
environmentId: input.environmentId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
void loadPreferences()
|
||||
.catch(() => null)
|
||||
.then((preferences) => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/Stac
|
||||
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Alert, Linking, Platform, ScrollView, View } from "react-native";
|
||||
import { Alert, Platform, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
@@ -95,21 +95,9 @@ export function ConnectionsNewRouteScreen({
|
||||
return;
|
||||
}
|
||||
|
||||
if (permission.canAskAgain) {
|
||||
Alert.alert(
|
||||
"Camera access needed",
|
||||
"Allow camera access to scan an environment pairing QR code.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
Alert.alert(
|
||||
"Camera access needed",
|
||||
"Camera access was denied for this app. Open Settings to enable it.",
|
||||
[
|
||||
{ text: "Cancel", style: "cancel" },
|
||||
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
|
||||
],
|
||||
"Allow camera access to scan an environment pairing QR code.",
|
||||
);
|
||||
}, [cameraPermission?.granted, requestCameraPermission]);
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import { AppText as Text } from "../../components/AppText";
|
||||
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import {
|
||||
buildFileTree,
|
||||
@@ -124,7 +123,7 @@ export function FileTreeBrowser(props: {
|
||||
const insets = useSafeAreaInsets();
|
||||
// Native transparent-header height ≈ safe-area top + nav bar (~44). Matches the
|
||||
// observed adjustedContentInset bottom (~102) seen in the native trace.
|
||||
const headerInset = NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + IOS_NAV_BAR_HEIGHT : 0;
|
||||
const headerInset = NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 44 : 0;
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
const { onPreviewFile, onSelectFile, selectedPath: controlledSelectedPath } = props;
|
||||
const controlledSelectedPathRef = useRef(controlledSelectedPath);
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useSavedRemoteConnections } from "../../state/use-remote-environment-re
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail";
|
||||
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { checkForAppUpdateOnLaunch, startAppUpdateForegroundRecheck } from "../updates/app-updates";
|
||||
import { checkForAppUpdateOnLaunch } from "../updates/app-updates";
|
||||
import { AndroidHomeFabLayout } from "./AndroidHomeFab";
|
||||
import { HomeScreen } from "./HomeScreen";
|
||||
import { HomeHeader } from "./HomeHeader";
|
||||
@@ -34,7 +34,6 @@ export function HomeRouteScreen() {
|
||||
|
||||
useEffect(() => {
|
||||
void checkForAppUpdateOnLaunch();
|
||||
startAppUpdateForegroundRecheck();
|
||||
}, []);
|
||||
|
||||
const {
|
||||
|
||||
@@ -6,7 +6,6 @@ type AddProjectDestinationRouteParams = {
|
||||
readonly source?: string | string[];
|
||||
readonly remoteUrl?: string | string[];
|
||||
readonly repositoryTitle?: string | string[];
|
||||
readonly repositoryName?: string | string[];
|
||||
};
|
||||
|
||||
export function AddProjectDestinationRoute({
|
||||
|
||||
@@ -7,9 +7,6 @@ import {
|
||||
canCreateProjectInEnvironment,
|
||||
findExistingAddProject,
|
||||
getAddProjectInitialQuery,
|
||||
getCloneDestinationBrowsePath,
|
||||
getCloneDestinationPath,
|
||||
getCloneDirectoryName,
|
||||
resolveAddProjectPath,
|
||||
sortAddProjectProviderSources,
|
||||
type AddProjectRemoteSource,
|
||||
@@ -26,8 +23,8 @@ import {
|
||||
} from "@t3tools/client-runtime/state/filesystem";
|
||||
import {
|
||||
appendBrowsePathSegment,
|
||||
ensureBrowseDirectoryPath,
|
||||
inferProjectTitleFromPath,
|
||||
isWindowsPlatform,
|
||||
} from "@t3tools/client-runtime/state/projects";
|
||||
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
|
||||
@@ -239,18 +236,11 @@ function ProjectPathInput(props: {
|
||||
);
|
||||
}
|
||||
|
||||
// `pinnedDirectoryName` is the repository folder the clone destination keeps
|
||||
// appended to whatever folder the user browses to. The plain add-project flow
|
||||
// passes nothing, so it keeps proposing the browsed folder itself.
|
||||
function useBrowsePathInput(environment: EnvironmentOption | null, pinnedDirectoryName = "") {
|
||||
function useBrowsePathInput(environment: EnvironmentOption | null) {
|
||||
const environmentId = environment?.environmentId ?? null;
|
||||
const environmentBaseDirectory = environment?.baseDirectory ?? null;
|
||||
const clonePathCaseSensitive = !isWindowsPlatform(environment?.platform ?? "");
|
||||
const [pathInput, commitPathInput] = useState(() =>
|
||||
getCloneDestinationPath(
|
||||
getAddProjectInitialQuery(environmentBaseDirectory),
|
||||
pinnedDirectoryName,
|
||||
),
|
||||
getAddProjectInitialQuery(environmentBaseDirectory),
|
||||
);
|
||||
const previousEnvironmentIdRef = useRef(environmentId);
|
||||
const environmentRuntime = useRemoteEnvironmentRuntime(environmentId);
|
||||
@@ -269,60 +259,33 @@ function useBrowsePathInput(environment: EnvironmentOption | null, pinnedDirecto
|
||||
[browseNavigation],
|
||||
);
|
||||
const navigateToBrowsePath = useCallback(
|
||||
async (input: {
|
||||
readonly browseDirectoryPath: string;
|
||||
readonly selectedDirectoryName?: string;
|
||||
}) => {
|
||||
const selectedDirectoryPath = input.selectedDirectoryName
|
||||
? appendBrowsePathSegment(input.browseDirectoryPath, input.selectedDirectoryName)
|
||||
: input.browseDirectoryPath;
|
||||
const nextPathInput =
|
||||
pinnedDirectoryName && input.selectedDirectoryName
|
||||
? getCloneDestinationBrowsePath({
|
||||
browseDirectoryPath: input.browseDirectoryPath,
|
||||
selectedDirectoryName: input.selectedDirectoryName,
|
||||
cloneDirectoryName: pinnedDirectoryName,
|
||||
caseSensitive: clonePathCaseSensitive,
|
||||
})
|
||||
: getCloneDestinationPath(selectedDirectoryPath, pinnedDirectoryName);
|
||||
async (path: string) => {
|
||||
setIsBrowseNavigating(true);
|
||||
const committed = await browseNavigation.run(
|
||||
async () => {
|
||||
if (environment && canPreloadBrowsePath(environmentRuntime?.connectionState)) {
|
||||
await loadBrowsePath({
|
||||
environmentId: environment.environmentId,
|
||||
input: { partialPath: selectedDirectoryPath },
|
||||
input: { partialPath: path },
|
||||
});
|
||||
}
|
||||
},
|
||||
() => commitPathInput(nextPathInput),
|
||||
() => commitPathInput(path),
|
||||
);
|
||||
if (committed) {
|
||||
setIsBrowseNavigating(false);
|
||||
}
|
||||
return committed;
|
||||
},
|
||||
[
|
||||
browseNavigation,
|
||||
clonePathCaseSensitive,
|
||||
environment,
|
||||
environmentRuntime?.connectionState,
|
||||
loadBrowsePath,
|
||||
pinnedDirectoryName,
|
||||
],
|
||||
[browseNavigation, environment, environmentRuntime?.connectionState, loadBrowsePath],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (environmentId !== null && environmentId !== previousEnvironmentIdRef.current) {
|
||||
previousEnvironmentIdRef.current = environmentId;
|
||||
setPathInput(
|
||||
getCloneDestinationPath(
|
||||
getAddProjectInitialQuery(environmentBaseDirectory),
|
||||
pinnedDirectoryName,
|
||||
),
|
||||
);
|
||||
setPathInput(getAddProjectInitialQuery(environmentBaseDirectory));
|
||||
}
|
||||
}, [environmentBaseDirectory, environmentId, pinnedDirectoryName, setPathInput]);
|
||||
}, [environmentBaseDirectory, environmentId, setPathInput]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
@@ -669,7 +632,6 @@ export function AddProjectRepositoryScreen(props: {
|
||||
source,
|
||||
remoteUrl,
|
||||
repositoryTitle: remoteUrl,
|
||||
repositoryName: getCloneDirectoryName(remoteUrl),
|
||||
}),
|
||||
);
|
||||
setIsSubmitting(false);
|
||||
@@ -693,7 +655,6 @@ export function AddProjectRepositoryScreen(props: {
|
||||
source,
|
||||
remoteUrl: repository.sshUrl,
|
||||
repositoryTitle: repository.nameWithOwner,
|
||||
repositoryName: getCloneDirectoryName(repository.nameWithOwner),
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -737,11 +698,7 @@ function FolderBrowser(props: {
|
||||
readonly environment: EnvironmentOption;
|
||||
readonly pathInput: string;
|
||||
readonly setPathInput: (path: string) => void;
|
||||
readonly navigateToBrowsePath: (input: {
|
||||
readonly browseDirectoryPath: string;
|
||||
readonly selectedDirectoryName?: string;
|
||||
}) => Promise<boolean>;
|
||||
readonly pinnedDirectoryName?: string;
|
||||
readonly navigateToBrowsePath: (path: string) => Promise<boolean>;
|
||||
}) {
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
const browsePath = useMemo(
|
||||
@@ -760,16 +717,9 @@ function FolderBrowser(props: {
|
||||
input: browseInput,
|
||||
}),
|
||||
);
|
||||
// A pinned repository folder does not exist yet, so filtering the listing by
|
||||
// it would empty the folder picker. Anything the user typed still filters.
|
||||
const pinnedDirectoryName = props.pinnedDirectoryName ?? "";
|
||||
const pinnedDirectoryMatches = isWindowsPlatform(props.environment.platform)
|
||||
? browsePath.filterQuery.toLowerCase() === pinnedDirectoryName.toLowerCase()
|
||||
: browsePath.filterQuery === pinnedDirectoryName;
|
||||
const browseFilterQuery = pinnedDirectoryMatches ? "" : browsePath.filterQuery;
|
||||
const { visibleEntries: visibleBrowseEntries } = useMemo(
|
||||
() => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browseFilterQuery),
|
||||
[browseFilterQuery, browseState.data?.entries],
|
||||
() => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browsePath.filterQuery),
|
||||
[browsePath.filterQuery, browseState.data?.entries],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -797,9 +747,7 @@ function FolderBrowser(props: {
|
||||
right={null}
|
||||
onPress={() => {
|
||||
if (browsePath.parentPath) {
|
||||
void props.navigateToBrowsePath({
|
||||
browseDirectoryPath: browsePath.parentPath,
|
||||
});
|
||||
void props.navigateToBrowsePath(browsePath.parentPath);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@@ -812,10 +760,11 @@ function FolderBrowser(props: {
|
||||
isFirst={index === 0 && !browsePath.canBrowseUp}
|
||||
right={null}
|
||||
onPress={() => {
|
||||
void props.navigateToBrowsePath({
|
||||
browseDirectoryPath: browsePath.directoryPath,
|
||||
selectedDirectoryName: entry.name,
|
||||
});
|
||||
const nextPath =
|
||||
browsePath.directoryPath.length > 0
|
||||
? appendBrowsePathSegment(browsePath.directoryPath, entry.name)
|
||||
: ensureBrowseDirectoryPath(entry.fullPath);
|
||||
void props.navigateToBrowsePath(nextPath);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
@@ -887,7 +836,6 @@ export function AddProjectDestinationScreen(props: {
|
||||
readonly environmentId?: string | string[];
|
||||
readonly remoteUrl?: string | string[];
|
||||
readonly repositoryTitle?: string | string[];
|
||||
readonly repositoryName?: string | string[];
|
||||
}) {
|
||||
const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
|
||||
reportFailure: false,
|
||||
@@ -896,15 +844,8 @@ export function AddProjectDestinationScreen(props: {
|
||||
const createProject = useCreateProject(environment);
|
||||
const remoteUrl = stringParam(props.remoteUrl);
|
||||
const repositoryTitle = stringParam(props.repositoryTitle);
|
||||
// A lookup derives this from "owner/repo", a pasted clone URL from its own
|
||||
// last segment. Older links without the param keep the browsed folder.
|
||||
// Trim once here: the path input and the folder-list filter must compare the
|
||||
// same value, or a deep link with a padded param empties the folder picker.
|
||||
const repositoryName = stringParam(props.repositoryName)?.trim() ?? "";
|
||||
const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput(
|
||||
environment,
|
||||
repositoryName,
|
||||
);
|
||||
const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
|
||||
useBrowsePathInput(environment);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -977,7 +918,6 @@ export function AddProjectDestinationScreen(props: {
|
||||
navigateToBrowsePath={navigateToBrowsePath}
|
||||
pathInput={pathInput}
|
||||
setPathInput={setPathInput}
|
||||
pinnedDirectoryName={repositoryName}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -39,7 +39,6 @@ import { environmentCatalog } from "../../connection/catalog";
|
||||
import { useEnvironmentPresentation } from "../../state/presentation";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { useThreadDraftForThread } from "../../state/use-thread-composer-state";
|
||||
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
|
||||
import {
|
||||
@@ -278,11 +277,9 @@ function ReviewFileNavigator({
|
||||
// The nested native header is translucent; start the list below it so
|
||||
// the scroll-edge effect can sample the content (same treatment as
|
||||
// FileTreeBrowser in the Files pane).
|
||||
paddingTop: Platform.OS === "ios" ? insets.top + IOS_NAV_BAR_HEIGHT + 8 : 8,
|
||||
paddingTop: Platform.OS === "ios" ? insets.top + 44 + 8 : 8,
|
||||
}}
|
||||
scrollIndicatorInsets={
|
||||
Platform.OS === "ios" ? { top: insets.top + IOS_NAV_BAR_HEIGHT } : undefined
|
||||
}
|
||||
scrollIndicatorInsets={Platform.OS === "ios" ? { top: insets.top + 44 } : undefined}
|
||||
renderItem={renderFile}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useAuth } from "@clerk/expo";
|
||||
import { AuthView, UserProfileView } from "@clerk/expo/native";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
|
||||
import { useCallback, useLayoutEffect } from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
@@ -25,21 +25,11 @@ function ConfiguredSettingsAuthRouteScreen() {
|
||||
() => navigation.dispatch(StackActions.popTo("SettingsContent")),
|
||||
[navigation],
|
||||
);
|
||||
const hasBeenSignedIn = useRef(isSignedIn);
|
||||
if (isSignedIn) {
|
||||
hasBeenSignedIn.current = true;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (hasBeenSignedIn.current && isLoaded && isSignedIn === false) {
|
||||
navigation.dispatch(StackActions.popTo("SettingsContent"));
|
||||
}
|
||||
}, [isLoaded, isSignedIn, navigation]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
hasBeenSignedIn.current ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} onHostBack={handleHostBack} />
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
|
||||
|
||||
describe("resolveAgentAwarenessPlatformPresentation", () => {
|
||||
it("explains that agent awareness settings are unavailable on Android", () => {
|
||||
expect(resolveAgentAwarenessPlatformPresentation("android")).toEqual({
|
||||
supported: false,
|
||||
subtitle: "iOS only",
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves supported iOS settings unchanged", () => {
|
||||
expect(resolveAgentAwarenessPlatformPresentation("ios")).toEqual({
|
||||
supported: true,
|
||||
subtitle: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
export function resolveAgentAwarenessPlatformPresentation(platform: string): {
|
||||
readonly supported: boolean;
|
||||
readonly subtitle: string | undefined;
|
||||
} {
|
||||
return platform === "ios"
|
||||
? { supported: true, subtitle: undefined }
|
||||
: { supported: false, subtitle: "iOS only" };
|
||||
}
|
||||
@@ -46,7 +46,6 @@ import { useSavedRemoteConnections } from "../../state/use-remote-environment-re
|
||||
import { SettingsRow } from "./components/SettingsRow";
|
||||
import { SettingsSection } from "./components/SettingsSection";
|
||||
import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
|
||||
import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
|
||||
|
||||
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
|
||||
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
|
||||
@@ -145,7 +144,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
|
||||
const agentAwarenessPlatform = resolveAgentAwarenessPlatformPresentation(Platform.OS);
|
||||
const insets = useSafeAreaInsets();
|
||||
const navigation = useNavigation();
|
||||
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
@@ -475,12 +473,10 @@ function ConfiguredSettingsRouteScreen() {
|
||||
icon="bell.badge"
|
||||
label="Device Notifications"
|
||||
disabled={
|
||||
!agentAwarenessPlatform.supported ||
|
||||
!agentAwarenessPushAvailable ||
|
||||
notificationStatus === "checking" ||
|
||||
notificationStatus === "unsupported"
|
||||
}
|
||||
subtitle={agentAwarenessPlatform.subtitle}
|
||||
// Only reads as on when this device is actually registered with the
|
||||
// relay; otherwise notifications cannot be delivered regardless of
|
||||
// the local iOS permission.
|
||||
@@ -491,7 +487,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
/>
|
||||
<SettingsSwitchRow
|
||||
disabled={
|
||||
!agentAwarenessPlatform.supported ||
|
||||
!agentAwarenessPushAvailable ||
|
||||
!isLoaded ||
|
||||
liveActivityStatus === "checking" ||
|
||||
@@ -499,7 +494,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
}
|
||||
icon="bolt.circle"
|
||||
label="Live Activity Updates"
|
||||
subtitle={agentAwarenessPlatform.subtitle}
|
||||
// Same gate: a saved preference is meaningless until the device
|
||||
// registration the relay needs to push updates has succeeded.
|
||||
value={
|
||||
@@ -614,10 +608,7 @@ function AppSettingsSection() {
|
||||
if (updateInFlight.current) return;
|
||||
updateInFlight.current = true;
|
||||
try {
|
||||
// The user asked for this restart by tapping the version row, so it may
|
||||
// apply immediately instead of prompting.
|
||||
await runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
onFailure: (message) => Alert.alert("Update failed", message),
|
||||
onStateChange: setUpdateState,
|
||||
});
|
||||
@@ -640,15 +631,11 @@ function AppSettingsSection() {
|
||||
? "Checking…"
|
||||
: updateState === "downloading"
|
||||
? "Downloading…"
|
||||
: // "ready" appears only when this check joined an in-flight background-mode
|
||||
// check; that download installs at the next backgrounding.
|
||||
updateState === "ready"
|
||||
? "Update ready"
|
||||
: updateState === "restarting"
|
||||
? "Restarting…"
|
||||
: updateState === "current"
|
||||
? "Up to date"
|
||||
: null;
|
||||
: updateState === "restarting"
|
||||
? "Restarting…"
|
||||
: updateState === "current"
|
||||
? "Up to date"
|
||||
: null;
|
||||
|
||||
const versionRow = (
|
||||
<View className="flex-row items-center gap-4 p-4">
|
||||
|
||||
@@ -11,7 +11,6 @@ export function SettingsSwitchRow(props: {
|
||||
readonly disabled?: boolean;
|
||||
readonly icon: SymbolName;
|
||||
readonly label: string;
|
||||
readonly subtitle?: string;
|
||||
readonly value: boolean;
|
||||
readonly onValueChange: (value: boolean) => void;
|
||||
}) {
|
||||
@@ -28,12 +27,7 @@ export function SettingsSwitchRow(props: {
|
||||
}
|
||||
>
|
||||
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-lg text-foreground">{props.label}</Text>
|
||||
{props.subtitle ? (
|
||||
<Text className="text-sm text-foreground-muted">{props.subtitle}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
<Text className="flex-1 text-lg text-foreground">{props.label}</Text>
|
||||
<Switch
|
||||
disabled={props.disabled}
|
||||
ios_backgroundColor={track}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
isProviderSendTurnSupportedImageMimeType,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -163,13 +162,6 @@ export async function buildIncomingShareDraft(input: {
|
||||
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
|
||||
continue;
|
||||
}
|
||||
if (!isProviderSendTurnSupportedImageMimeType(mimeType)) {
|
||||
warnings.push(
|
||||
`'${resolved?.originalName ?? fallbackName(uri, index, mimeType)}' is not a supported image type.`,
|
||||
);
|
||||
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
resolved?.contentSize !== null &&
|
||||
resolved?.contentSize !== undefined &&
|
||||
|
||||
@@ -7,13 +7,11 @@ import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanim
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { APP_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { GitActionProgress } from "../../state/use-vcs-action-state";
|
||||
|
||||
const OVERLAY_LAYOUT_TRANSITION = LinearTransition.duration(220);
|
||||
const OVERLAY_TOP_GAP = 8;
|
||||
const AnimatedLiquidGlassView = Animated.createAnimatedComponent(LiquidGlassView);
|
||||
|
||||
export function GitActionProgressOverlay(props: {
|
||||
@@ -54,7 +52,7 @@ export function GitActionProgressOverlay(props: {
|
||||
entering={isLiquidGlassSupported ? undefined : FadeIn.duration(200)}
|
||||
exiting={FadeOut.duration(150)}
|
||||
className="absolute inset-x-3 z-[100]"
|
||||
style={{ top: insets.top + APP_BAR_HEIGHT + OVERLAY_TOP_GAP }}
|
||||
style={{ top: insets.top + 48 }}
|
||||
pointerEvents="box-none"
|
||||
>
|
||||
<Pressable onPress={handlePress}>
|
||||
|
||||
@@ -56,7 +56,6 @@ import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/re
|
||||
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
|
||||
import { useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
import { resolveDraftProjectSelection } from "./new-task-project-selection";
|
||||
import {
|
||||
@@ -584,17 +583,11 @@ export function NewTaskDraftScreen(props: {
|
||||
flow.environments.find(
|
||||
(environment) => environment.environmentId === flow.selectedEnvironmentId,
|
||||
)?.environmentLabel ?? "Environment";
|
||||
const availableCurrentBranchName =
|
||||
const currentBranchName =
|
||||
flow.availableBranches.find((branch) => branch.current)?.name ??
|
||||
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
const selectedBranchName = resolveProjectThreadCreationBranch({
|
||||
workspaceMode: flow.workspaceMode,
|
||||
selectedBranch:
|
||||
flow.selectedBranchName ??
|
||||
(flow.workspaceMode === "worktree" ? availableCurrentBranchName : null),
|
||||
currentCheckoutBranch: flow.currentCheckoutBranchName,
|
||||
});
|
||||
const selectedBranchName = flow.selectedBranchName ?? currentBranchName;
|
||||
const selectedBranchLabel = resolveNewTaskBranchLabel({
|
||||
branchName: selectedBranchName,
|
||||
startFromOrigin: flow.startFromOrigin,
|
||||
@@ -716,20 +709,14 @@ export function NewTaskDraftScreen(props: {
|
||||
// -only Activity start. If creation fails, the token registration's replay
|
||||
// finds no work and ends the card within seconds.
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
environmentId: selectedProject.environmentId,
|
||||
threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
|
||||
projectTitle: selectedProject.title,
|
||||
});
|
||||
const creationBranch = resolveProjectThreadCreationBranch({
|
||||
workspaceMode,
|
||||
selectedBranch: selectedBranchName,
|
||||
currentCheckoutBranch: flow.currentCheckoutBranchName,
|
||||
});
|
||||
const result = await createProjectThread({
|
||||
project: selectedProject,
|
||||
modelSelection,
|
||||
envMode: workspaceMode,
|
||||
branch: creationBranch,
|
||||
branch: selectedBranchName,
|
||||
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
|
||||
startFromOrigin,
|
||||
runtimeMode,
|
||||
|
||||
@@ -105,6 +105,7 @@ export interface ThreadComposerProps {
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
readonly serverConfig: T3ServerConfig | null;
|
||||
readonly queueCount: number;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectCwd: string | null;
|
||||
readonly editorRef?: RefObject<ComposerEditorHandle | null>;
|
||||
@@ -326,7 +327,9 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
props.selectedThread.session?.status === "starting";
|
||||
|
||||
const sendLabel =
|
||||
props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send";
|
||||
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
|
||||
? "Queue"
|
||||
: "Send";
|
||||
const currentModelSelection = props.selectedThread.modelSelection;
|
||||
const currentRuntimeMode = props.selectedThread.runtimeMode;
|
||||
const connectionStatus = composerConnectionStatus({
|
||||
@@ -538,7 +541,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
// after the send so its preference read and native Activity start don't
|
||||
// contend with the queued-message feedback on the tap frame.
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
environmentId: props.environmentId,
|
||||
threadTitle: props.selectedThread.title,
|
||||
projectTitle: props.environmentLabel ?? "T3 Code",
|
||||
});
|
||||
|
||||
@@ -57,7 +57,6 @@ import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
|
||||
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import type {
|
||||
PendingApproval,
|
||||
@@ -101,6 +100,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly threadSyncStatus?: EnvironmentThreadStatus;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
readonly threadCwd: string | null;
|
||||
@@ -249,7 +249,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
}
|
||||
}, []);
|
||||
const windowHeight = useWindowDimensions().height;
|
||||
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + IOS_NAV_BAR_HEIGHT;
|
||||
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const composerEditorRef = useRef<ComposerEditorHandle>(null);
|
||||
@@ -726,6 +726,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
selectedThread={props.selectedThread}
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Image,
|
||||
Linking,
|
||||
Platform,
|
||||
type LayoutChangeEvent,
|
||||
type NativeScrollEvent,
|
||||
@@ -46,11 +47,9 @@ import ImageViewing from "react-native-image-viewing";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
|
||||
import {
|
||||
hasNativeSelectableMarkdownText,
|
||||
@@ -283,7 +282,7 @@ const MarkdownExternalLink = memo(function MarkdownExternalLink(props: {
|
||||
<NativeText
|
||||
className="font-sans"
|
||||
onPress={() => {
|
||||
void tryOpenExternalUrl(props.href, "markdown-link");
|
||||
void Linking.openURL(props.href);
|
||||
}}
|
||||
style={{
|
||||
color: props.color,
|
||||
@@ -613,7 +612,7 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
onPress={
|
||||
linkHref
|
||||
? () => {
|
||||
void tryOpenExternalUrl(linkHref, "markdown-link");
|
||||
void Linking.openURL(linkHref);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
@@ -1397,7 +1396,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const userBubbleMaxWidth = contentWidth * 0.85;
|
||||
const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
|
||||
const insets = useSafeAreaInsets();
|
||||
const topContentInset = props.contentTopInset ?? insets.top + IOS_NAV_BAR_HEIGHT;
|
||||
const topContentInset = props.contentTopInset ?? insets.top + 44;
|
||||
const bottomContentInset = props.contentBottomInset ?? 18;
|
||||
const usesNativeAutomaticInsets =
|
||||
props.usesAutomaticContentInsets === true && Platform.OS === "ios";
|
||||
@@ -1410,7 +1409,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// header-providing screen) and fall back to the standard iOS bar height.
|
||||
const navigationHeaderHeight = useContext(HeaderHeightContext);
|
||||
const anchorTopInset = usesNativeAutomaticInsets
|
||||
? navigationHeaderHeight || insets.top + IOS_NAV_BAR_HEIGHT
|
||||
? navigationHeaderHeight || insets.top + 44
|
||||
: topContentInset;
|
||||
|
||||
const iconSubtleColor = useThemeColor("--color-icon-subtle");
|
||||
@@ -1436,7 +1435,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}
|
||||
|
||||
if (presentation.href) {
|
||||
void tryOpenExternalUrl(presentation.href, "markdown-link");
|
||||
void Linking.openURL(presentation.href);
|
||||
}
|
||||
},
|
||||
[props.environmentId, props.threadId, props.workspaceRoot, navigation],
|
||||
|
||||
@@ -785,6 +785,7 @@ function ThreadRouteContent(
|
||||
connectionStateLabel={routeConnectionState}
|
||||
threadSyncStatus={selectedThreadDetailState.status}
|
||||
loadEarlier={loadEarlierTurns}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
threadCwd={selectedThreadCwd}
|
||||
|
||||
@@ -52,7 +52,6 @@ import {
|
||||
useComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useDebouncedValue, usePaginatedBranches } from "../../state/queries";
|
||||
import { vcsEnvironment } from "../../state/vcs";
|
||||
import {
|
||||
flattenQueuedThreadMessages,
|
||||
threadOutboxManager,
|
||||
@@ -140,7 +139,6 @@ type NewTaskFlowContextValue = {
|
||||
readonly branchesFetchingNextPage: boolean;
|
||||
readonly hasMoreBranches: boolean;
|
||||
readonly availableBranches: ReadonlyArray<VcsRef>;
|
||||
readonly currentCheckoutBranchName: string | null;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
readonly planModeEnabled: boolean;
|
||||
@@ -555,22 +553,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
),
|
||||
[allBranchRefs],
|
||||
);
|
||||
// The ref actually checked out in the project root, serialized onto new
|
||||
// local threads. It comes from the live status stream rather than listRefs'
|
||||
// `current` flag, which is served from a cache that can lag an out-of-band
|
||||
// `git switch` by minutes — and from the same value the PR badge compares
|
||||
// against. Detached HEAD and non-repository projects report no ref, so this
|
||||
// stays null instead of fabricating a branch. The status family is
|
||||
// deduplicated per (environmentId, cwd) with the thread rows.
|
||||
const projectGitStatus = useEnvironmentQuery(
|
||||
branchTarget.environmentId !== null && branchTarget.cwd !== null
|
||||
? vcsEnvironment.status({
|
||||
environmentId: branchTarget.environmentId,
|
||||
input: { cwd: branchTarget.cwd },
|
||||
})
|
||||
: null,
|
||||
);
|
||||
const currentCheckoutBranchName = projectGitStatus.data?.refName ?? null;
|
||||
|
||||
const filteredBranches = useMemo(() => {
|
||||
const query = branchQuery.trim().toLowerCase();
|
||||
@@ -877,10 +859,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
...(projectTitle !== undefined ? { projectTitle } : {}),
|
||||
...(projectCwd !== undefined ? { projectCwd } : {}),
|
||||
workspaceMode: mode,
|
||||
// Only an explicit picker choice, never the current checkout: a
|
||||
// queued local task drains days later against whatever is checked
|
||||
// out then, so recording a queue-time guess would pin a stale label
|
||||
// to a thread that ran somewhere else.
|
||||
branch: workspaceSelection?.branch ?? null,
|
||||
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
|
||||
// The draft only carries the flag when the user touched it; fall
|
||||
@@ -1018,7 +996,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
branchesFetchingNextPage,
|
||||
hasMoreBranches,
|
||||
availableBranches,
|
||||
currentCheckoutBranchName,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
planModeEnabled,
|
||||
@@ -1066,7 +1043,6 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
branchesFetchingNextPage,
|
||||
buildPendingTaskMessage,
|
||||
cancelEditingPendingTask,
|
||||
currentCheckoutBranchName,
|
||||
editingPendingTask,
|
||||
environments,
|
||||
expandedProvider,
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
|
||||
|
||||
describe("resolveProjectThreadCreationBranch", () => {
|
||||
it("uses the live checkout for an untouched local draft label and recorded branch", () => {
|
||||
expect(
|
||||
resolveProjectThreadCreationBranch({
|
||||
workspaceMode: "local",
|
||||
selectedBranch: null,
|
||||
currentCheckoutBranch: "feature/x",
|
||||
}),
|
||||
).toBe("feature/x");
|
||||
});
|
||||
|
||||
it("prefers an explicit picker choice over the current checkout", () => {
|
||||
expect(
|
||||
resolveProjectThreadCreationBranch({
|
||||
workspaceMode: "local",
|
||||
selectedBranch: "main",
|
||||
currentCheckoutBranch: "feature/x",
|
||||
}),
|
||||
).toBe("main");
|
||||
});
|
||||
|
||||
it("stays null when no ref is checked out (detached HEAD, non-repository, status not loaded)", () => {
|
||||
expect(
|
||||
resolveProjectThreadCreationBranch({
|
||||
workspaceMode: "local",
|
||||
selectedBranch: null,
|
||||
currentCheckoutBranch: null,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("never borrows the current checkout for a worktree draft", () => {
|
||||
expect(
|
||||
resolveProjectThreadCreationBranch({
|
||||
workspaceMode: "worktree",
|
||||
selectedBranch: null,
|
||||
currentCheckoutBranch: "feature/x",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the explicit base branch for a worktree draft", () => {
|
||||
expect(
|
||||
resolveProjectThreadCreationBranch({
|
||||
workspaceMode: "worktree",
|
||||
selectedBranch: "main",
|
||||
currentCheckoutBranch: "feature/x",
|
||||
}),
|
||||
).toBe("main");
|
||||
});
|
||||
});
|
||||
@@ -32,26 +32,6 @@ export const ProjectThreadCreationValidationError = Schema.Union([
|
||||
]);
|
||||
export type ProjectThreadCreationValidationError = typeof ProjectThreadCreationValidationError.Type;
|
||||
|
||||
/**
|
||||
* Branch recorded on a thread created from the new-task composer. An explicit
|
||||
* picker choice always wins. An untouched current-checkout draft records the
|
||||
* ref that is actually checked out, so the thread's PR badge and branch label
|
||||
* match the live git status instead of staying blank. A detached HEAD, a
|
||||
* non-repository project, or a status that has not arrived stays null rather
|
||||
* than fabricating a branch. Only the online creation path resolves a
|
||||
* checkout; a queued task cannot know the checkout it will drain against.
|
||||
*/
|
||||
export function resolveProjectThreadCreationBranch(input: {
|
||||
readonly workspaceMode: "local" | "worktree";
|
||||
readonly selectedBranch: string | null;
|
||||
readonly currentCheckoutBranch: string | null;
|
||||
}): string | null {
|
||||
if (input.selectedBranch !== null) {
|
||||
return input.selectedBranch;
|
||||
}
|
||||
return input.workspaceMode === "local" ? input.currentCheckoutBranch : null;
|
||||
}
|
||||
|
||||
export function validateProjectThreadCreation(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectId: ProjectId;
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
createAppUpdateDeferral,
|
||||
createAppUpdateLaunchCheck,
|
||||
FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS,
|
||||
registerHiddenUpdateTap,
|
||||
runAppUpdateCheck,
|
||||
shouldRecheckAppUpdateOnForeground,
|
||||
type AppUpdateCheckState,
|
||||
type AppUpdateClient,
|
||||
type AppUpdateEnvironment,
|
||||
} from "./app-updates";
|
||||
|
||||
vi.mock("expo-updates", () => ({
|
||||
@@ -35,41 +31,6 @@ function makeUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateCl
|
||||
};
|
||||
}
|
||||
|
||||
function makeUpdateEnvironment(overrides: Partial<AppUpdateEnvironment> = {}): {
|
||||
readonly backgroundCallbacks: Array<() => void>;
|
||||
readonly environment: AppUpdateEnvironment;
|
||||
readonly foregroundStayCallbacks: Array<() => void>;
|
||||
} {
|
||||
const backgroundCallbacks: Array<() => void> = [];
|
||||
const foregroundStayCallbacks: Array<() => void> = [];
|
||||
return {
|
||||
backgroundCallbacks,
|
||||
foregroundStayCallbacks,
|
||||
environment: {
|
||||
confirmInstallNow: vi.fn(async () => true),
|
||||
flushPendingWrites: vi.fn(async () => {}),
|
||||
isSafeToRestartInBackground: vi.fn(async () => true),
|
||||
onNextBackground: vi.fn((apply: () => void, _includeCurrent: boolean) => {
|
||||
backgroundCallbacks.push(apply);
|
||||
}),
|
||||
onForegroundStay: vi.fn((apply: () => void) => {
|
||||
foregroundStayCallbacks.push(apply);
|
||||
}),
|
||||
...overrides,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeAvailableUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateClient {
|
||||
return makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => ({
|
||||
isAvailable: true,
|
||||
isRollBackToEmbedded: false,
|
||||
})),
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
describe("runAppUpdateCheck", () => {
|
||||
it("does nothing while running from the Metro development server", async () => {
|
||||
vi.stubGlobal("__DEV__", true);
|
||||
@@ -84,313 +45,23 @@ describe("runAppUpdateCheck", () => {
|
||||
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("downloads silently and installs at the next backgrounding", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { backgroundCallbacks, environment } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
it("downloads and restarts when a new update is available", async () => {
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => ({
|
||||
isAvailable: true,
|
||||
isRollBackToEmbedded: false,
|
||||
})),
|
||||
});
|
||||
const states: AppUpdateCheckState[] = [];
|
||||
|
||||
await runAppUpdateCheck({
|
||||
client,
|
||||
deferral,
|
||||
environment,
|
||||
onStateChange: (state) => states.push(state),
|
||||
});
|
||||
await runAppUpdateCheck({ client, onStateChange: (state) => states.push(state) });
|
||||
|
||||
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
|
||||
expect(client.fetchUpdateAsync).toHaveBeenCalledOnce();
|
||||
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
|
||||
expect(client.reloadAsync).not.toHaveBeenCalled();
|
||||
expect(states).toEqual(["checking", "downloading", "ready"]);
|
||||
expect(deferral.pendingInstall).toBe(true);
|
||||
expect(backgroundCallbacks).toHaveLength(1);
|
||||
|
||||
backgroundCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
|
||||
expect(environment.flushPendingWrites).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("flushes pending writes before restarting", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { environment } = makeUpdateEnvironment();
|
||||
|
||||
await runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
client,
|
||||
deferral: createAppUpdateDeferral(),
|
||||
environment,
|
||||
});
|
||||
|
||||
const flushOrder = vi.mocked(environment.flushPendingWrites).mock.invocationCallOrder[0]!;
|
||||
const reloadOrder = vi.mocked(client.reloadAsync).mock.invocationCallOrder[0]!;
|
||||
expect(flushOrder).toBeLessThan(reloadOrder);
|
||||
});
|
||||
|
||||
it("prompts once the app has stayed foregrounded with the download waiting", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { environment, foregroundStayCallbacks } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
|
||||
expect(foregroundStayCallbacks).toHaveLength(1);
|
||||
|
||||
foregroundStayCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
|
||||
expect(environment.confirmInstallNow).toHaveBeenCalledOnce();
|
||||
expect(environment.flushPendingWrites).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the background install armed when the foreground prompt is declined", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { backgroundCallbacks, environment, foregroundStayCallbacks } = makeUpdateEnvironment({
|
||||
confirmInstallNow: vi.fn(async () => false),
|
||||
});
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
|
||||
foregroundStayCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(environment.confirmInstallNow).toHaveBeenCalledOnce());
|
||||
expect(client.reloadAsync).not.toHaveBeenCalled();
|
||||
expect(deferral.pendingInstall).toBe(true);
|
||||
|
||||
backgroundCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
|
||||
});
|
||||
|
||||
it("skips the foreground prompt once the install is no longer pending", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { environment, foregroundStayCallbacks } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
|
||||
// A failed deferred reload resets the deferral before the stay fires.
|
||||
deferral.pendingInstall = false;
|
||||
foregroundStayCallbacks[0]!();
|
||||
|
||||
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
|
||||
expect(client.reloadAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("re-arms instead of restarting when the app is no longer safely backgrounded", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const safe = vi.fn(async () => false);
|
||||
const { backgroundCallbacks, environment } = makeUpdateEnvironment({
|
||||
isSafeToRestartInBackground: safe,
|
||||
});
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
expect(backgroundCallbacks).toHaveLength(1);
|
||||
// Arming may fire for an already-backgrounded app…
|
||||
expect(vi.mocked(environment.onNextBackground).mock.calls[0]![1]).toBe(true);
|
||||
|
||||
backgroundCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(backgroundCallbacks).toHaveLength(2));
|
||||
expect(client.reloadAsync).not.toHaveBeenCalled();
|
||||
expect(deferral.pendingInstall).toBe(true);
|
||||
// …but a re-arm must wait for a fresh transition, or an unsafe attempt
|
||||
// would retry in a tight loop within the same background session.
|
||||
expect(vi.mocked(environment.onNextBackground).mock.calls[1]![1]).toBe(false);
|
||||
|
||||
safe.mockResolvedValue(true);
|
||||
backgroundCallbacks[1]!();
|
||||
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
|
||||
});
|
||||
|
||||
it("resets the deferral when the deferred restart fails", async () => {
|
||||
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const client = makeAvailableUpdateClient({
|
||||
reloadAsync: vi.fn(async () => {
|
||||
throw new Error("reload rejected");
|
||||
}),
|
||||
});
|
||||
const { backgroundCallbacks, environment } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
backgroundCallbacks[0]!();
|
||||
|
||||
await vi.waitFor(() => expect(deferral.pendingInstall).toBe(false));
|
||||
reportError.mockRestore();
|
||||
});
|
||||
|
||||
it("arms the deferred install once across repeated checks", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { environment } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
|
||||
expect(environment.onNextBackground).toHaveBeenCalledOnce();
|
||||
expect(environment.onForegroundStay).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("restarts into an already-downloaded update when the user asks to install", async () => {
|
||||
const client = makeUpdateClient();
|
||||
const { environment } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
deferral.pendingInstall = true;
|
||||
|
||||
await runAppUpdateCheck({ applyMode: "immediate", client, deferral, environment });
|
||||
|
||||
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
|
||||
expect(client.reloadAsync).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("honors an immediate request that joined an in-flight background check", async () => {
|
||||
let resolveCheck!: (result: {
|
||||
readonly isAvailable: boolean;
|
||||
readonly isRollBackToEmbedded: boolean;
|
||||
}) => void;
|
||||
const checkResult = new Promise<{
|
||||
readonly isAvailable: boolean;
|
||||
readonly isRollBackToEmbedded: boolean;
|
||||
}>((resolve) => {
|
||||
resolveCheck = resolve;
|
||||
});
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(() => checkResult),
|
||||
});
|
||||
const { environment } = makeUpdateEnvironment();
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
const backgroundCheck = runAppUpdateCheck({ client, deferral, environment });
|
||||
const manualCheck = runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
client,
|
||||
deferral,
|
||||
environment,
|
||||
});
|
||||
|
||||
resolveCheck({ isAvailable: true, isRollBackToEmbedded: false });
|
||||
await Promise.all([backgroundCheck, manualCheck]);
|
||||
|
||||
// The coalesced background check deferred the download, but the manual
|
||||
// caller explicitly asked to install, so the restart happens anyway.
|
||||
expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
|
||||
expect(client.reloadAsync).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("runs a single restart when the deferred install races the foreground prompt", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
let releaseFlush!: () => void;
|
||||
const blockedFlush = new Promise<void>((resolve) => {
|
||||
releaseFlush = resolve;
|
||||
});
|
||||
const flushPendingWrites = vi.fn(async (): Promise<void> => {});
|
||||
const { backgroundCallbacks, environment, foregroundStayCallbacks } = makeUpdateEnvironment({
|
||||
flushPendingWrites,
|
||||
});
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
flushPendingWrites.mockReturnValue(blockedFlush);
|
||||
|
||||
// The deferred install starts and blocks on its flush; the foreground
|
||||
// prompt firing in that window must not begin a second restart.
|
||||
backgroundCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(flushPendingWrites).toHaveBeenCalledOnce());
|
||||
foregroundStayCallbacks[0]!();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
|
||||
|
||||
releaseFlush();
|
||||
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
|
||||
});
|
||||
|
||||
it("holds the deferred restart and re-arms when the pre-restart flush fails", async () => {
|
||||
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { backgroundCallbacks, environment } = makeUpdateEnvironment({
|
||||
flushPendingWrites: vi.fn(async () => {
|
||||
throw new Error("disk full");
|
||||
}),
|
||||
});
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
backgroundCallbacks[0]!();
|
||||
|
||||
await vi.waitFor(() => expect(backgroundCallbacks).toHaveLength(2));
|
||||
expect(client.reloadAsync).not.toHaveBeenCalled();
|
||||
expect(deferral.pendingInstall).toBe(true);
|
||||
reportError.mockRestore();
|
||||
});
|
||||
|
||||
it("restarts without prompting when the caller asked for an immediate install", async () => {
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { environment } = makeUpdateEnvironment();
|
||||
const states: AppUpdateCheckState[] = [];
|
||||
|
||||
await runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
client,
|
||||
deferral: createAppUpdateDeferral(),
|
||||
environment,
|
||||
onStateChange: (state) => states.push(state),
|
||||
});
|
||||
|
||||
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
|
||||
expect(client.reloadAsync).toHaveBeenCalledOnce();
|
||||
expect(states).toEqual(["checking", "downloading", "restarting"]);
|
||||
});
|
||||
|
||||
it("holds an automatic rollback restart when the flush fails and re-arms it", async () => {
|
||||
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => ({
|
||||
isAvailable: false,
|
||||
isRollBackToEmbedded: true,
|
||||
})),
|
||||
fetchUpdateAsync: vi.fn(async () => ({
|
||||
isNew: false,
|
||||
isRollBackToEmbedded: true,
|
||||
})),
|
||||
});
|
||||
const flushPendingWrites = vi.fn(async (): Promise<void> => {
|
||||
throw new Error("storage unavailable");
|
||||
});
|
||||
const { backgroundCallbacks, environment } = makeUpdateEnvironment({ flushPendingWrites });
|
||||
const deferral = createAppUpdateDeferral();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral, environment });
|
||||
|
||||
// Nobody asked for this restart, so it must not discard the state it
|
||||
// failed to land; the rollback waits armed for the next backgrounding.
|
||||
expect(client.reloadAsync).not.toHaveBeenCalled();
|
||||
expect(deferral.pendingInstall).toBe(true);
|
||||
expect(backgroundCallbacks).toHaveLength(1);
|
||||
|
||||
flushPendingWrites.mockResolvedValue(undefined);
|
||||
backgroundCallbacks[0]!();
|
||||
await vi.waitFor(() => expect(client.reloadAsync).toHaveBeenCalledOnce());
|
||||
reportError.mockRestore();
|
||||
});
|
||||
|
||||
it("still restarts a user-requested install when the flush fails", async () => {
|
||||
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
const client = makeAvailableUpdateClient();
|
||||
const { environment } = makeUpdateEnvironment({
|
||||
flushPendingWrites: vi.fn(async () => {
|
||||
throw new Error("storage unavailable");
|
||||
}),
|
||||
});
|
||||
|
||||
await runAppUpdateCheck({
|
||||
applyMode: "immediate",
|
||||
client,
|
||||
deferral: createAppUpdateDeferral(),
|
||||
environment,
|
||||
});
|
||||
|
||||
expect(client.reloadAsync).toHaveBeenCalledOnce();
|
||||
reportError.mockRestore();
|
||||
});
|
||||
|
||||
it("restarts into the embedded bundle for a rollback directive", async () => {
|
||||
const client = makeUpdateClient({
|
||||
checkForUpdateAsync: vi.fn(async () => ({
|
||||
@@ -402,13 +73,10 @@ describe("runAppUpdateCheck", () => {
|
||||
isRollBackToEmbedded: true,
|
||||
})),
|
||||
});
|
||||
const { environment } = makeUpdateEnvironment();
|
||||
|
||||
await runAppUpdateCheck({ client, deferral: createAppUpdateDeferral(), environment });
|
||||
await runAppUpdateCheck({ client });
|
||||
|
||||
expect(client.fetchUpdateAsync).toHaveBeenCalledOnce();
|
||||
// A rollback pulls a broken bundle, so it never waits on the prompt.
|
||||
expect(environment.confirmInstallNow).not.toHaveBeenCalled();
|
||||
expect(client.reloadAsync).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
@@ -608,36 +276,6 @@ describe("createAppUpdateLaunchCheck", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldRecheckAppUpdateOnForeground", () => {
|
||||
it("requires a meaningful background gap", () => {
|
||||
expect(shouldRecheckAppUpdateOnForeground(null, 100_000, false)).toBe(false);
|
||||
expect(
|
||||
shouldRecheckAppUpdateOnForeground(
|
||||
100_000,
|
||||
100_000 + FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS - 1,
|
||||
false,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldRecheckAppUpdateOnForeground(
|
||||
100_000,
|
||||
100_000 + FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS,
|
||||
false,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("stays quiet while a downloaded update waits for its install", () => {
|
||||
expect(
|
||||
shouldRecheckAppUpdateOnForeground(
|
||||
100_000,
|
||||
100_000 + FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS,
|
||||
true,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("registerHiddenUpdateTap", () => {
|
||||
it("unlocks the manual check on the fifth tap", () => {
|
||||
let count = 0;
|
||||
|
||||
@@ -8,13 +8,7 @@ import {
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
export type AppUpdateCheckState =
|
||||
| "idle"
|
||||
| "checking"
|
||||
| "downloading"
|
||||
| "ready"
|
||||
| "restarting"
|
||||
| "current";
|
||||
export type AppUpdateCheckState = "idle" | "checking" | "downloading" | "restarting" | "current";
|
||||
|
||||
export interface AppUpdateClient {
|
||||
readonly isEnabled: boolean;
|
||||
@@ -29,70 +23,8 @@ export interface AppUpdateClient {
|
||||
readonly reloadAsync: () => Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pieces of the app the update flow has to coordinate with before it may
|
||||
* tear down the JavaScript runtime. Injectable so the flow stays unit-testable.
|
||||
*/
|
||||
export interface AppUpdateEnvironment {
|
||||
/** Asks the user to install the waiting update now; `false` keeps it deferred. */
|
||||
readonly confirmInstallNow: () => Promise<boolean>;
|
||||
/**
|
||||
* Lands persisted state (drafts, outbox) before the restart. Rejects when a
|
||||
* write failed, so a silent restart can hold off instead of dropping the
|
||||
* unsaved in-memory state.
|
||||
*/
|
||||
readonly flushPendingWrites: () => Promise<void>;
|
||||
/**
|
||||
* Whether a deferred restart may fire right now: the app must still be
|
||||
* backgrounded (flush latency or an iOS suspend can push the continuation
|
||||
* into the next foreground session) and not merely paused behind an
|
||||
* app-initiated handoff like the Android image picker.
|
||||
*/
|
||||
readonly isSafeToRestartInBackground: () => Promise<boolean>;
|
||||
/**
|
||||
* Runs `apply` the next time the app enters the background. With
|
||||
* `includeCurrent`, an app that is already backgrounded fires immediately
|
||||
* (so a backgrounding that raced module load is not missed); without it,
|
||||
* only a future transition fires, so an attempt that already failed in the
|
||||
* current background session cannot retry in a tight loop.
|
||||
*/
|
||||
readonly onNextBackground: (apply: () => void, includeCurrent: boolean) => void;
|
||||
/**
|
||||
* Runs `apply` once the app has stayed foregrounded for the whole prompt
|
||||
* window — the signal that a deferred install has had no backgrounding to
|
||||
* ride on.
|
||||
*/
|
||||
readonly onForegroundStay: (apply: () => void) => void;
|
||||
}
|
||||
|
||||
/** Tracks a downloaded update waiting for a safe moment to install. */
|
||||
export interface AppUpdateDeferral {
|
||||
pendingInstall: boolean;
|
||||
/**
|
||||
* Claimed by whichever restart sequence (deferred backgrounding, foreground
|
||||
* prompt, manual install) starts first, so racing paths cannot tear down
|
||||
* the runtime twice.
|
||||
*/
|
||||
installInProgress: boolean;
|
||||
}
|
||||
|
||||
export function createAppUpdateDeferral(): AppUpdateDeferral {
|
||||
return { pendingInstall: false, installInProgress: false };
|
||||
}
|
||||
|
||||
const appUpdateDeferral = createAppUpdateDeferral();
|
||||
|
||||
interface AppUpdateCheckOptions {
|
||||
/**
|
||||
* "background" (default) installs silently at the next backgrounding,
|
||||
* asking only if the app then stays foregrounded so long that the install
|
||||
* never gets its chance. "immediate" restarts as soon as the download
|
||||
* lands — reserved for flows where the user explicitly requested the update.
|
||||
*/
|
||||
readonly applyMode?: "background" | "immediate";
|
||||
readonly client?: AppUpdateClient;
|
||||
readonly deferral?: AppUpdateDeferral;
|
||||
readonly environment?: AppUpdateEnvironment;
|
||||
readonly onFailure?: (message: string) => void;
|
||||
readonly onStateChange?: (state: AppUpdateCheckState) => void;
|
||||
}
|
||||
@@ -154,15 +86,6 @@ export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Pr
|
||||
|
||||
if (appUpdateCheckInFlight) {
|
||||
await observeAppUpdateCheck(appUpdateCheckInFlight, options);
|
||||
// A background-mode check in flight may have deferred the download this
|
||||
// caller explicitly asked to install; honor the explicit request now.
|
||||
if (options.applyMode === "immediate") {
|
||||
const deferral = options.deferral ?? appUpdateDeferral;
|
||||
if (deferral.pendingInstall) {
|
||||
const environment = options.environment ?? defaultAppUpdateEnvironment;
|
||||
await installPendingAppUpdate(client, environment, deferral, options);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -186,9 +109,6 @@ export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Pr
|
||||
appUpdateCheckInFlight = inFlight;
|
||||
|
||||
const execution = performAppUpdateCheck(client, {
|
||||
applyMode: options.applyMode,
|
||||
deferral: options.deferral,
|
||||
environment: options.environment,
|
||||
onFailure: (message) => {
|
||||
progress.failure = message;
|
||||
notifyListeners(failureListeners, message);
|
||||
@@ -255,15 +175,6 @@ async function performAppUpdateCheck(
|
||||
options: AppUpdateCheckOptions,
|
||||
): Promise<void> {
|
||||
const setState = options.onStateChange ?? (() => {});
|
||||
const environment = options.environment ?? defaultAppUpdateEnvironment;
|
||||
const deferral = options.deferral ?? appUpdateDeferral;
|
||||
|
||||
// The user explicitly asked to install and a previous check has already
|
||||
// downloaded the update; restart into it without another network round trip.
|
||||
if (options.applyMode === "immediate" && deferral.pendingInstall) {
|
||||
await installPendingAppUpdate(client, environment, deferral, options);
|
||||
return;
|
||||
}
|
||||
|
||||
setState("checking");
|
||||
const check = await settlePromise(() => client.checkForUpdateAsync());
|
||||
@@ -292,252 +203,14 @@ async function performAppUpdateCheck(
|
||||
return;
|
||||
}
|
||||
|
||||
// A rollback directive exists to pull a broken bundle; never hold it
|
||||
// behind a prompt or a deferred install.
|
||||
if (options.applyMode === "immediate" || fetched.value.isRollBackToEmbedded) {
|
||||
const outcome = await installAppUpdate(
|
||||
client,
|
||||
environment,
|
||||
deferral,
|
||||
options,
|
||||
options.applyMode === "immediate",
|
||||
);
|
||||
if (outcome === "flush-failed") {
|
||||
// Only reachable for an automatic rollback: keep the state-bearing
|
||||
// runtime alive and retry like a deferred install. The fetched rollback
|
||||
// still applies at the next cold start regardless.
|
||||
setState("ready");
|
||||
armDeferredAppUpdateInstall(client, environment, deferral);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
setState("ready");
|
||||
armDeferredAppUpdateInstall(client, environment, deferral);
|
||||
}
|
||||
|
||||
type AppUpdateInstallOutcome = "installed" | "flush-failed" | "restart-failed";
|
||||
|
||||
/**
|
||||
* Restarting mid-session while native surfaces are mounted is the crashiest
|
||||
* moment expo-updates has, so the restart flushes persistence first and, by
|
||||
* default, waits for a backgrounding — where nothing is rendering and the
|
||||
* teardown is invisible. Only a restart the user explicitly asked for may
|
||||
* proceed over a failed flush; an automatic one aborts with "flush-failed"
|
||||
* so unsaved state is never silently discarded.
|
||||
*/
|
||||
async function installAppUpdate(
|
||||
client: AppUpdateClient,
|
||||
environment: AppUpdateEnvironment,
|
||||
deferral: AppUpdateDeferral,
|
||||
options: AppUpdateCheckOptions,
|
||||
userRequested: boolean,
|
||||
): Promise<AppUpdateInstallOutcome> {
|
||||
// A concurrent install sequence already owns the restart.
|
||||
if (deferral.installInProgress) return "installed";
|
||||
deferral.installInProgress = true;
|
||||
const setState = options.onStateChange ?? (() => {});
|
||||
setState("restarting");
|
||||
const flushed = await settlePromise(() => environment.flushPendingWrites());
|
||||
if (flushed._tag === "Failure") {
|
||||
reportUpdateFailure(flushed, "Could not save pending state.", undefined);
|
||||
if (!userRequested) {
|
||||
deferral.installInProgress = false;
|
||||
return "flush-failed";
|
||||
}
|
||||
}
|
||||
const reloaded = await settlePromise(() => client.reloadAsync());
|
||||
if (reloaded._tag === "Failure") {
|
||||
reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.", options.onFailure);
|
||||
setState("idle");
|
||||
deferral.installInProgress = false;
|
||||
return "restart-failed";
|
||||
}
|
||||
return "installed";
|
||||
}
|
||||
|
||||
/** Restarts into an already-downloaded update at the user's request. */
|
||||
async function installPendingAppUpdate(
|
||||
client: AppUpdateClient,
|
||||
environment: AppUpdateEnvironment,
|
||||
deferral: AppUpdateDeferral,
|
||||
options: AppUpdateCheckOptions,
|
||||
): Promise<void> {
|
||||
const outcome = await installAppUpdate(client, environment, deferral, options, true);
|
||||
if (outcome === "restart-failed") {
|
||||
// Let later checks re-arm the install; the downloaded update still
|
||||
// applies at the next cold start regardless.
|
||||
deferral.pendingInstall = false;
|
||||
}
|
||||
}
|
||||
|
||||
function armDeferredAppUpdateInstall(
|
||||
client: AppUpdateClient,
|
||||
environment: AppUpdateEnvironment,
|
||||
deferral: AppUpdateDeferral,
|
||||
): void {
|
||||
if (deferral.pendingInstall) return;
|
||||
deferral.pendingInstall = true;
|
||||
scheduleDeferredAppUpdateInstall(client, environment, deferral, true);
|
||||
environment.onForegroundStay(() => {
|
||||
void promptDeferredAppUpdateInstall(client, environment, deferral);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A deferred install normally rides the next backgrounding, but a session that
|
||||
* never leaves the foreground would sit on the download forever. Only then is
|
||||
* the user asked, and declining simply leaves the background install armed.
|
||||
*/
|
||||
async function promptDeferredAppUpdateInstall(
|
||||
client: AppUpdateClient,
|
||||
environment: AppUpdateEnvironment,
|
||||
deferral: AppUpdateDeferral,
|
||||
): Promise<void> {
|
||||
if (!deferral.pendingInstall || deferral.installInProgress) return;
|
||||
const installNow = await settlePromise(() => environment.confirmInstallNow());
|
||||
if (installNow._tag !== "Success" || !installNow.value) return;
|
||||
// A backgrounding while the alert was up may have started the deferred
|
||||
// restart already; the stale accept must not start a second one.
|
||||
if (!deferral.pendingInstall || deferral.installInProgress) return;
|
||||
await installPendingAppUpdate(client, environment, deferral, {});
|
||||
}
|
||||
|
||||
function scheduleDeferredAppUpdateInstall(
|
||||
client: AppUpdateClient,
|
||||
environment: AppUpdateEnvironment,
|
||||
deferral: AppUpdateDeferral,
|
||||
includeCurrent: boolean,
|
||||
): void {
|
||||
environment.onNextBackground(() => {
|
||||
void applyDeferredAppUpdateInstall(client, environment, deferral);
|
||||
}, includeCurrent);
|
||||
}
|
||||
|
||||
async function applyDeferredAppUpdateInstall(
|
||||
client: AppUpdateClient,
|
||||
environment: AppUpdateEnvironment,
|
||||
deferral: AppUpdateDeferral,
|
||||
): Promise<void> {
|
||||
if (!deferral.pendingInstall || deferral.installInProgress) return;
|
||||
deferral.installInProgress = true;
|
||||
const flushed = await settlePromise(() => environment.flushPendingWrites());
|
||||
const safe = await settlePromise(() => environment.isSafeToRestartInBackground());
|
||||
if (flushed._tag === "Failure" || safe._tag !== "Success" || !safe.value) {
|
||||
if (flushed._tag === "Failure") {
|
||||
// Nothing is lost yet: keep the state-bearing runtime alive and retry
|
||||
// the flush at the next backgrounding instead of restarting over it.
|
||||
reportUpdateFailure(flushed, "Could not save pending state.", undefined);
|
||||
}
|
||||
deferral.installInProgress = false;
|
||||
// This attempt already ran in the current background session; retrying
|
||||
// before a fresh transition would just loop over the same failure.
|
||||
scheduleDeferredAppUpdateInstall(client, environment, deferral, false);
|
||||
return;
|
||||
}
|
||||
const reloaded = await settlePromise(() => client.reloadAsync());
|
||||
if (reloaded._tag === "Failure") {
|
||||
reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.", undefined);
|
||||
deferral.installInProgress = false;
|
||||
// Let later checks re-arm the install; the downloaded update still
|
||||
// applies at the next cold start regardless.
|
||||
deferral.pendingInstall = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function defaultConfirmInstallNow(): Promise<boolean> {
|
||||
const { Alert } = await import("react-native");
|
||||
return new Promise<boolean>((resolve) => {
|
||||
Alert.alert(
|
||||
"Update ready",
|
||||
"A new version has been downloaded and installs automatically the next time you leave the app. Install it now instead?",
|
||||
[
|
||||
{ onPress: () => resolve(false), style: "cancel", text: "Later" },
|
||||
{ onPress: () => resolve(true), text: "Install Now" },
|
||||
],
|
||||
{ cancelable: true, onDismiss: () => resolve(false) },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function defaultFlushPendingWrites(): Promise<void> {
|
||||
// Attempt every flush before surfacing the first failure, so one broken
|
||||
// store cannot keep the others from landing.
|
||||
const results = await Promise.allSettled([
|
||||
import("../../state/use-composer-drafts").then((drafts) => drafts.flushComposerDrafts()),
|
||||
import("../../state/thread-outbox").then((outbox) => outbox.flushThreadOutbox()),
|
||||
]);
|
||||
const failed = results.find(
|
||||
(result): result is PromiseRejectedResult => result.status === "rejected",
|
||||
);
|
||||
if (failed) throw failed.reason;
|
||||
}
|
||||
|
||||
async function defaultIsSafeToRestartInBackground(): Promise<boolean> {
|
||||
const { isForegroundHandoffActive } = await import("../../lib/foreground-handoff");
|
||||
if (isForegroundHandoffActive()) return false;
|
||||
const { AppState } = await import("react-native");
|
||||
return AppState.currentState === "background";
|
||||
}
|
||||
|
||||
function defaultOnNextBackground(apply: () => void, includeCurrent: boolean): void {
|
||||
void import("react-native").then(({ AppState }) => {
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state !== "background") return;
|
||||
subscription.remove();
|
||||
apply();
|
||||
});
|
||||
// The app may already have backgrounded while this module was loading;
|
||||
// the listener alone would then wait a whole extra foreground cycle.
|
||||
if (includeCurrent && AppState.currentState === "background") {
|
||||
subscription.remove();
|
||||
apply();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* How long the app may stay foregrounded with a downloaded update before the
|
||||
* install prompt appears. Long enough that most sessions background naturally
|
||||
* and install silently instead.
|
||||
*/
|
||||
export const DEFERRED_INSTALL_PROMPT_AFTER_MS = 30 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* The window resets on every backgrounding because that is exactly when the
|
||||
* deferred install gets its chance. iOS "inactive" blips (app switcher, a
|
||||
* pulled-down notification shade) leave the timer running.
|
||||
*/
|
||||
function defaultOnForegroundStay(apply: () => void): void {
|
||||
void import("react-native").then(({ AppState }) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const arm = () => {
|
||||
timer ??= setTimeout(() => {
|
||||
subscription.remove();
|
||||
apply();
|
||||
}, DEFERRED_INSTALL_PROMPT_AFTER_MS);
|
||||
};
|
||||
const disarm = () => {
|
||||
if (timer === undefined) return;
|
||||
clearTimeout(timer);
|
||||
timer = undefined;
|
||||
};
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") arm();
|
||||
else if (state === "background") disarm();
|
||||
});
|
||||
if (AppState.currentState === "active") arm();
|
||||
});
|
||||
}
|
||||
|
||||
const defaultAppUpdateEnvironment: AppUpdateEnvironment = {
|
||||
confirmInstallNow: defaultConfirmInstallNow,
|
||||
flushPendingWrites: defaultFlushPendingWrites,
|
||||
isSafeToRestartInBackground: defaultIsSafeToRestartInBackground,
|
||||
onNextBackground: defaultOnNextBackground,
|
||||
onForegroundStay: defaultOnForegroundStay,
|
||||
};
|
||||
|
||||
function reportUpdateFailure(
|
||||
result: AtomCommandResult<unknown, unknown>,
|
||||
fallback: string,
|
||||
@@ -570,53 +243,3 @@ export function createAppUpdateLaunchCheck(
|
||||
}
|
||||
|
||||
export const checkForAppUpdateOnLaunch = createAppUpdateLaunchCheck();
|
||||
|
||||
/**
|
||||
* The app can stay resident for days, so a launch-only check misses updates
|
||||
* published while it was in memory. Anything shorter reads as noise: brief
|
||||
* app switches should not trigger network checks or an install prompt.
|
||||
*/
|
||||
export const FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS = 15 * 60 * 1000;
|
||||
|
||||
export function shouldRecheckAppUpdateOnForeground(
|
||||
backgroundedAtMs: number | null,
|
||||
activeAtMs: number,
|
||||
pendingInstall: boolean,
|
||||
): boolean {
|
||||
if (pendingInstall) return false;
|
||||
return (
|
||||
backgroundedAtMs !== null &&
|
||||
activeAtMs - backgroundedAtMs >= FOREGROUND_APP_UPDATE_RECHECK_AFTER_MS
|
||||
);
|
||||
}
|
||||
|
||||
export function createAppUpdateForegroundRecheck(
|
||||
client: AppUpdateClient = Updates,
|
||||
deferral: AppUpdateDeferral = appUpdateDeferral,
|
||||
): () => void {
|
||||
let started = false;
|
||||
|
||||
return () => {
|
||||
if (started || !isAppUpdateCheckAvailable(client)) return;
|
||||
started = true;
|
||||
void import("react-native").then(({ AppState }) => {
|
||||
let backgroundedAtMs: number | null = null;
|
||||
AppState.addEventListener("change", (state) => {
|
||||
if (state === "background") {
|
||||
backgroundedAtMs = Date.now();
|
||||
return;
|
||||
}
|
||||
if (state !== "active") return;
|
||||
const shouldCheck = shouldRecheckAppUpdateOnForeground(
|
||||
backgroundedAtMs,
|
||||
Date.now(),
|
||||
deferral.pendingInstall,
|
||||
);
|
||||
backgroundedAtMs = null;
|
||||
if (shouldCheck) void runAppUpdateCheck({ client, deferral });
|
||||
});
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export const startAppUpdateForegroundRecheck = createAppUpdateForegroundRecheck();
|
||||
@@ -1,19 +0,0 @@
|
||||
import type { File } from "expo-file-system";
|
||||
|
||||
let tempFileSequence = 0;
|
||||
|
||||
/**
|
||||
* Replaces a file's contents through a sibling temp file and an overwriting
|
||||
* rename, so an interrupted write (app restart, process death) never leaves a
|
||||
* truncated document at the final path. Each write stages through its own
|
||||
* temp file so concurrent writers to the same destination cannot move or
|
||||
* clobber each other's staging file mid-flight.
|
||||
*/
|
||||
export async function writeFileAtomically(file: File, contents: string): Promise<void> {
|
||||
const { File: FileConstructor } = await import("expo-file-system");
|
||||
tempFileSequence += 1;
|
||||
const temp = new FileConstructor(file.parentDirectory, `${file.name}.${tempFileSequence}.tmp`);
|
||||
temp.create({ intermediates: true, overwrite: true });
|
||||
temp.write(contents);
|
||||
temp.moveSync(file, { overwrite: true });
|
||||
}
|
||||