249 Commits
Author SHA1 Message Date
Weixuan Fu dfc92186f0 Update README.md 2025-04-16 22:02:53 +08:00
Weixuan Fu 338b9b85e6 Update LICENSE 2024-10-01 22:40:46 +08:00
Weixuan Fu 16b8a709a2 Update README.md 2024-08-23 11:39:01 +08:00
Weixuan Fu 8e3c90e9f7 Merge pull request #468 from ComfyNodePRs/licence-update
Update PyProject Toml - License
2024-08-14 13:11:52 +08:00
snomiao f084b076aa chore(licence-update): Update PyProject Toml - License 2024-08-14 00:07:45 +00:00
Weixuan Fu 563be3c17e Merge pull request #451 from Amorano/patch-1
report error instead of exception dump
2024-08-13 00:19:30 +08:00
Weixuan Fu 8e7058e151 Merge pull request #454 from 11cafe/beta
Beta
2024-08-04 17:35:15 +08:00
Weixuan Fu 98e5772cb2 build 2024-08-04 17:34:13 +08:00
Weixuan Fu a23b6cd56b Merge pull request #453 from 11cafe/dev
Dev
2024-08-04 17:32:56 +08:00
Weixuan Fu fb5e3ae89e wait for document.body to load and comfyapp to load before loading workspace manager to avoid plugin not showup 2024-08-04 17:28:31 +08:00
Weixuan Fu 2f4d3c26a9 fix encrypt utils not found, unable to build 2024-08-04 16:56:46 +08:00
Alexander G. Morano 74ea810ca6 report error instead of exception dump
When the json data is malformed, or someone is storing OTHER data than comfy workflows in the folders, this can cause an exception dump when the manager reads the files.

This simply adds a nicer message around the process.
2024-08-02 16:14:39 -07:00
Weixuan Fu 8bbfe5314d Update README.md 2024-07-10 11:28:00 +08:00
Weixuan Fu 621afb11ac Merge pull request #433 from 11cafe/beta
fix new settings not working in windows
2024-07-02 21:41:38 +08:00
Weixuan Fu 8456ea44bf fix new settings not working in windows 2024-07-02 21:40:16 +08:00
Weixuan Fu c89c5d3310 Merge pull request #432 from 11cafe/beta
better settings.json
2024-07-02 13:27:52 +08:00
Weixuan Fu 7daf20238b build dist - fix user settings, replace userSettings with settings.json with readable format 2024-07-01 23:29:27 +08:00
Weixuan Fu 2697daa7b8 Merge branch 'dev' into beta 2024-07-01 23:28:36 +08:00
Weixuan Fu 64e5f7f480 fix my workflows dir setting not saved 2024-07-01 23:28:07 +08:00
Weixuan Fu c2780caad4 build dist 2024-06-30 02:09:49 +08:00
Weixuan Fu fb9f355c6a Merge branch 'beta' 2024-06-30 02:09:29 +08:00
Weixuan Fu e751e0543a Merge branch 'dev' into betat p 2024-06-30 02:09:10 +08:00
Weixuan Fu bece4a711f make share link unlisted by default 2024-06-30 02:08:27 +08:00
Weixuan Fu f62e1dc1a5 Merge branch 'beta' 2024-06-29 15:08:04 +08:00
Weixuan Fu cb623b6e5f build dist 2024-06-29 15:07:45 +08:00
Weixuan Fu b1052d32b2 Merge branch 'dev' into beta 2024-06-29 15:07:03 +08:00
Weixuan Fu 5442392003 fix api prompt not added in create version 2024-06-29 15:06:47 +08:00
Weixuan Fu 3b23b8aa91 Merge pull request #429 from 11cafe/beta
Beta
2024-06-29 14:12:29 +08:00
Weixuan Fu c385393313 build dis - copy share link, disable video thumbnail, disable save disk db 2024-06-29 14:07:46 +08:00
Weixuan Fu db9245b2ef Merge branch 'dev' into beta 2024-06-29 14:06:27 +08:00
Weixuan Fu eccfd87ce4 remove video preview 2024-06-29 14:06:09 +08:00
Weixuan Fu 201a1aabd5 add copy share link button in dropdown. and remove save disk db 2024-06-29 14:03:26 +08:00
Weixuan Fu a251035fee remove backfill indexdb 2024-06-29 13:06:50 +08:00
Weixuan Fu 87a1d96c2f Merge pull request #424 from 11cafe/beta
Beta
2024-06-26 16:53:17 +08:00
Weixuan Fu 8e1c6a47cb build for v history 2024-06-26 16:52:39 +08:00
Weixuan Fu f68a5e994a Merge branch 'dev' into beta 2024-06-26 16:52:14 +08:00
Weixuan Fu ee2a3a2d2c fix version load 2024-06-26 16:51:44 +08:00
Weixuan Fu 3da2fcfa72 Merge branch 'beta' 2024-06-26 12:56:09 +08:00
Weixuan Fu f3c8e8c98d build dist 2024-06-26 12:55:12 +08:00
Weixuan Fu 3f02557170 Merge branch 'dev' into beta 2024-06-26 12:54:55 +08:00
Weixuan Fu 23652905c9 add copy cloud shareable link 2024-06-26 12:52:50 +08:00
Weixuan Fu d9c2015850 Merge pull request #421 from 11cafe/beta
Beta
2024-06-26 11:04:57 +08:00
Weixuan Fu cf5ce2c3df build dist 2024-06-26 11:02:15 +08:00
Weixuan Fu 4a5c7c1631 update cloud id after created cloud version 2024-06-26 11:01:06 +08:00
Weixuan Fu 19ac362b3a add version hi`story drawer 2024-06-26 02:08:12 +08:00
Weixuan Fu 41c6ad5318 add error logs 2024-06-25 23:10:06 +08:00
Weixuan Fu 9cf00a6de0 Update README.md 2024-06-25 22:40:20 +08:00
Weixuan Fu b36e2a472f Update README.md 2024-06-25 22:37:58 +08:00
Weixuan Fu 276fead5c9 remove rebase dist 2024-06-25 22:17:06 +08:00
Weixuan Fu 431d56ef14 add share key for create version 2024-06-25 22:11:38 +08:00
Weixuan Fu 793f07f6e2 add decode encode 2024-06-25 22:11:38 +08:00
Weixuan Fu 194f9ddac0 create version connect cloud 2024-06-25 22:11:38 +08:00
Weixuan Fu 203a357837 fix workspace manager not showup after comfyui updated 2024-06-25 22:11:21 +08:00
Weixuan Fu 759f304478 Merge pull request #417 from 11cafe/beta
beta
2024-06-24 20:07:34 +08:00
Weixuan Fu dd3add9543 build disr 2024-06-24 20:03:38 +08:00
Weixuan Fu 1549af7b6b Merge branch 'dev' into beta 2024-06-24 20:03:08 +08:00
Weixuan Fu 649a06eac3 fix multi tab overwrites wrong cur workflow 2024-06-24 20:02:54 +08:00
Weixuan Fu cddff8f4e4 Update README.md 2024-06-23 09:19:39 +08:00
Weixuan Fu d3ef04400f Update README.md 2024-06-21 18:50:10 +08:00
Weixuan Fu e65ad81b55 save or discard dialog setting
Beta
2024-06-21 18:26:13 +08:00
Weixuan Fu 939272dc9d build dist - save or discard dialog setting 2024-06-21 18:25:05 +08:00
Weixuan Fu 1dc8f62529 Merge branch 'dev' into beta 2024-06-21 18:24:21 +08:00
Weixuan Fu 7870cf2249 add settings to disable unsaved warning 2024-06-21 18:24:00 +08:00
Weixuan Fu b9889fb9e8 revert back unwanted changes 2024-06-21 18:11:05 +08:00
Weixuan Fu 60c31720b3 Update README.md 2024-06-21 18:00:42 +08:00
Weixuan Fu 2136340896 Update README.md 2024-06-21 18:00:17 +08:00
Weixuan Fu 21fc00f2b3 build dist 2024-06-21 17:53:21 +08:00
Weixuan Fu 4bcb0f5e13 Merge pull request #413 from 11cafe/beta
remove autosave workflow mode
2024-06-21 17:51:27 +08:00
Weixuan Fu bdc09ce94b remove overwrite dropping files setting 2024-06-21 17:49:32 +08:00
Weixuan Fu 34594aaee6 Merge branch 'dev' into beta 2024-06-21 17:47:56 +08:00
Weixuan Fu 296a65aab7 remove + newworkflow button in topbar 2024-06-21 17:44:19 +08:00
Weixuan Fu 69eaecef67 remove auto save mode 2024-06-21 17:37:40 +08:00
Weixuan Fu e03250c75b add try catch image upload error to prevent throwing
Beta
2024-06-21 14:22:59 +08:00
Weixuan Fu 69061b049e add build dist 2024-06-21 14:22:25 +08:00
Weixuan Fu ba98a8a728 Merge branch 'dev' into beta 2024-06-21 14:17:47 +08:00
Weixuan Fu 0ca5a256a0 add try catch image upload error to prevent throwing 2024-06-21 14:17:36 +08:00
Weixuan Fu 6b22f272bf Merge pull request #410 from 11cafe/beta
fix share dialog not working in older plugin due to host domain mismatch
2024-06-20 13:18:45 +08:00
Weixuan Fu 237ad68f68 build dist 2024-06-20 12:41:39 +08:00
Weixuan Fu d5203e2f19 remove indexdb usage in workflowstable, store all metadata in json.workspace_info 2024-06-20 12:41:16 +08:00
Weixuan Fu c0abaefe33 revert back share dialog 2024-06-20 12:40:01 +08:00
Weixuan Fu f93df0fae6 fix sharing build dist 2024-06-20 12:29:22 +08:00
Weixuan Fu 8955f2b8d9 delete dist 2024-06-20 12:28:47 +08:00
Weixuan Fu 257ae0eeed Merge branch 'beta' into dev 2024-06-20 12:27:48 +08:00
Weixuan Fu e9ae7cf78f build dist 2024-06-20 12:25:55 +08:00
Weixuan Fu - windows c017486af7 build dist 2024-06-20 12:25:55 +08:00
Weixuan Fu c42a7488f9 Update README.md 2024-06-20 12:25:55 +08:00
Weixuan Fu 64bef141e8 Update README.md 2024-06-20 12:25:55 +08:00
Weixuan Fu cc6e84e61c Update README.md 2024-06-20 12:25:55 +08:00
Weixuan Fu 3fba152799 build dist 2024-06-20 12:25:55 +08:00
Weixuan Fu d0250c8656 build dist 2024-06-20 12:25:55 +08:00
Weixuan Fu c3801d48a4 build dist for enforce 2way sync 2024-06-20 12:25:55 +08:00
Weixuan Fu 0ede851085 build dist 2024-06-20 12:25:55 +08:00
Weixuan Fu 46a421a656 Update README.md 2024-06-20 12:25:55 +08:00
Weixuan Fu 170cd936bc Update README.md 2024-06-20 12:25:55 +08:00
Weixuan Fu d54721a7b4 Update README.md 2024-06-20 12:25:55 +08:00
Weixuan Fu 73ef48bc22 Update README.md 2024-06-20 12:25:55 +08:00
Weixuan Fu 6e1c5cd8af Update README.md 2024-06-20 12:25:55 +08:00
Weixuan Fu dc59c5a19b build 2024-06-20 12:25:55 +08:00
Weixuan Fu a15985e146 formatter 2024-06-20 12:24:13 +08:00
Weixuan Fu - windows 16e061326a fix share dialog not working in older plugin due to host domain mismatch 2024-06-20 12:22:52 +08:00
Weixuan Fu 44543a9a13 Merge pull request #409 from 11cafe/beta
build dist
2024-06-20 10:59:33 +08:00
Weixuan Fu 9b0aa05bdf build dist 2024-06-20 10:59:00 +08:00
Weixuan Fu 19190f9d10 Merge pull request #408 from 11cafe/beta
fix delete workflow inside folder not working in windows due to path \
2024-06-20 10:58:32 +08:00
Weixuan Fu f8658097ab code formatter 2024-06-20 10:56:35 +08:00
Weixuan Fu 2265813f21 Update README.md 2024-06-20 02:27:12 +08:00
Weixuan Fu - windows 793d64a62c build dist 2024-06-20 01:31:03 +08:00
Weixuan Fu - windows 98b02afa22 Merge branch 'dev' into beta 2024-06-20 01:27:50 +08:00
Weixuan Fu - windows 08daec1df0 fix path sep not working on window 2024-06-20 01:26:30 +08:00
Weixuan Fu 70aa6bfdb4 fix windows path error when deleting workflow inside folder 2024-06-20 01:03:10 +08:00
Weixuan Fu efe02ddfcb Update README.md 2024-06-19 19:26:43 +08:00
Weixuan Fu b7b09de812 Update README.md 2024-06-19 01:20:37 +08:00
Weixuan Fu 64b2ddad3a cleanup code 2024-06-18 13:00:54 +08:00
Weixuan Fu 1fdef6a8d3 Merge pull request #407 from 11cafe/beta
Beta
2024-06-18 08:59:19 +08:00
Weixuan Fu df93ecaa42 build dist 2024-06-18 08:58:30 +08:00
Weixuan Fu 853b4c8926 Merge branch 'dev' into beta 2024-06-18 08:58:07 +08:00
Weixuan Fu 1aec5359ce use civit api instead of search api to download models to avoid search index upgrade every time 2024-06-18 08:54:57 +08:00
Weixuan Fu 2398de9940 Merge pull request #405 from 11cafe/beta
fix model list not show up, save workflow metadata to workflow json file (cloudID, saveLock, imagePath)
2024-06-18 08:39:19 +08:00
Weixuan Fu 8af9d6143c build dist 2024-06-18 01:22:00 +08:00
Weixuan Fu 62a53cfdf4 Merge branch 'dev' into beta 2024-06-18 01:21:32 +08:00
Weixuan Fu b44e4e4972 fix model list not displaying models 2024-06-18 01:21:15 +08:00
Weixuan Fu 713eb1158c Merge pull request #403 from 11cafe/less-indexdb
save metadata in workflow json
2024-06-17 12:02:56 +08:00
Weixuan Fu 1b3241424f save metadata in workflow json 2024-06-17 11:50:38 +08:00
Weixuan Fu 74c2efaca3 send2trash, fix indexdb opening error by try catch, restructure and simplify share dialog
Beta
2024-06-17 11:15:33 +08:00
Weixuan Fu 2f4a3f52c4 build dist for enforce 2way sync 2024-06-16 19:58:42 +08:00
Weixuan Fu e98014823b Merge branch 'dev' into beta 2024-06-16 19:58:09 +08:00
Weixuan Fu 827a1f1731 enfore 2way sync mode 2024-06-16 19:57:55 +08:00
Weixuan Fu 610a4fca92 build dist 2024-06-16 19:56:18 +08:00
Weixuan Fu b212bada44 Merge pull request #401 from 11cafe/dev
add send2trash when deleting workflow, restructure sharedialog, fix indexdb error preventing workflows to show up in files drawer
2024-06-16 19:55:43 +08:00
Weixuan Fu 9afa5b920f add try catch around send2trash, change all nodecafe.org to nodecafe.co 2024-06-16 01:23:42 +08:00
Weixuan Fu db9c13f89d Update README.md 2024-06-15 02:17:58 +08:00
Weixuan Fu 0ced230c8f improve share workflow 2024-06-15 01:49:34 +08:00
Weixuan Fu ea4a814e02 Update README.md 2024-06-14 15:17:18 +08:00
Weixuan Fu 010839adbb Update README.md 2024-06-14 15:16:35 +08:00
Weixuan Fu 705633b9d9 fix share dialog, cleaner 2024-06-05 19:37:47 +08:00
Weixuan Fu f97450465d cleanup share and deps form logic, add models deps automatically 2024-06-05 19:23:37 +08:00
Weixuan Fu 7228169ee7 fix version name not updating 2024-06-04 22:46:07 +08:00
Weixuan Fu 9c1a1890fe Update README.md 2024-06-04 00:46:26 +08:00
Weixuan Fu 4fcf3dc053 fix 2024-06-02 20:44:51 +08:00
Weixuan Fu c977e4cd51 Update README.md 2024-05-31 17:50:26 +08:00
Weixuan Fu f7652cbcbe remove legacy non-twoway-sync mode disk file manipulations 2024-05-30 18:43:09 +08:00
Weixuan Fu 727f55d843 add try catch when scan from workflow folder, remove saving workflowJSON col to media table 2024-05-30 18:33:08 +08:00
Weixuan Fu 5343172070 fix savelock not working on page refresh 2024-05-30 02:28:06 +08:00
Weixuan Fu 1c488fdbe4 add send to trash package to delete file to trash instead of perm deletion 2024-05-30 02:08:11 +08:00
Weixuan Fu 74be8c1e08 Merge pull request #390 from 11cafe/beta
update civit index
2024-05-27 21:55:00 +08:00
Weixuan Fu 81a0cf3827 build 2024-05-27 21:54:26 +08:00
Weixuan Fu 6176a56ff9 fix civit ai search index 2024-05-27 21:53:08 +08:00
Weixuan Fu ed4c5b85b9 Merge pull request #387 from 11cafe/dev
add publisher id to toml
2024-05-23 16:45:47 +08:00
Weixuan Fu dd7c892ef5 add publisher id to toml 2024-05-23 16:38:28 +08:00
Weixuan Fu 297dbab260 Update README.md 2024-05-23 14:20:16 +08:00
Weixuan Fu 40c9ec735a Update README.md 2024-05-23 14:19:55 +08:00
Weixuan Fu 728332d5f7 Update README.md 2024-05-23 14:19:13 +08:00
Weixuan Fu b5efdf65a5 Merge pull request #386 from 11cafe/beta
fix privacy always private in share dialog, add full error stack trace in scan workflows error
2024-05-23 14:17:58 +08:00
Weixuan Fu 3bc35d1d24 build 2024-05-23 14:16:57 +08:00
Weixuan Fu d8e7522807 Merge branch 'dev' into beta 2024-05-23 14:16:24 +08:00
Weixuan Fu 9f90903f08 add traceback full error stack in scan workflow handle 2024-05-23 14:16:06 +08:00
Weixuan Fu 056d0cf1d1 Merge pull request #383 from 11cafe/beta
fix workspace not run in cloud - replace all fetch with fetch api
2024-05-23 13:58:23 +08:00
Weixuan Fu e272cd2c69 Update README.md 2024-05-22 22:14:01 +08:00
Weixuan Fu 4bf83146ee fix share dialog selected privacy not effecting cloud 2024-05-22 12:56:13 +08:00
Weixuan Fu 4059f3f412 Merge pull request #382 from 11cafe/dev
fix workspace not run in cloud - replace all fetch with fetch api
2024-05-22 12:30:52 +08:00
Weixuan Fu d6733ce226 fix workspace not run in cloud - replace all fetch with fetch api 2024-05-22 12:12:43 +08:00
Weixuan Fu e76736f72a Merge pull request #374 from 11cafe/beta
fix cloud proxy problem app.js cannot import
2024-05-22 11:40:42 +08:00
Weixuan Fu 952bae503f Merge pull request #376 from haohaocreates/pyproject.toml
Add pyproject.toml for Custom Node Registry
2024-05-22 11:32:31 +08:00
Weixuan Fu 93db2f5654 Merge pull request #377 from haohaocreates/publish-action
Add Github Action for Publishing to Comfy Registry
2024-05-22 11:27:12 +08:00
haohaocreates 1827f6ec65 Add Github Action for Publishing to Comfy Registry 2024-05-16 23:23:19 -04:00
haohaocreates ded779d20b Remove Models Dependencies 2024-05-16 22:47:46 -04:00
haohaocreates 1d9b1ef665 Add pyproject.toml for Custom Node Registry 2024-05-16 22:46:08 -04:00
Weixuan Fu a20fd1f3ed build fix for cloud proxy 2024-05-14 18:44:49 +08:00
Weixuan Fu 2262bd5bb1 Merge branch 'dev' into beta 2024-05-14 18:44:24 +08:00
Weixuan Fu f040fc294c fix app import for cloud proxy
fix app import for cloud proxy
2024-05-14 18:44:06 +08:00
Weixuan Fu e64e78e68c fix json compare to debounce onIsDirty to reduce frequency of json compare 2024-05-14 18:42:41 +08:00
Weixuan Fu 14eadf8582 fix app import for cloud proxy 2024-05-14 18:37:11 +08:00
Weixuan Fu 1ebaaca144 Merge pull request #372 from 11cafe/beta
fix app import to do lazy load
2024-05-14 18:27:49 +08:00
Weixuan Fu 797b878aa8 Merge branch 'dev' into beta 2024-05-14 18:26:13 +08:00
Weixuan Fu d972cf8e88 fix app import to do lazy load 2024-05-14 18:25:35 +08:00
Weixuan Fu 352572dd64 Merge pull request #371 from 11cafe/beta
fix 2 duplicated lora added when drag from model manager
2024-05-14 18:17:38 +08:00
Weixuan Fu 585adf9e00 Merge brancht 'dev' into beta 2024-05-14 18:15:12 +08:00
Weixuan Fu 1995ac6278 fix duplicated loras node added, fix save new workflow prompt cancel still save new workflow 2024-05-14 00:35:23 +08:00
Weixuan Fu 7d36bcd6ff Merge pull request #367 from 11cafe/beta
add try catch on json.load in dedup
2024-05-10 15:35:30 +08:00
Weixuan Fu cb9fa6de6d Merge pull request #366 from 11cafe/dev
add try catch on json.load in dedup
2024-05-10 15:34:45 +08:00
Weixuan Fu 5a50adc876 add try catch on json.load in dedup 2024-05-10 15:33:10 +08:00
Weixuan Fu 22a030b4f6 Merge pull request #364 from 11cafe/beta
make refresh keep the current workflow cache
2024-05-10 15:03:20 +08:00
Weixuan Fu e012933486 Merge branch 'dev' into beta 2024-05-10 13:26:31 +08:00
Weixuan Fu 6bbfe6fdc4 Merge pull request #363 from 11cafe/null-flow
remove file input listener, onConfigure check for workspace_info.id matches curWorkflow.id, if not match, set curworkflow to null
2024-05-10 13:14:43 +08:00
Weixuan Fu f085b4a23c when curflow is null, make new workflow button save new workflow button; also check isDirty when refresh page 2024-05-10 13:11:17 +08:00
Weixuan Fu 37d949f575 compare workspace_info.id onconfigure if not == curflowID then set null 2024-05-10 11:41:49 +08:00
Weixuan Fu 429a3a0d60 Merge pull request #362 from 11cafe/cloudhost-setting
add setting to chang cloud host
2024-05-10 11:40:53 +08:00
Weixuan Fu 73f400340c add setting to chang cloud host 2024-05-10 11:11:28 +08:00
Weixuan Fu ecd91c636c Merge pull request #348 from 11cafe/cache-last-workflow
use localstorage cached last workflow instead of override with curren…
2024-05-10 11:06:49 +08:00
Weixuan Fu 50e69bccdf Update README.md 2024-05-07 20:23:20 +08:00
Weixuan Fu 8efdf23c2f Update README.md 2024-05-07 20:23:08 +08:00
Weixuan Fu de29d72afa Update README.md 2024-05-06 20:25:37 +08:00
Weixuan Fu 4767dba038 Merge pull request #359 from 11cafe/beta
change card bg color
2024-04-30 19:17:56 +08:00
Weixuan Fu 01db33312c change split border color 2024-04-30 19:16:25 +08:00
Weixuan Fu c19423afc3 Merge branch 'dev' into beta 2024-04-30 19:15:01 +08:00
Weixuan Fu cfd349f05c change drawer color to black 2024-04-30 19:12:07 +08:00
Weixuan Fu acf12e54ca upgrade share dialog to include deps form, fix some ui bugs like multi select button not show up
upgrade share dialog to include deps form, fix some ui bugs like multi select button not show up
2024-04-18 18:03:50 +08:00
Weixuan Fu f566650a60 build last pr: update share dialog with resource deps form 2024-04-17 18:03:33 +08:00
Weixuan Fu 0ee3c36f00 merge download runnable json into share dialog, remove unused npm packages (uuid, framer-motion), add back multi select button
merge download runnable json into share dialog, remove unused npm packages (uuid, framer-motion), add back multi select button
2024-04-17 18:02:17 +08:00
Weixuan Fu 2c26b90f7d simplify share dialog, remove versions list, only allow latest version share 2024-04-17 17:32:37 +08:00
Weixuan Fu 03c83f3f01 integrate enable deps form to share dialog 2024-04-17 17:28:53 +08:00
Weixuan Fu b62c3ef9df use localstorage cached last workflow instead of override with current disk saved version 2024-04-15 18:46:41 +08:00
Weixuan Fu 823bb4cc2c bring back multi select button 2024-04-15 17:32:16 +08:00
Weixuan Fu dbcf3d434b Merge pull request #346 from 11cafe/beta
fix civit model index change
2024-04-13 22:46:37 +08:00
Weixuan Fu eb1dce7168 Merge branch 'dev' into beta 2024-04-13 22:43:52 +08:00
Weixuan Fu c9e48dde09 hide scrollbar
hide scrollbar
2024-04-12 22:54:49 +08:00
Weixuan Fu cc4a5e4c94 Merge branch 'dev' into beta 2024-04-12 22:51:10 +08:00
Weixuan Fu 4d40613b15 Merge pull request #341 from 11cafe/beta
fix model download has extra symbol
2024-04-09 21:17:29 +08:00
Weixuan Fu b447707173 build 2024-04-09 21:16:18 +08:00
Weixuan Fu 77f524aa55 Merge pull request #340 from 11cafe/dev
fix download model url sometimes has extra ; symbol on filename
2024-04-09 21:15:45 +08:00
Weixuan Fu 321c996439 Merge branch 'beta' 2024-04-08 16:11:05 +08:00
Weixuan Fu 802bdfd85b Merge branch 'dev' into beta 2024-04-08 03:21:00 +08:00
Weixuan Fu 74cd371af8 Merge branch 'dev' into beta 2024-04-07 22:34:57 +08:00
Weixuan Fu 5dc8ab668f fix reboot issue on linu 2024-04-07 19:59:17 +08:00
Weixuan Fu 8ed164625f build for fix reboot, make autosave false by default 2024-04-07 19:59:17 +08:00
Weixuan Fu 594525b997 fixed shelve reboot error, make auto save false default 2024-04-07 19:59:17 +08:00
Weixuan Fu 4427a5c2a8 add edit download url button to download space json, fix shift+s block input 2024-04-07 19:59:17 +08:00
Weixuan Fu 0383b3ec3b fix reboot issue on linu 2024-04-06 16:55:18 +08:00
Weixuan Fu 5984111a54 Update README.md 2024-04-05 00:50:04 +08:00
Weixuan Fu fd183c641d build for fix reboot, make autosave false by default 2024-04-04 23:58:37 +08:00
Weixuan Fu e5a82dce97 fix shelve throws when reboot 2024-04-04 23:57:37 +08:00
Weixuan Fu a7a6b215ab revert model_list shelve open for perf benchmark 2024-03-31 23:06:23 +08:00
Weixuan Fu a8eed53e26 Merge pull request #331 from 11cafe/beta
fix files list slow loading, add action buttons back to gallery
2024-03-31 23:01:58 +08:00
Weixuan Fu 95d32bd6f7 build new pr 2024-03-31 22:50:16 +08:00
Weixuan Fu 2d949971d7 Merge branch 'dev' into beta 2024-03-31 22:48:23 +08:00
Weixuan Fu 1aed7674ed force unlock method to fix reboot issue, better perf 2024-03-31 22:48:13 +08:00
Weixuan Fu d70a0afac5 buikd 2024-03-30 03:45:50 +08:00
Weixuan Fu ebeae00012 build 2024-03-30 00:55:32 +08:00
Weixuan Fu fe06783557 Merge pull request #328 from 11cafe/fix-reboot
Fix reboot
2024-03-30 00:54:22 +08:00
Weixuan Fu db4a896632 method2-with lock open shelf each operation, may slow down perf 2024-03-30 00:07:15 +08:00
Weixuan Fu 1d45ea7f15 method1-force remove stale lock if shelf open throws 2024-03-30 00:06:09 +08:00
Weixuan Fu 61a899a2bf Merge pull request #326 from 11cafe/beta
fix changelogs table savedb() slow ui
2024-03-29 00:02:35 +08:00
Weixuan Fu f86417afcf Merge branch 'dev' into beta 2024-03-29 00:00:10 +08:00
Weixuan Fu dcf41eccd2 fix gallery carousel height, fix spotlight up/down arrow
Beta
2024-03-28 22:37:25 +08:00
Weixuan Fu 68bc061d9d Merge branch 'dev' into beta 2024-03-28 22:35:27 +08:00
Weixuan Fu c18a6f8d72 fix gallery carousel smaller and disppears when more rows of gallery image - Merge branch 'dev' into beta 2024-03-28 22:25:12 +08:00
Weixuan Fu 2e1853574a Update README.md 2024-03-28 22:17:16 +08:00
Weixuan Fu 39d7515f25 fix: setupGithooks not found Merge pull request #318 from Volankey/patch-1
fix: setupGithooks not found
2024-03-28 22:07:09 +08:00
Weixuan Fu 4a17c57741 build fix shortcut listener block original keybiindings like arrow u
Beta
2024-03-28 22:00:13 +08:00
Weixuan Fu 3f1bf33a9e build fix shortcut listener block original keybiindings like arrow up/down,… 2024-03-28 21:58:23 +08:00
Volankey 89c84cfce7 fix: setupGithooks not found 2024-03-28 15:26:47 +08:00
Weixuan Fu 5abf796cf0 Merge pull request #317 from 11cafe/beta
build fix autosave locked files
2024-03-28 13:49:48 +08:00
Weixuan Fu 3a98031a89 build fix autosave locked files 2024-03-28 13:49:01 +08:00
Weixuan Fu 5989874857 Merge pull request #316 from 11cafe/dev
fix autosave even when save lock is on
2024-03-28 13:48:23 +08:00
Weixuan Fu 2c1a3be4ab fix build 2024-03-28 00:16:51 +08:00
Weixuan Fu 0053caf0ad Merge pull request #314 from 11cafe/beta
add hide thumbnail image option setting, createFlow avoid overwriting deps
2024-03-28 00:15:54 +08:00
Weixuan Fu 816b4bbef6 build 2024-03-28 00:13:04 +08:00
Weixuan Fu bbb483b27b add build files 2024-03-27 23:30:24 +08:00
Weixuan Fu 2b5691b84a Update README.md 2024-03-27 23:01:10 +08:00
Weixuan Fu 6ad9609325 Update README.md 2024-03-27 22:45:51 +08:00
102 changed files with 2217 additions and 2372 deletions
+20
View File
@@ -0,0 +1,20 @@
name: Publish to Comfy registry
on:
workflow_dispatch:
push:
branches:
- main
paths:
- "pyproject.toml"
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Publish Custom Node
uses: Comfy-Org/publish-node-action@main
with:
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} ## Add your own personal access token to your Github Repository secrets and reference it here.
+1
View File
@@ -11,6 +11,7 @@ pnpm-debug.log*
lerna-debug.log* lerna-debug.log*
ui/node_modules ui/node_modules
# ui/src/utils/encryptUtils.ts
db db
dist-ssr dist-ssr
*.local *.local
+21 -674
View File
@@ -1,674 +1,21 @@
GNU GENERAL PUBLIC LICENSE MIT License
Version 3, 29 June 2007
Copyright (c) 2024 11cafe
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies Permission is hereby granted, free of charge, to any person obtaining a copy
of this license document, but changing it is not allowed. of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
Preamble to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
The GNU General Public License is a free, copyleft license for furnished to do so, subject to the following conditions:
software and other kinds of works.
The above copyright notice and this permission notice shall be included in all
The licenses for most software and other practical works are designed copies or substantial portions of the Software.
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
share and change all versions of a program--to make sure it remains free IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
software for all its users. We, the Free Software Foundation, use the FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
GNU General Public License for most of our software; it applies also to AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
any other work released this way by its authors. You can apply it to LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
your programs, too. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+24 -42
View File
@@ -1,15 +1,10 @@
# ☕️ ComfyUI Workspace Manager - Comfyspace # ☕️ ComfyUI Workspace Manager - Comfyspace
**[2025-4-16] 📣Hi since ComfyUI frontend has built-in workspace management feature now, this plugin becomes obsolte and will not be maintained anymore. Thanks everyone for supporting comfyui-workspace-manager! Sorry that this cannot continue anymore.**
A ComfyUI workflow and model manager extension to **organize and manage all your workflows, models and generated images in one place**. Seamlessly switch between workflows, track version history and image generation history, 1 click install models from Civit ai, browse/update your installed models A ComfyUI workflow and model manager extension to **organize and manage all your workflows, models and generated images in one place**. Seamlessly switch between workflows, track version history and image generation history, 1 click install models from Civit ai, browse/update your installed models
If you have questions or suggestions, please [join our Discord](https://discord.gg/HHvfEurv2Z)!
[New!] we're building a comfyui custom nodes library wiki like Pypi: https://www.nodecafe.org/
welcome any feedbacks!
🔴‼️ If you updated or cloned this repo between March 14-17, 2024, please update it again to latest verison, there were some bugs that may cause you lose changes in Auto Save mode.
‼️ [3-23-2024]**search and install models from civitai is not working in previous versions**, because civitai changed something in their api. **Please update to the latest version** if you are seeing blank screen in Install Models dialog
<img width="610" alt="Screenshot 2024-03-08 at 6 41 18 PM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/30455eb1-3d12-4930-bb81-28b33148fbaa"> <img width="610" alt="Screenshot 2024-03-08 at 6 41 18 PM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/30455eb1-3d12-4930-bb81-28b33148fbaa">
@@ -21,15 +16,26 @@ Simply search for “ComfyUI Workspace Manager”, install, and restart ComfyUI.
### [Option 2] via git ### [Option 2] via git
Like any other custom node installation, in your ComfyUI root folder Like any other custom node installation, in your ComfyUI root folder run command and restart your ComfyUI.
``` ```
cd custom_nodes && git clone https://github.com/11cafe/comfyui-workspace-manager.git cd custom_nodes && git clone https://github.com/11cafe/comfyui-workspace-manager.git
``` ```
and restart your ComfyUI.
It is recommended to do git clone than downloading zip folder, because you can get latest updates by `git pull`! Please upgrade to V2 asap, you should see an **unicorn🦄** here instead of ☕️ (V1). I will stop supporting V1 soon.
<img width="136" alt="Screenshot 2024-05-31 at 5 39 58 PM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/f52a83f2-4679-4a40-95ed-e75584516ec5">
Recommanded settings for V2 (Do not use these settings if you are on V1):
- Enable two way sync (‼️ Will stop supporting non-two-way sync mode starting next version)
- Make sure My Workspace Save Directory is valid path
<img width="202" alt="Screenshot 2024-05-30 at 6 34 39 PM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/67020966-c190-48cb-bffc-b715449d5c99">
<img width="377" alt="335530039-10002a3f-ea2f-4bd1-8597-0ae1443d9851" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/6001a7f1-93f2-48ef-86c6-95c9560030ef">
## Features ## Features
@@ -37,11 +43,11 @@ It is recommended to do git clone than downloading zip folder, because you can g
- 🔁Switch between different workflows easily. 1click open workflow in multiple browser tabs. - 🔁Switch between different workflows easily. 1click open workflow in multiple browser tabs.
- 🤏**Drag and drop** to insert subworkflows into current flow. - 🤏**Drag and drop** to insert subworkflows into current flow.
- 🗂️Organize workflows with folders, tags. - 🗂️Organize workflows with folders (tags are deprecated, please use folders to organize)
- 📂Save and sync all your workflows in a local folder (by default under `/ComfyUI/my_workflows` customize in Settings) - 📂Save and sync all your workflows in a local folder (by default under `/ComfyUI/my_workflows` customize in Settings)
- **Save workflow by pressing the 💾 button, or ⌨Shift+S shortcut** (customize in Settings). - **Save workflow by pressing the 💾 button, or ⌨Shift+S shortcut** (customize in Settings).
- Every time you save, it will create a new record in **Version History**. You can easily revert to any version. - Every time you save, it will create a new record in **Version History**. You can easily revert to any version.
- **Enable/disable autosave workflow** (please disable autosave if you are experiencing UI lagging) - **Enable/disable autosave workflow** (please disable autosave if you are experiencing UI slowing)
- You can move files using OS File Explorer and it will be **two-way synced** with workspace. - You can move files using OS File Explorer and it will be **two-way synced** with workspace.
- 🕛**Version control** of workflow, create/switch versions - 🕛**Version control** of workflow, create/switch versions
- Bulk import workflows into your workspace - Bulk import workflows into your workspace
@@ -63,31 +69,11 @@ Recommend using Chrome browser for the best experience. Safari doesn't work well
[中文版教程](https://www.uisdc.com/workspace-manager) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [Roadmap](https://github.com/orgs/11cafe/projects/1/views/1) [中文版教程](https://www.uisdc.com/workspace-manager) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; [Roadmap](https://github.com/orgs/11cafe/projects/1/views/1)
# <<<<<<< HEAD ## Updates
🚧🔴 Drag and drop to insert subworkflow is not working. I have debugged for many hours but just can't make it work perfectly. If anyone is interested here is the code: **🦄v2.0 Two-way sync with local folder, models manager support external models path like Automatic1111, cloud sync workflows**
https://github.com/11cafe/comfyui-workspace-manager/blob/d2d2f0c1f1ace35236e73fa5074e9feb83342773/ui/src/utils.tsx#L192
I would really appreciate it if someone can find a solution to insert a subworkflow to current canvas given the json object. v2.0 demo: https://youtu.be/7Hht_BMe844
### 🦄v2.0 beta: Two-way sync with local folder, select model install path, cloud sync workflows
> > > > > > > dev
**🦩v2.1 New gallery coming soon! Inspect image metadata, search image by prompt, model/lora used**
<img width="700" alt="Screenshot 2024-03-23 at 12 58 38 AM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/5bac9793-7491-4131-b850-037094d03823">
Control+P quick spotlight search (like VSCode)
<img width="500" alt="Screenshot 2024-03-27 at 3 49 35 PM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/47c14904-180c-4c52-a644-223d0936c9fa">
**🦄v2.0 Two-way sync with local folder, select model install path, cloud sync workflows**
- Two-way sync with selected local folder so you can move files using File Explore or Finder to sync them with workspace!
- **Models manager support external models path like Automatic1111**! Choose models downloading folder from added external paths.
- Add models thumbnails image by putting a image file with the same name in models folder like A1111
- One click sharing to cloud to backup your workflows to cloud
v2.0 demo: https://youtu.be/7Hht_BMe844
**v1.7 ComfyUI model manager, view your installed models, install models from civit ai, open workflow in multiple browser tabs** **v1.7 ComfyUI model manager, view your installed models, install models from civit ai, open workflow in multiple browser tabs**
@@ -97,7 +83,7 @@ Control+P quick spotlight search (like VSCode)
<img width="200" alt="Screenshot 2024-01-23 at 12 26 56 AM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/d29d0831-a15a-4597-acf6-facee4dbc76e"> <img width="200" alt="Screenshot 2024-01-23 at 12 26 56 AM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/d29d0831-a15a-4597-acf6-facee4dbc76e">
<img width="460" alt="gallery" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/2b7886c9-2d4a-46c6-adac-429720f74f11"> ## Usage
switch between flows: switch between flows:
@@ -111,10 +97,6 @@ Bulk import flows:
<img width="400" alt="Screenshot 2024-01-02 at 10 22 45 PM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/884c8852-73c7-41d6-9179-7fb1fcea9d04"> <img width="400" alt="Screenshot 2024-01-02 at 10 22 45 PM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/884c8852-73c7-41d6-9179-7fb1fcea9d04">
add tags to flow:
<img width="400" alt="Screenshot 2023-12-13 at 1 54 04 AM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/6bf4d22b-f52a-4d23-8882-4a31162616f3">
Workflow operations: Manual Save, Download, Discard unsaved changes: Workflow operations: Manual Save, Download, Discard unsaved changes:
<img width="500" alt="Screenshot 2023-12-29 at 9 59 57 PM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/88c82672-ebf2-4feb-bf5b-74b447843c2c"> <img width="500" alt="Screenshot 2023-12-29 at 9 59 57 PM" src="https://github.com/11cafe/comfyui-workspace-manager/assets/18367033/88c82672-ebf2-4feb-bf5b-74b447843c2c">
+19 -51
View File
@@ -5,24 +5,26 @@ import folder_paths
import shutil import shutil
import os import os
import sys import sys
import subprocess # don't remove this import subprocess
from urllib.parse import urlparse
import subprocess import subprocess
import os import os
import json import json
from .service.model_manager.model_installer import download_url_with_wget
from .service.model_manager.model_list import get_model_list
from .service.media_service import * from .service.media_service import *
from .service.file_sync_service import * from .service.file_sync_service import *
from .service.db_service import get_my_workflows_dir
from .service.node_service import * from .service.node_service import *
from .service.setting_service import *
from .service.model_manager.model_installer import *
try:
from send2trash import send2trash
except ImportError:
send2trash = None
WEB_DIRECTORY = "entry" WEB_DIRECTORY = "entry"
NODE_CLASS_MAPPINGS = {} NODE_CLASS_MAPPINGS = {}
__all__ = ['NODE_CLASS_MAPPINGS'] __all__ = ['NODE_CLASS_MAPPINGS']
version = "V1.0.0" version = "V2.1.0"
print(f"### Loading: Workspace Manager ({version})") print(f"🦄🦄Loading: Workspace Manager ({version})")
workspace_path = os.path.join(os.path.dirname(__file__)) workspace_path = os.path.join(os.path.dirname(__file__))
comfy_path = os.path.dirname(folder_paths.__file__) comfy_path = os.path.dirname(folder_paths.__file__)
db_dir_path = os.path.join(workspace_path, "db") db_dir_path = os.path.join(workspace_path, "db")
@@ -32,39 +34,8 @@ if os.path.exists(dist_path):
server.PromptServer.instance.app.add_routes([ server.PromptServer.instance.app.add_routes([
web.static('/workspace_web/', dist_path), web.static('/workspace_web/', dist_path),
]) ])
else:
BACKUP_DIR = os.path.join(workspace_path, "backup") print(f"🦄🦄🔴🔴Error: Web directory not found: {dist_path}")
MAX_BACKUP_FILES = 20
@server.PromptServer.instance.routes.post("/workspace/list_backup")
async def list_backup(request):
try:
data = await request.json()
dir_path = os.path.join(BACKUP_DIR, data.get('dir'))
# List all files in the directory
files = os.listdir(dir_path)
# Filter out .json files and sort them by filename (which starts with Unix timestamp)
json_files = sorted(
[file for file in files if file.endswith('.json')],
key=lambda x: x, # Assuming the format is 'timestamp_filename.json'
reverse=True
)
# Select the 10 most recent files
recent_json_files = json_files[:10]
# Read the contents of each JSON file
file_contents = []
for file in recent_json_files:
with open(os.path.join(dir_path, file), 'r') as f:
content = json.load(f)
file_contents.append({"fileName": file, "jsonStr": content})
return web.Response(text=json.dumps(file_contents), content_type='application/json')
except Exception as e:
return web.Response(text=json.dumps({"error": str(e)}), status=500)
@server.PromptServer.instance.routes.post("/workspace/get_system_dir") @server.PromptServer.instance.routes.post("/workspace/get_system_dir")
async def get_system_dir(request): async def get_system_dir(request):
@@ -112,31 +83,28 @@ async def update_file(request):
await asyncio.to_thread(write_json_to_file, json_str) await asyncio.to_thread(write_json_to_file, json_str)
return web.Response(text="File updated successfully") return web.Response(text="File updated successfully")
@server.PromptServer.instance.routes.post("/workspace/delete_file") @server.PromptServer.instance.routes.post("/workspace/delete_file")
async def delete_file(request): async def delete_file(request):
data = await request.json() data = await request.json()
file_path = data['file_path'] file_path = data['file_path']
delete_empty_folder = data['deleteEmptyFolder']
def sync_delete_file(file_path, delete_empty_folder): def sync_delete_file(file_path):
my_workflows_dir = get_my_workflows_dir() my_workflows_dir = get_my_workflows_dir()
full_path = os.path.join(my_workflows_dir, file_path) full_path = os.path.join(my_workflows_dir, file_path)
if os.path.exists(full_path): if os.path.exists(full_path):
os.remove(full_path) if send2trash:
directory = os.path.dirname(full_path) send2trash(full_path)
if delete_empty_folder and not os.listdir(directory):
# If the directory is empty, remove the directory
os.rmdir(directory)
return "File and empty directory deleted successfully"
else: else:
return "File deleted successfully" os.remove(full_path)
print("❌⛔️send2trash is not available. Deleting file permanently. Please `pip install send2trash`")
return "File deleted successfully"
else: else:
return "File not found" return "File not found"
# Run the synchronous file operation in a separate thread # Run the synchronous file operation in a separate thread
response_text = await asyncio.to_thread(sync_delete_file, file_path, delete_empty_folder) response_text = await asyncio.to_thread(sync_delete_file, file_path)
if response_text == "File not found": if response_text == "File not found":
return web.Response(text=response_text, status=404) return web.Response(text=response_text, status=404)
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
import{r as l,N as r}from"./input.js";import{W as S,ag as w,w as p,E as f,ah as _,ai as C}from"./App-qo42s2ji.js";import{u as b}from"./useDebounceFn-ld478fd0.js";function R(){const{isDirty:d,setIsDirty:h,setRoute:g,saveCurWorkflow:v,setCurFlowIDAndName:k}=l.useContext(S),E=l.useRef(d);l.useEffect(()=>{E.current=d},[d]),l.useEffect(()=>{const c=e=>{var n;if(document.visibilityState==="hidden")return;const t=C(e);if(t)switch(t===f.openSpotlightSearch&&e.preventDefault(),window.dispatchEvent(new CustomEvent(_,{detail:{shortcutType:t}})),t){case f.SAVE:v();break;case f.SAVE_AS:g("saveAsModal");break;case f.openSpotlightSearch:g("spotlightSearch");break}else(n=e.target)!=null&&n.matches("input, textarea")&&Object.keys(r.canvas.selected_nodes??{}).length&&m()},u=async()=>{var t,n,a,i;if(!((t=r)!=null&&t.graph)){console.error("🦄 Error in workspace manager! app.graph is not available in restoreCurWorkflow()");return}const e=(a=(n=r.graph.extra)==null?void 0:n[w])==null?void 0:a.id;if(e){const s=await((i=p)==null?void 0:i.get(e));s&&k(s),!(s!=null&&s.saveLock)&&s&&s.json!==JSON.stringify(r.graph.serialize())&&h(!0)}},o=r.graph.onConfigure;return r.graph.onConfigure=function(){o==null||o.apply(this,arguments),setTimeout(()=>{var t,n,a,i;const e=(n=(t=r.graph.extra)==null?void 0:t[w])==null?void 0:n.id;(e==null||e!=((i=(a=p)==null?void 0:a.curWorkflow)==null?void 0:i.id))&&k(null)},500)},document.addEventListener("click",e=>{Object.keys(r.canvas.selected_nodes??{}).length&&(r.canvas.node_over!=null||r.canvas.node_capturing_input!=null||r.canvas.node_widget!=null)&&m()}),document.addEventListener("keydown",c),u(),()=>{document.removeEventListener("keydown",c)}},[]);const y=async()=>{var u,o,e,t;if((o=(u=p)==null?void 0:u.curWorkflow)!=null&&o.saveLock||E.current)return;const c=r.graph.serialize();JSON.stringify(c)!==((t=(e=p)==null?void 0:e.curWorkflow)==null?void 0:t.json)&&h(!0)},[m,D]=b(y,900);return null}export{R as default};
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{d as a}from"./App-qo42s2ji.js";var p=a("copy","IconCopy",[["path",{d:"M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z",key:"svg-0"}],["path",{d:"M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1",key:"svg-1"}]]);export{p as I};
+1
View File
@@ -0,0 +1 @@
import{d as a}from"./App-qo42s2ji.js";var r=a("search","IconSearch",[["path",{d:"M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0",key:"svg-0"}],["path",{d:"M21 21l-6 -6",key:"svg-1"}]]);export{r as I};
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
.dragPanelIcon{display:none!important}.workspaceManagerPanel:hover .dragPanelIcon{display:block!important}
@@ -0,0 +1 @@
.drag-model-manager-top-bar-icon{visibility:hidden!important}.model-manager-top-bar:hover .drag-model-manager-top-bar-icon{visibility:visible!important}
+1
View File
@@ -0,0 +1 @@
import{f as x,j as l,g as i,e as w,k as C,o as E,l as I,r as f,a5 as P}from"./input.js";import{ab as z}from"./App-qo42s2ji.js";var v=x(function(o,s){const{children:t,placeholder:n,className:r,...a}=o;return l.jsxs(i.select,{...a,ref:s,className:w("chakra-select",r),children:[n&&l.jsx("option",{value:"",children:n}),t]})});v.displayName="SelectField";function F(e,o){const s={},t={};for(const[n,r]of Object.entries(e))o.includes(n)?s[n]=r:t[n]=r;return[s,t]}var H=x((e,o)=>{var s;const t=C("Select",e),{rootProps:n,placeholder:r,icon:a,color:c,height:_,h:d,minH:h,minHeight:y,iconColor:p,iconSize:u,...j}=E(e),[g,N]=F(j,P),m=z(N),k={width:"100%",height:"fit-content",position:"relative",color:c},b={paddingEnd:"2rem",...t.field,_focus:{zIndex:"unset",...(s=t.field)==null?void 0:s._focus}};return l.jsxs(i.div,{className:"chakra-select__wrapper",__css:k,...g,...n,children:[l.jsx(v,{ref:o,height:d??_,minH:h??y,placeholder:r,...m,__css:b,children:e.children}),l.jsx(S,{"data-disabled":I(m.disabled),...(p||c)&&{color:p||c},__css:t.icon,...u&&{fontSize:u},children:a})]})});H.displayName="Select";var M=e=>l.jsx("svg",{viewBox:"0 0 24 24",...e,children:l.jsx("path",{fill:"currentColor",d:"M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"})}),R=i("div",{baseStyle:{position:"absolute",display:"inline-flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",top:"50%",transform:"translateY(-50%)"}}),S=e=>{const{children:o=l.jsx(M,{}),...s}=e,t=f.cloneElement(o,{role:"presentation",className:"chakra-select__icon",focusable:!1,"aria-hidden":!0,style:{width:"1em",height:"1em",color:"currentColor"}});return l.jsx(R,{...s,className:"chakra-select__icon-wrapper",children:f.isValidElement(o)?t:null})};S.displayName="SelectIcon";export{H as S};
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{b as D,r as h,j as t,g as i,a2 as v,f as j,k as T,o as B,H as E,e as $}from"./input.js";import{u as z}from"./chunk-7D6N5TE5-rpRnbuGR.js";var[Z,F]=D({name:"CheckboxGroupContext",strict:!1});function M(o){const[s,n]=h.useState(o),[e,r]=h.useState(!1);return o!==s&&(r(!0),n(o)),e}function W(o){return t.jsx(i.svg,{width:"1.2em",viewBox:"0 0 12 10",style:{fill:"none",strokeWidth:2,stroke:"currentColor",strokeDasharray:16},...o,children:t.jsx("polyline",{points:"1.5 6 4.5 9 10.5 1"})})}function X(o){return t.jsx(i.svg,{width:"1.2em",viewBox:"0 0 24 24",style:{stroke:"currentColor",strokeWidth:4},...o,children:t.jsx("line",{x1:"21",x2:"3",y1:"12",y2:"12"})})}function H(o){const{isIndeterminate:s,isChecked:n,...e}=o,r=s?X:W;return n||s?t.jsx(i.div,{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:t.jsx(r,{...e})}):null}var L={display:"inline-flex",alignItems:"center",justifyContent:"center",verticalAlign:"top",userSelect:"none",flexShrink:0},O={cursor:"pointer",display:"inline-flex",alignItems:"center",verticalAlign:"top",position:"relative"},q=v({from:{opacity:0,strokeDashoffset:16,transform:"scale(0.95)"},to:{opacity:1,strokeDashoffset:0,transform:"scale(1)"}}),J=v({from:{opacity:0},to:{opacity:1}}),K=v({from:{transform:"scaleX(0.65)"},to:{transform:"scaleX(1)"}}),Q=j(function(s,n){const e=F(),r={...e,...s},a=T("Checkbox",r),c=B(s),{spacing:x="0.5rem",className:C,children:m,iconColor:u,iconSize:d,icon:k=t.jsx(H,{}),isChecked:f,isDisabled:g=e==null?void 0:e.isDisabled,onChange:p,inputProps:w,..._}=c;let y=f;e!=null&&e.value&&c.value&&(y=e.value.includes(c.value));let b=p;e!=null&&e.onChange&&c.value&&(b=E(e.onChange,p));const{state:l,getInputProps:A,getCheckboxProps:S,getLabelProps:G,getRootProps:P}=z({..._,isDisabled:g,isChecked:y,onChange:b}),I=M(l.isChecked),R=h.useMemo(()=>({animation:I?l.isIndeterminate?`${J} 20ms linear, ${K} 200ms linear`:`${q} 200ms linear`:void 0,fontSize:d,color:u,...a.icon}),[u,d,I,l.isIndeterminate,a.icon]),N=h.cloneElement(k,{__css:R,isIndeterminate:l.isIndeterminate,isChecked:l.isChecked});return t.jsxs(i.label,{__css:{...O,...a.container},className:$("chakra-checkbox",C),...P(),children:[t.jsx("input",{className:"chakra-checkbox__input",...A(w,n)}),t.jsx(i.span,{__css:{...L,...a.control},className:"chakra-checkbox__control",...S(),children:N}),m&&t.jsx(i.span,{className:"chakra-checkbox__label",...G(),__css:{marginStart:x,...a.label},children:m})]})});Q.displayName="Checkbox";var U=j(function(s,n){const{templateAreas:e,gap:r,rowGap:a,columnGap:c,column:x,row:C,autoFlow:m,autoRows:u,templateRows:d,autoColumns:k,templateColumns:f,...g}=s,p={display:"grid",gridTemplateAreas:e,gridGap:r,gridRowGap:a,gridColumnGap:c,gridAutoColumns:k,gridColumn:x,gridRow:C,gridAutoFlow:m,gridAutoRows:u,gridTemplateRows:d,gridTemplateColumns:f};return t.jsx(i.div,{ref:n,__css:p,...g})});U.displayName="Grid";export{Q as C,U as G};
+1
View File
@@ -0,0 +1 @@
import{f as t}from"./App-qo42s2ji.js";import{f as o,j as s}from"./input.js";var e=o((a,r)=>s.jsx(t,{align:"center",...a,direction:"column",ref:r}));e.displayName="VStack";export{e as V};
+1
View File
@@ -0,0 +1 @@
import{f as l,n as f,o as h,j as e,g as n,e as m,k as y,r as o}from"./input.js";import{u as w}from"./chunk-7D6N5TE5-rpRnbuGR.js";var N=l(function(a,i){const s=f("Link",a),{className:c,isExternal:t,...r}=h(a);return e.jsx(n.a,{target:t?"_blank":void 0,rel:t?"noopener":void 0,ref:i,className:m("chakra-link",c),...r,__css:s})});N.displayName="Link";var j=l(function(a,i){const s=y("Switch",a),{spacing:c="0.5rem",children:t,...r}=h(a),{getIndicatorProps:u,getInputProps:p,getCheckboxProps:x,getRootProps:_,getLabelProps:g}=w(r),b=o.useMemo(()=>({display:"inline-block",position:"relative",verticalAlign:"middle",lineHeight:0,...s.container}),[s.container]),S=o.useMemo(()=>({display:"inline-flex",flexShrink:0,justifyContent:"flex-start",boxSizing:"content-box",cursor:"pointer",...s.track}),[s.track]),d=o.useMemo(()=>({userSelect:"none",marginStart:c,...s.label}),[c,s.label]);return e.jsxs(n.label,{..._(),className:m("chakra-switch",a.className),__css:b,children:[e.jsx("input",{className:"chakra-switch__input",...p({},i)}),e.jsx(n.span,{...x(),className:"chakra-switch__track",__css:S,children:e.jsx(n.span,{__css:s.thumb,className:"chakra-switch__thumb",...u()})}),t&&e.jsx(n.span,{className:"chakra-switch__label",...g(),__css:d,children:t})]})});j.displayName="Switch";export{N as L,j as S};
+1
View File
@@ -0,0 +1 @@
import{h as m}from"./App-qo42s2ji.js";const r="WORKSPACE_CIVIT_API_KEY_STORAGE_KEY";function h(){return localStorage.getItem(r)}function g(e){localStorage.setItem(r,e)}function v(e){return`https://civitai.com/api/download/models/${e}`}async function w(e){var s,a,n;try{const l=`https://civitai.com/api/v1/model-versions/by-hash/${e}`,t=await(await fetch(l)).json();let i;if(await((s=m)==null?void 0:s.getSetting("showNsfwModelThumbnail"))===!0)i=(n=(a=t==null?void 0:t.images)==null?void 0:a[0])==null?void 0:n.url;else if(!t.model.nsfw){const o=t.images.find(c=>c.nsfwLevel==1);i=o==null?void 0:o.url}return{modelName:t.model.name,civitModelID:String(t.modelId),civitModelVersionID:String(t.id),imageUrl:i??void 0}}catch{return{}}}export{v as a,w as f,h as g,g as s};
+688
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
import{r}from"./input.js";function a(u,c){const e=r.useRef(0),t=r.useCallback(()=>{e.current!==null&&(clearTimeout(e.current),e.current=0)},[]),n=r.useCallback((...o)=>{t(),e.current=setTimeout(()=>u(...o),c)},[u,c,t]);return r.useEffect(()=>()=>{t()},[]),[n,t]}export{a as u};
+5 -26
View File
@@ -1,27 +1,6 @@
const targetNode = document.body; //@ts-ignore
import { api } from "../../scripts/api.js";
// Options for the observer (which mutations to observe) setTimeout(() => {
const config = { childList: true, subtree: true }; import(api.api_base + "/workspace_web/input.js");
const api_base = window.location.pathname.split("/").slice(0, -1).join("/"); }, 500);
// @ts-ignore
const callback = function (mutationsList, observer) {
for (const mutation of mutationsList) {
if (mutation.type === "childList") {
// @ts-ignore
mutation.addedNodes.forEach((node) => {
if (node.nodeName === "CANVAS") {
// @ts-ignore
import(api_base + "/workspace_web/input.js");
observer.disconnect();
}
});
}
}
};
// Create an instance of the MutationObserver
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
+13
View File
@@ -0,0 +1,13 @@
[project]
name = "comfyui-workspace-manager"
description = "A ComfyUI custom node for project management to centralize the management of all your workflows in one place. Seamlessly switch between workflows, create and update them within a single workspace, like Google Docs."
version = "1.0.0"
license = { file = "LICENSE" }
[project.urls]
Repository = "https://github.com/11cafe/comfyui-workspace-manager"
[tool.comfy]
PublisherId = "weixuan11"
DisplayName = "comfyui-workspace-manager"
Icon = ""
+1
View File
@@ -0,0 +1 @@
send2trash
-19
View File
@@ -51,22 +51,3 @@ async def get_workspace(request):
table = request.query.get('table') table = request.query.get('table')
data = await asyncio.to_thread(read_table, table) data = await asyncio.to_thread(read_table, table)
return web.json_response(data) return web.json_response(data)
def get_my_workflows_dir():
data = read_table('userSettings')
if (data):
records = json.loads(data)
if DEFAULT_USER in records and 'myWorkflowsDir' in records[DEFAULT_USER]:
curDir = records[DEFAULT_USER]['myWorkflowsDir']
elif 'myWorkflowsDir' in records:
curDir = records['myWorkflowsDir']
# this is to be compatible of a bug that a dict is stored in userSettings.myWorkflowsDir
# should not be needed once all users refresh their settings
if not isinstance(curDir, str):
curDir = curDir.get('path', None)
if curDir and os.path.exists(curDir):
return curDir
return os.path.join(comfy_path, 'my_workflows')
+9 -4
View File
@@ -1,8 +1,6 @@
import asyncio import asyncio
import folder_paths import folder_paths
from datetime import datetime from datetime import datetime
import platform
import tempfile
import server import server
import os import os
from aiohttp import web from aiohttp import web
@@ -136,7 +134,11 @@ def read_workflow_file(path, id):
def check_and_update_workflow_id(file_path, seen_ids): def check_and_update_workflow_id(file_path, seen_ids):
with open(file_path, "r", encoding="utf-8") as f: with open(file_path, "r", encoding="utf-8") as f:
json_data = json.load(f) try:
json_data = json.load(f)
except json.JSONDecodeError as e:
print(f"Error reading JSON from {file_path}: {e}")
return
if ( if (
"extra" in json_data "extra" in json_data
and "workspace_info" in json_data["extra"] and "workspace_info" in json_data["extra"]
@@ -172,7 +174,10 @@ def dedupe_workflow_ids():
if not file.endswith(".json"): if not file.endswith(".json"):
continue continue
file_path = os.path.join(root, file) file_path = os.path.join(root, file)
check_and_update_workflow_id(file_path, seen_ids) try:
check_and_update_workflow_id(file_path, seen_ids)
except Exception as e:
print(f"Error while processing file {file_path}: {e}")
@server.PromptServer.instance.routes.get('/workspace/deduplicate_workflow_ids') @server.PromptServer.instance.routes.get('/workspace/deduplicate_workflow_ids')
async def deduplicate_workflow_ids(request): async def deduplicate_workflow_ids(request):
+5 -1
View File
@@ -6,10 +6,11 @@ from aiohttp import FormData, web, ClientSession
import folder_paths import folder_paths
import os import os
from .model_manager.model_preview import get_thumbnail_for_image_file from .model_manager.model_preview import get_thumbnail_for_image_file
from .setting_service import get_settings
image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'] image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp']
video_extensions = ['.mp4', '.mov', '.avi', '.webm', '.mkv'] video_extensions = ['.mp4', '.mov', '.avi', '.webm', '.mkv']
API_URL = 'https://www.nodecafe.org/api/image/upload'
def view_media(filename, isPreview = False, isInput = False): def view_media(filename, isPreview = False, isInput = False):
if not filename: if not filename:
return web.Response(status=404) return web.Response(status=404)
@@ -62,6 +63,9 @@ async def view_file(request):
@server.PromptServer.instance.routes.post("/workspace/upload_image") # Handle POST requests @server.PromptServer.instance.routes.post("/workspace/upload_image") # Handle POST requests
async def upload_image_handler(request): async def upload_image_handler(request):
settings = get_settings()
cloudHost = settings.get("cloudHost", 'https://www.nodecafe.co')
API_URL = cloudHost + '/api/image/upload'
data = await request.json() data = await request.json()
image_paths = data.get("images") image_paths = data.get("images")
if not image_paths: if not image_paths:
+1 -1
View File
@@ -18,7 +18,7 @@ if not os.path.exists(FILE_HASH_DICT_FOLDER_PATH):
os.makedirs(FILE_HASH_DICT_FOLDER_PATH) os.makedirs(FILE_HASH_DICT_FOLDER_PATH)
# Early open shelve for better performance # Early open shelve for better performance
with shelve.open(FILE_HASH_DICT_PATH) as file_hash_dict: with shelve.open(FILE_HASH_DICT_PATH) as file_hash_dict_early_open:
print(f"Workspace manager - Openning file hash dict") print(f"Workspace manager - Openning file hash dict")
file_list = [] file_list = []
+21 -4
View File
@@ -3,11 +3,16 @@ from aiohttp import web
import asyncio import asyncio
import json import json
import os import os
import glob import traceback
import logging
from threading import Lock from threading import Lock
import server import server
import uuid import uuid
from .db_service import get_my_workflows_dir from .setting_service import get_my_workflows_dir
@server.PromptServer.instance.routes.get('/workspace/get_os')
async def scan_my_workflows_files(request):
return web.Response(text= json.dumps({'os': platform.system()}), content_type='application/json')
@server.PromptServer.instance.routes.post('/workspace/file/scan_my_workflows_folder') @server.PromptServer.instance.routes.post('/workspace/file/scan_my_workflows_folder')
async def scan_my_workflows_files(request): async def scan_my_workflows_files(request):
@@ -33,6 +38,7 @@ def folder_handle(path, recursive, metaInfoOnly, fileList=None):
createTime, updateTime = getFileCreateTime(item_path) createTime, updateTime = getFileCreateTime(item_path)
fileList.append({ fileList.append({
'name': item, 'name': item,
'path': item_path,
'type': 'folder', 'type': 'folder',
'createTime': createTime, 'createTime': createTime,
'updateTime': updateTime 'updateTime': updateTime
@@ -41,16 +47,23 @@ def folder_handle(path, recursive, metaInfoOnly, fileList=None):
if recursive: if recursive:
folder_handle(item_path, recursive, metaInfoOnly, fileList) folder_handle(item_path, recursive, metaInfoOnly, fileList)
except Exception as e: except Exception as e:
print(f"Error scanning item {item}: {e}") logging.error(f"Error scan workflow {item_path}: {e}, {traceback.format_exc()}")
return fileList return fileList
def file_handle(name, fileList, file_path, metaInfoOnly): def file_handle(name, fileList, file_path, metaInfoOnly):
with open(file_path, 'r', encoding='utf-8') as f: with open(file_path, 'r', encoding='utf-8') as f:
json_data = json.load(f) json_data = json.load(f)
if not isinstance(json_data, (dict,)):
logging.error(f"{file_path} not in proper ComfyUI workflow format")
return
createTime, updateTime = getFileCreateTime(file_path) createTime, updateTime = getFileCreateTime(file_path)
workspace_info = json_data.get('extra', {}).get('workspace_info', {}) workspace_info = json_data.get('extra', {}).get('workspace_info', {})
workflow_id = workspace_info.get('id', str(uuid.uuid4())) workflow_id = workspace_info.get('id', str(uuid.uuid4()))
saveLock = workspace_info.get('saveLock', False)
cloudID = workspace_info.get('cloudID', None)
coverMediaPath = workspace_info.get('coverMediaPath', None)
# Update JSON data with new ID if needed and write back to file # Update JSON data with new ID if needed and write back to file
if 'id' not in workspace_info: if 'id' not in workspace_info:
if 'extra' not in json_data: if 'extra' not in json_data:
@@ -65,6 +78,10 @@ def file_handle(name, fileList, file_path, metaInfoOnly):
'name': name, 'name': name,
'type': "workflow", 'type': "workflow",
'id': workflow_id, 'id': workflow_id,
'path': file_path,
'saveLock': saveLock,
'cloudID': cloudID,
'coverMediaPath': coverMediaPath,
'createTime': createTime, 'createTime': createTime,
'updateTime': updateTime 'updateTime': updateTime
} }
@@ -83,4 +100,4 @@ def getFileCreateTime(path):
createTime = int(getattr(file_stats, 'st_birthtime', file_stats.st_ctime) * 1000) createTime = int(getattr(file_stats, 'st_birthtime', file_stats.st_ctime) * 1000)
updateTime = int(file_stats.st_mtime * 1000) updateTime = int(file_stats.st_mtime * 1000)
return createTime, updateTime return createTime, updateTime
+60
View File
@@ -0,0 +1,60 @@
import server
import os
import folder_paths
import json
import asyncio
from aiohttp import web
from .db_service import DEFAULT_USER, read_table, db_dir_path
comfy_path = os.path.dirname(folder_paths.__file__)
@server.PromptServer.instance.routes.get("/workspace/get_settings")
def get_settings_endpoint(request):
settings = get_settings()
return web.json_response(text=json.dumps(settings), content_type='application/json')
def get_settings():
new_settings_path = os.path.join(db_dir_path, 'settings.json')
if os.path.exists(new_settings_path):
# to deprecate and remove legacy settings file
# if os.path.exists(f'{db_dir_path}/useSettings.json'):
# os.remove(f'{db_dir_path}/useSettings.json')
with open(new_settings_path, 'r') as file:
return json.load(file)
data = read_table('userSettings')
if (data):
records = json.loads(data)
if DEFAULT_USER in records and 'myWorkflowsDir' in records[DEFAULT_USER]:
return records[DEFAULT_USER]
return None
@server.PromptServer.instance.routes.post("/workspace/save_settings")
async def save_settings(request):
data = await request.json()
json_data = data
file_name = f'{db_dir_path}/settings.json'
# Offload file writing to a separate thread
def write_json_string_to_db(file_name, json_data):
if not os.path.exists(db_dir_path):
os.makedirs(db_dir_path)
# Write the JSON data to the specified file
with open(file_name, 'w') as file:
file.write(json.dumps(json_data, indent=4))
await asyncio.to_thread(write_json_string_to_db, file_name, json_data)
return web.Response(text=f"JSON saved to {file_name}")
def get_my_workflows_dir():
data = get_settings()
if (data):
if 'myWorkflowsDir' in data:
curDir = data['myWorkflowsDir']
# this is to be compatible of a bug that a dict is stored in userSettings.myWorkflowsDir
# should not be needed once all users refresh their settings
if not isinstance(curDir, str):
curDir = curDir.get('path', None)
if curDir and os.path.exists(curDir):
return curDir
return os.path.join(comfy_path, 'my_workflows')
+10 -2
View File
@@ -4,7 +4,11 @@ from aiohttp import web
import os import os
from pathlib import Path from pathlib import Path
import server import server
from .db_service import get_my_workflows_dir from .setting_service import get_my_workflows_dir
try:
from send2trash import send2trash
except ImportError:
send2trash = None
@server.PromptServer.instance.routes.post('/workspace/folder/create') @server.PromptServer.instance.routes.post('/workspace/folder/create')
async def create_folder(request): async def create_folder(request):
@@ -31,7 +35,11 @@ def delete_folder_sync(reqJson):
folder_path = reqJson.get('path') folder_path = reqJson.get('path')
folder_path = os.path.join(get_my_workflows_dir(), folder_path) folder_path = os.path.join(get_my_workflows_dir(), folder_path)
try: try:
shutil.rmtree(folder_path) if send2trash:
send2trash(folder_path)
else:
shutil.rmtree(folder_path)
print("❌⛔️send2trash is not available. Deleting file permanently. Please `pip install send2trash`")
return {"success": True} return {"success": True}
except Exception as e: except Exception as e:
return {"success": False, "error": str(e)} return {"success": False, "error": str(e)}
+1 -1
View File
@@ -8,7 +8,7 @@
"build": "vite build", "build": "vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview", "preview": "vite preview",
"setupGithooks": "node ../scripts/setupGithooks" "setupGithooks": "node ../scripts/setupGitHooks"
}, },
"dependencies": { "dependencies": {
"@chakra-ui/react": "^2.8.2", "@chakra-ui/react": "^2.8.2",
+24 -30
View File
@@ -1,10 +1,22 @@
import { Table } from "./db-tables/WorkspaceDB"; import { Table } from "./db-tables/WorkspaceDB";
import type { ModelsListRespItem } from "./model-manager/types"; import type { ModelsListRespItem } from "./model-manager/types";
import { api } from "./utils/comfyapp";
export function fetchApi(
route: string,
options?: RequestInit,
): Promise<Response> {
if (api == null) {
console.error("api is null!");
throw new Error("api is null!");
}
return api.fetchApi(route, options);
}
export async function getDB(table: Table): Promise<string | undefined> { export async function getDB(table: Table): Promise<string | undefined> {
console.warn("[workspace deprecated] getDB is deprecated", table); console.warn("[workspace deprecated] getDB is deprecated", table);
try { try {
const response = await fetch(`/workspace/get_db?table=${table}`); const response = await fetchApi(`/workspace/get_db?table=${table}`);
if (!response.ok) { if (!response.ok) {
return undefined; return undefined;
} }
@@ -18,7 +30,7 @@ export async function getDB(table: Table): Promise<string | undefined> {
export async function saveDB(table: Table, jsonData: string) { export async function saveDB(table: Table, jsonData: string) {
try { try {
const response = await fetch("/workspace/save_db", { const response = await fetchApi("/workspace/save_db", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -34,7 +46,7 @@ export async function saveDB(table: Table, jsonData: string) {
export async function updateFile(file_path: string, jsonData: string) { export async function updateFile(file_path: string, jsonData: string) {
try { try {
const response = await fetch("/workspace/update_file", { const response = await fetchApi("/workspace/update_file", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -54,7 +66,7 @@ export async function updateFile(file_path: string, jsonData: string) {
export async function deleteFile(file_path: string, deleteEmptyFolder = false) { export async function deleteFile(file_path: string, deleteEmptyFolder = false) {
try { try {
const response = await fetch("/workspace/delete_file", { const response = await fetchApi("/workspace/delete_file", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -71,27 +83,9 @@ export async function deleteFile(file_path: string, deleteEmptyFolder = false) {
} }
} }
export async function listBackup(dir: string) {
try {
const response = await fetch("/workspace/list_backup", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
dir: dir,
}),
});
const result = await response.text();
return result;
} catch (error) {
console.error("Error saving workspace:", error);
}
}
export async function getSystemDir(root?: string) { export async function getSystemDir(root?: string) {
try { try {
const response = await fetch("/workspace/get_system_dir", { const response = await fetchApi("/workspace/get_system_dir", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -109,7 +103,7 @@ export async function getSystemDir(root?: string) {
export async function openWorkflowsFolder() { export async function openWorkflowsFolder() {
try { try {
const response = await fetch("/workspace/open_workflow_file_browser", { const response = await fetchApi("/workspace/open_workflow_file_browser", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -123,7 +117,7 @@ export async function openWorkflowsFolder() {
} }
export async function fetchMyWorkflowsDir() { export async function fetchMyWorkflowsDir() {
const resp = await fetch("/workspace/get_my_workflows_dir"); const resp = await fetchApi("/workspace/get_my_workflows_dir");
const res = (await resp.json()) as { const res = (await resp.json()) as {
path?: string; path?: string;
error?: string; error?: string;
@@ -137,7 +131,7 @@ export async function fetchMyWorkflowsDir() {
export async function getAllModelsList() { export async function getAllModelsList() {
try { try {
const response = await fetch("/model_manager/get_model_list", { const response = await fetchApi("/model_manager/get_model_list", {
method: "GET", method: "GET",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -152,7 +146,7 @@ export async function getAllModelsList() {
export async function getAllFoldersList() { export async function getAllFoldersList() {
try { try {
const response = await fetch("/model_manager/get_folder_list", { const response = await fetchApi("/model_manager/get_folder_list", {
method: "GET", method: "GET",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -167,7 +161,7 @@ export async function getAllFoldersList() {
export async function deleteLocalDiskFolder(folderPath: string) { export async function deleteLocalDiskFolder(folderPath: string) {
try { try {
const response = await fetch("/workspace/delete_folder", { const response = await fetchApi("/workspace/delete_folder", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -185,7 +179,7 @@ export async function deleteLocalDiskFolder(folderPath: string) {
export async function cancelDownload(savePath: string) { export async function cancelDownload(savePath: string) {
try { try {
const response = await fetch("/model_manager/cancel_installation", { const response = await fetchApi("/model_manager/cancel_installation", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -206,7 +200,7 @@ export async function copyFlowsToNewDirectory(
dstDir: string, dstDir: string,
) { ) {
try { try {
const response = await fetch("/workspace/copy_json_files", { const response = await fetchApi("/workspace/copy_json_files", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
+73 -154
View File
@@ -1,15 +1,4 @@
import { import { Suspense, useCallback, useEffect, useRef, useState } from "react";
Suspense,
useCallback,
useEffect,
useRef,
useState,
DragEvent,
} from "react";
// @ts-ignore
import { app } from "/scripts/app.js";
// @ts-ignore
import { api } from "/scripts/api.js";
import { Box, Portal, useToast } from "@chakra-ui/react"; import { Box, Portal, useToast } from "@chakra-ui/react";
import { import {
loadDBs, loadDBs,
@@ -38,12 +27,14 @@ const GalleryModal = React.lazy(() => import("./gallery/GalleryModal"));
import { IconExternalLink } from "@tabler/icons-react"; import { IconExternalLink } from "@tabler/icons-react";
import { DRAWER_Z_INDEX, UPGRADE_TO_2WAY_SYNC_KEY } from "./const"; import { DRAWER_Z_INDEX, UPGRADE_TO_2WAY_SYNC_KEY } from "./const";
import ServerEventListener from "./model-manager/hooks/ServerEventListener"; import ServerEventListener from "./model-manager/hooks/ServerEventListener";
import { nanoid } from "nanoid"; import { Session, WorkspaceRoute } from "./types/types";
import { WorkspaceRoute } from "./types/types";
import { useStateRef } from "./customHooks/useStateRef"; import { useStateRef } from "./customHooks/useStateRef";
import { indexdb } from "./db-tables/indexdb"; import { indexdb } from "./db-tables/indexdb";
import EnableTwowaySyncConfirm from "./settings/EnableTwowaySyncConfirm"; import EnableTwowaySyncConfirm from "./settings/EnableTwowaySyncConfirm";
import { deepJsonDiffCheck } from "./utils/deepJsonDiffCheck"; import { api, app } from "./utils/comfyapp";
import { fetchApi } from "./Api";
import { serverInfo } from "./utils/OsPathUtils";
import { decodeKey } from "./utils/encryptUtils";
export default function App() { export default function App() {
const [curFlowName, setCurFlowName] = useState<string | null>(null); const [curFlowName, setCurFlowName] = useState<string | null>(null);
@@ -51,7 +42,7 @@ export default function App() {
const [loadingDB, setLoadingDB] = useState(true); const [loadingDB, setLoadingDB] = useState(true);
const [flowID, setFlowID] = useState<string | null>(null); const [flowID, setFlowID] = useState<string | null>(null);
const curFlowID = useRef<string | null>(null); const curFlowID = useRef<string | null>(null);
const [session, setSession] = useState<Session | null>(null);
const [isDirty, setIsDirty] = useState(false); const [isDirty, setIsDirty] = useState(false);
const workspaceContainerRef = useRef(null); const workspaceContainerRef = useRef(null);
const { showDialog } = useDialog(); const { showDialog } = useDialog();
@@ -60,7 +51,8 @@ export default function App() {
const toast = useToast(); const toast = useToast();
const [curVersion, setCurVersion] = useStateRef<WorkflowVersion | null>(null); const [curVersion, setCurVersion] = useStateRef<WorkflowVersion | null>(null);
const saveCurWorkflow = useCallback(async (force = false) => { const saveCurWorkflow = useCallback(async (force = false) => {
if (curFlowID.current) { const curWorkflow = workflowsTable?.curWorkflow;
if (curWorkflow) {
if (!force && workflowsTable?.curWorkflow?.saveLock) { if (!force && workflowsTable?.curWorkflow?.saveLock) {
toast({ toast({
title: "The workflow is locked and cannot be saved", title: "The workflow is locked and cannot be saved",
@@ -71,31 +63,20 @@ export default function App() {
} }
const graphJson = JSON.stringify(app.graph.serialize()); const graphJson = JSON.stringify(app.graph.serialize());
await Promise.all([ await Promise.all([
workflowsTable?.updateFlow(curFlowID.current, { workflowsTable?.updateFlow(curWorkflow.id, {
json: graphJson, json: graphJson,
}), }),
changelogsTable?.create({ changelogsTable?.create({
workflowID: curFlowID.current, workflowID: curWorkflow.id,
json: graphJson, json: graphJson,
isAutoSave: false, isAutoSave: false,
}), }),
]); ]);
userSettingsTable?.settings?.autoSave &&
toast({
title: "Saved",
status: "success",
duration: 1000,
isClosable: true,
});
setIsDirty(false); setIsDirty(false);
} }
}, []); }, []);
const discardUnsavedChanges = async () => { const discardUnsavedChanges = async () => {
if (userSettingsTable?.settings?.autoSave) {
alert("You cannot discard unsaved changes when auto save is enabled");
return;
}
const userInput = confirm( const userInput = confirm(
"Are you sure you want to discard unsaved changes? This will revert current workflow to your last saved version. You will lose all changes made since your last save.", "Are you sure you want to discard unsaved changes? This will revert current workflow to your last saved version. You will lose all changes made since your last save.",
); );
@@ -150,77 +131,71 @@ export default function App() {
try { try {
await loadDBs(); await loadDBs();
} catch (error) { } catch (error) {
console.error("error loading db", error); console.error("🦄Workspace Manager - Error loading db", error);
} }
setLoadingDB(false); setLoadingDB(false);
let latestWfID = null; const urlWorkflowID = getWorkflowIdInUrlHash();
latestWfID = getWorkflowIdInUrlHash(); if (urlWorkflowID != null) {
if (latestWfID == null) { loadWorkflowIDImpl(urlWorkflowID);
latestWfID = localStorage.getItem("curFlowID");
} }
if (latestWfID) { fetchApi("/workspace/deduplicate_workflow_ids");
loadWorkflowIDImpl(latestWfID); fetchApi("/workspace/get_os")
} .then((resp) => resp.json())
fetch("/workspace/deduplicate_workflow_ids"); .then((data) => {
const twoway = await userSettingsTable?.getSetting("twoWaySync"); if (data.os) {
!twoway && serverInfo.os = data.os;
indexdb.cache.get(UPGRADE_TO_2WAY_SYNC_KEY).then(async (value) => {
if (value?.value !== "true") {
const workflowsCount = await indexdb.workflows.count();
if (workflowsCount == 0) {
// empty workflows, enable 2way sync
await userSettingsTable?.upsert({ twoWaySync: true });
await indexdb.cache.put({
id: UPGRADE_TO_2WAY_SYNC_KEY,
value: "true",
});
return;
}
const myWorkflowsDir =
await userSettingsTable?.getSetting("myWorkflowsDir");
showDialog(
<EnableTwowaySyncConfirm
myWorkflowsDir={myWorkflowsDir ?? "undefined"}
/>,
[
{
label: "I have downloaded all my workflows and ready to enable",
onClick: async () => {
await userSettingsTable?.upsert({ twoWaySync: true });
if (await userSettingsTable?.getSetting("twoWaySync")) {
indexdb.cache.put({
id: UPGRADE_TO_2WAY_SYNC_KEY,
value: "true",
});
location.reload();
}
},
colorScheme: "red",
},
],
{
closeOnOverlayClick: false,
},
);
} }
}); });
}; const twoway = await userSettingsTable?.getSetting("twoWaySync");
const checkIsDirty = () => { if (!twoway) {
if (curFlowID.current == null) return false; const workflowsCount = await indexdb.workflows.count();
const curflow = workflowsTable?.curWorkflow; if (workflowsCount == 0) {
if (curflow == null) return false; // empty workflows, enable 2way sync
if (curflow.json == null) return true; await userSettingsTable?.upsert({ twoWaySync: true });
const graphJson = app.graph.serialize() ?? {}; await indexdb.cache.put({
let lastSaved = {}; id: UPGRADE_TO_2WAY_SYNC_KEY,
try { value: "true",
lastSaved = curflow?.json ? JSON.parse(curflow?.json) : {}; });
} catch (e) { return;
console.error("error parsing json", e); }
const myWorkflowsDir =
await userSettingsTable?.getSetting("myWorkflowsDir");
showDialog(
<EnableTwowaySyncConfirm
myWorkflowsDir={myWorkflowsDir ?? "undefined"}
/>,
[
{
label: "I have downloaded all my workflows and ready to enable",
onClick: async () => {
await userSettingsTable?.upsert({ twoWaySync: true });
if (await userSettingsTable?.getSetting("twoWaySync")) {
indexdb.cache.put({
id: UPGRADE_TO_2WAY_SYNC_KEY,
value: "true",
});
location.reload();
}
},
colorScheme: "red",
},
],
{
closeOnOverlayClick: false,
},
);
}
const encodedKey = localStorage.getItem("workspace_manager_shareKey");
if (encodedKey) {
const shareKey = decodeKey(encodedKey);
shareKey &&
setSession({
shareKey: shareKey,
username: null,
});
} }
const equal = deepJsonDiffCheck(graphJson, lastSaved);
return !equal;
}; };
const loadWorkflowIDImpl = async (id: string, versionID?: string | null) => { const loadWorkflowIDImpl = async (id: string, versionID?: string | null) => {
@@ -269,8 +244,8 @@ export default function App() {
if ( if (
!isDirty || !isDirty ||
forceLoad || forceLoad ||
userSettingsTable?.settings?.autoSave || workflowsTable?.curWorkflow == null ||
workflowsTable?.curWorkflow == null userSettingsTable?.settings?.disableUnsavedWarning
) { ) {
loadWorkflowIDImpl(id, versionID); loadWorkflowIDImpl(id, versionID);
return; return;
@@ -352,7 +327,6 @@ export default function App() {
json: workflow.json, json: workflow.json,
name: newFlowName || workflow.name, name: newFlowName || workflow.name,
parentFolderID: workflow.parentFolderID, parentFolderID: workflow.parentFolderID,
tags: workflow.tags,
}); });
flow && (await loadWorkflowID(flow.id)); flow && (await loadWorkflowID(flow.id));
}; };
@@ -390,37 +364,6 @@ export default function App() {
graphAppSetup(); graphAppSetup();
setLoadChild(true); setLoadChild(true);
const fileInput = document.getElementById(
"comfy-file-input",
) as HTMLInputElement;
const fileInputListener = async () => {
if (fileInput && fileInput.files && fileInput.files.length > 0) {
const newFlow: Workflow = {
id: nanoid(),
name: fileInput.files[0].name,
json: JSON.stringify(defaultGraph),
updateTime: Date.now(),
createTime: Date.now(),
};
setCurFlowIDAndName(newFlow);
await workflowsTable?.createFlow(newFlow);
}
};
fileInput?.addEventListener("change", fileInputListener);
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
const autoSaveEnabled = userSettingsTable?.settings?.autoSave ?? true;
if (workflowsTable?.curWorkflow?.saveLock) return;
const isDirty = checkIsDirty();
if (!autoSaveEnabled && isDirty) {
e.preventDefault(); // For modern browsers
e.returnValue = "You have unsaved changes!"; // For older browsers
showSaveOrDiscardCurWorkflowDialog();
}
};
window.addEventListener("beforeunload", handleBeforeUnload);
const handleExecuted = (e: any) => { const handleExecuted = (e: any) => {
e.detail?.output?.images?.forEach( e.detail?.output?.images?.forEach(
(im: { filename: string; subfolder: string; type: string }) => { (im: { filename: string; subfolder: string; type: string }) => {
@@ -439,35 +382,8 @@ export default function App() {
}; };
api.addEventListener("executed", handleExecuted); api.addEventListener("executed", handleExecuted);
const handleDrop = async (event: DragEvent) => {
const fileName = event.dataTransfer?.files[0]?.name;
const n = app.dragOverNode;
if (n && n.onDragDrop) {
return;
}
const overwriteFlow =
(await userSettingsTable?.getSetting(
"overwriteCurWorkflowWhenDroppingFileToCanvas",
)) ?? false;
if (!overwriteFlow && fileName) {
const newFlow: Workflow = {
id: nanoid(),
name: fileName,
json: JSON.stringify(defaultGraph),
updateTime: Date.now(),
createTime: Date.now(),
};
setCurFlowIDAndName(newFlow);
await workflowsTable?.createFlow(newFlow);
}
};
app.canvasEl.addEventListener("drop", handleDrop);
return () => { return () => {
window.removeEventListener("change", fileInputListener);
window.removeEventListener("beforeunload", handleBeforeUnload);
window.removeEventListener("executed", handleExecuted); window.removeEventListener("executed", handleExecuted);
app.canvasEl.removeEventListener("drop", handleDrop);
}; };
}, []); }, []);
@@ -491,6 +407,9 @@ export default function App() {
route: route, route: route,
curVersion: curVersion, curVersion: curVersion,
setCurVersion: setCurVersion, setCurVersion: setCurVersion,
setCurFlowIDAndName: setCurFlowIDAndName,
session: session,
updateSession: setSession,
}} }}
> >
<div ref={workspaceContainerRef} className="workspace_manager"> <div ref={workspaceContainerRef} className="workspace_manager">
@@ -18,6 +18,7 @@ import FilesListFolderItemRightClickMenu from "./FilesListFolderItemRightClickMe
import { ESortTypes, sortTypeLocalStorageKey } from "./types"; import { ESortTypes, sortTypeLocalStorageKey } from "./types";
import { Folder, Workflow } from "../types/dbTypes"; import { Folder, Workflow } from "../types/dbTypes";
import ItemsList from "./ItemsList"; import ItemsList from "./ItemsList";
import { getPathSep } from "../utils/OsPathUtils";
type Props = { type Props = {
folder: Folder; folder: Folder;
@@ -82,8 +83,8 @@ export default memo(function FilesListFolderItem({ folder }: Props) {
}, [isCollapsed]); }, [isCollapsed]);
useEffect(() => { useEffect(() => {
const cur = workflowsTable?.curWorkflow; const cur = workflowsTable?.curWorkflow;
const curWorkflowPath = cur?.parentFolderID + "/"; const curWorkflowPath = cur?.parentFolderID + getPathSep();
const folderPath = folder.id + "/"; const folderPath = folder.id + getPathSep();
const childreHasCurworkflow = curWorkflowPath.startsWith(folderPath); const childreHasCurworkflow = curWorkflowPath.startsWith(folderPath);
if (childreHasCurworkflow) { if (childreHasCurworkflow) {
setIsCollapsed(false); setIsCollapsed(false);
+10 -3
View File
@@ -12,15 +12,21 @@ import {
IconCopy, IconCopy,
IconDotsVertical, IconDotsVertical,
IconExternalLink, IconExternalLink,
IconLink,
IconLock, IconLock,
IconLockOpen, IconLockOpen,
IconUpload, IconUpload,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
import AddTagToWorkflowPopover from "./AddTagToWorkflowPopover";
import { Workflow } from "../types/dbTypes"; import { Workflow } from "../types/dbTypes";
import { mediaTable, workflowsTable } from "../db-tables/WorkspaceDB"; import {
mediaTable,
userSettingsTable,
workflowsTable,
} from "../db-tables/WorkspaceDB";
import { WorkspaceContext } from "../WorkspaceContext"; import { WorkspaceContext } from "../WorkspaceContext";
import { openWorkflowInNewTab } from "../utils"; import { openWorkflowInNewTab } from "../utils";
import { fetchApi } from "../Api";
import CopyShareLinkMenuItem from "../components/CopyShareLinkMenuItem";
type Props = { type Props = {
workflow: Workflow; workflow: Workflow;
@@ -55,7 +61,7 @@ export default function MoreActionMenu({ workflow }: Props) {
body.append(`images[${index}]`, file, file.name); body.append(`images[${index}]`, file, file.name);
}); });
body.append("subfolder", "workspace_manager"); body.append("subfolder", "workspace_manager");
await fetch("/workspace/images/save", { await fetchApi("/workspace/images/save", {
method: "POST", method: "POST",
body, body,
}); });
@@ -114,6 +120,7 @@ export default function MoreActionMenu({ workflow }: Props) {
{isLocked ? "Unlock" : "Lock"} {isLocked ? "Unlock" : "Lock"}
</MenuItem> </MenuItem>
</Tooltip> </Tooltip>
<CopyShareLinkMenuItem curFlow={workflow} />
<MenuItem <MenuItem
icon={<IconUpload />} icon={<IconUpload />}
onClick={() => { onClick={() => {
+13 -18
View File
@@ -30,8 +30,6 @@ import RecentFilesDrawerMenu from "./RecentFilesDrawerMenu";
import { insertWorkflowToCanvas, sortFileItem } from "../utils"; import { insertWorkflowToCanvas, sortFileItem } from "../utils";
import MultipleSelectionOperation from "./MultipleSelectionOperation"; import MultipleSelectionOperation from "./MultipleSelectionOperation";
import { ESortTypes, sortTypeLocalStorageKey } from "./types"; import { ESortTypes, sortTypeLocalStorageKey } from "./types";
// @ts-expect-error ComfyUI import
import { app } from "/scripts/app.js";
import { useDebounce } from "../customHooks/useDebounce"; import { useDebounce } from "../customHooks/useDebounce";
import SearchInput from "../components/SearchInput"; import SearchInput from "../components/SearchInput";
import { openWorkflowsFolder } from "../Api"; import { openWorkflowsFolder } from "../Api";
@@ -40,6 +38,7 @@ import MyTagsRow from "./MyTagsRow";
import ImportFlowsFileInput from "./ImportFlowsFileInput"; import ImportFlowsFileInput from "./ImportFlowsFileInput";
import ItemsList from "./ItemsList"; import ItemsList from "./ItemsList";
import { DRAWER_Z_INDEX } from "../const"; import { DRAWER_Z_INDEX } from "../const";
import { app } from "../utils/comfyapp";
type Props = { type Props = {
onClose: () => void; onClose: () => void;
@@ -258,22 +257,18 @@ export default function RecentFilesDrawer({ onClose, onClickNewFlow }: Props) {
/> />
<HStack mb={2} mt={2} p={0} justifyContent="space-between"> <HStack mb={2} mt={2} p={0} justifyContent="space-between">
<HStack> <HStack>
{allFlowsRef.current.length > 0 ? ( <MultipleSelectionOperation
<MultipleSelectionOperation multipleState={multipleState}
multipleState={multipleState} changeMultipleState={(state) => {
changeMultipleState={(state) => { setMultipleState(state);
setMultipleState(state); !state && setSelectedKeys([]);
!state && setSelectedKeys([]); }}
}} selectedKeys={selectedKeys}
selectedKeys={selectedKeys} isSelectedAll={
isSelectedAll={ selectedKeys.length === allFlowsRef.current.length
selectedKeys.length === allFlowsRef.current.length }
} batchOperationCallback={batchOperationCallback}
batchOperationCallback={batchOperationCallback} />
/>
) : (
<Box />
)}
{!multipleState && ( {!multipleState && (
<Tooltip hasArrow label="New folder" placement="bottom-start"> <Tooltip hasArrow label="New folder" placement="bottom-start">
<IconButton <IconButton
@@ -11,9 +11,7 @@ import {
IconMoon, IconMoon,
IconSettings, IconSettings,
IconSun, IconSun,
IconTag,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
import ManageTagsModal from "./ManageTagsModal";
import { useState } from "react"; import { useState } from "react";
import WorkspaceSettingsModal from "./WorkspaceSettingsModal"; import WorkspaceSettingsModal from "./WorkspaceSettingsModal";
const ICON_SIZE = 16; const ICON_SIZE = 16;
@@ -21,7 +19,6 @@ type Props = {
// onclose: () => void; // onclose: () => void;
}; };
export default function RecentFilesDrawerMenu({}: Props) { export default function RecentFilesDrawerMenu({}: Props) {
const [isManageTagsOpen, setIsManageTagsOpen] = useState(false);
const [isSettingsOpen, setIsSettingsOpen] = useState(false); const [isSettingsOpen, setIsSettingsOpen] = useState(false);
const { colorMode, toggleColorMode } = useColorMode(); const { colorMode, toggleColorMode } = useColorMode();
@@ -43,13 +40,6 @@ export default function RecentFilesDrawerMenu({}: Props) {
> >
Settings Settings
</MenuItem> </MenuItem>
<MenuItem
onClick={() => setIsManageTagsOpen(true)}
icon={<IconTag size={ICON_SIZE} />}
fontSize={16}
>
Manage Tags
</MenuItem>
<MenuItem <MenuItem
onClick={toggleColorMode} onClick={toggleColorMode}
icon={ icon={
@@ -65,9 +55,6 @@ export default function RecentFilesDrawerMenu({}: Props) {
</MenuItem> </MenuItem>
</MenuList> </MenuList>
</Menu> </Menu>
{isManageTagsOpen && (
<ManageTagsModal onclose={() => setIsManageTagsOpen(false)} />
)}
{isSettingsOpen && ( {isSettingsOpen && (
<WorkspaceSettingsModal onClose={() => setIsSettingsOpen(false)} /> <WorkspaceSettingsModal onClose={() => setIsSettingsOpen(false)} />
)} )}
@@ -89,7 +89,7 @@ export default memo(function WorkflowListItem({ workflow }: Props) {
w={"100%"} w={"100%"}
justify={"space-between"} justify={"space-between"}
borderBottom={"1px solid"} borderBottom={"1px solid"}
borderColor={colorMode == "dark" ? "gray.900" : "gray.200"} borderColor={colorMode == "dark" ? "gray.700" : "gray.200"}
onMouseEnter={() => setIsHovering(true)} onMouseEnter={() => setIsHovering(true)}
onMouseLeave={() => setIsHovering(false)} onMouseLeave={() => setIsHovering(false)}
> >
@@ -111,7 +111,7 @@ export default memo(function WorkflowListItem({ workflow }: Props) {
{isHovering ? ( {isHovering ? (
<WorkflowListItemActionButtons workflow={workflow} /> <WorkflowListItemActionButtons workflow={workflow} />
) : ( ) : (
<Text color={"GrayText"} ml={"2px"} fontSize={"sm"}> <Text color={"GrayText"} fontSize={"sm"}>
{formatTimestamp(workflow.updateTime, false, false, "/")} {formatTimestamp(workflow.updateTime, false, false, "/")}
</Text> </Text>
)} )}
@@ -10,12 +10,12 @@ import {
VStack, VStack,
} from "@chakra-ui/react"; } from "@chakra-ui/react";
import { ShortcutSettings } from "../settings/ShortcutSettings"; import { ShortcutSettings } from "../settings/ShortcutSettings";
import FolderOnTopSettings from "../settings/FolderOnTopSettings";
import TwoWaySyncSettings from "../settings/TwoWaySyncSettings"; import TwoWaySyncSettings from "../settings/TwoWaySyncSettings";
import CommonCheckboxSettings from "../settings/CommonCheckboxSettings"; import CommonCheckboxSettings from "../settings/CommonCheckboxSettings";
import SelectMyWorkflowsDir from "../settings/SelectMyWorkflowsDir"; import SelectMyWorkflowsDir from "../settings/SelectMyWorkflowsDir";
import { CommonNumberSetting } from "../settings/CommonNumberSetting"; import { CommonNumberSetting } from "../settings/CommonNumberSetting";
import AutosaveSetting from "../settings/AutosaveSetting"; import CloudHostSetting from "../settings/CloudHostSetting";
import SharekeySetting from "../settings/SharekeySetting";
export default function WorkspaceSettingsModal({ export default function WorkspaceSettingsModal({
onClose, onClose,
@@ -38,13 +38,12 @@ export default function WorkspaceSettingsModal({
w="100%" w="100%"
> >
<SelectMyWorkflowsDir /> <SelectMyWorkflowsDir />
<AutosaveSetting />
<ShortcutSettings /> <ShortcutSettings />
<TwoWaySyncSettings /> <TwoWaySyncSettings />
<FolderOnTopSettings /> <SharekeySetting />
<CommonCheckboxSettings <CommonCheckboxSettings
settingKey="overwriteCurWorkflowWhenDroppingFileToCanvas" settingKey="foldersOnTop"
text="Overwrite current workflow when drag and drop workflow file to canvas" text={`Folders always on top`}
/> />
<CommonNumberSetting <CommonNumberSetting
label={`Maximum number of save change history to store. This does not include label={`Maximum number of save change history to store. This does not include
@@ -52,10 +51,16 @@ export default function WorkspaceSettingsModal({
and has no limit.`} and has no limit.`}
settingKey="maximumChangelogNumber" settingKey="maximumChangelogNumber"
/> />
<CommonCheckboxSettings
settingKey="disableUnsavedWarning"
text={`Disable the "Save or Discard" warning when closing a workflow with unsaved changes. ⛔️Be careful, if you disable this reminder and forget to save your workflow, you will lose your changes.`}
/>
<CommonCheckboxSettings <CommonCheckboxSettings
settingKey="hideCoverImage" settingKey="hideCoverImage"
text="Hide thumbnail image in workflow list" text="Hide thumbnail image in workflow list"
/> />
<CloudHostSetting />
</VStack> </VStack>
</HStack> </HStack>
</ModalBody> </ModalBody>
+7 -1
View File
@@ -1,6 +1,6 @@
import { createContext } from "react"; import { createContext } from "react";
import { Folder, Workflow, WorkflowVersion } from "./types/dbTypes"; import { Folder, Workflow, WorkflowVersion } from "./types/dbTypes";
import { WorkspaceRoute } from "./types/types"; import { Session, WorkspaceRoute } from "./types/types";
export type JsonDiff = { export type JsonDiff = {
old: Object; old: Object;
new: Object; new: Object;
@@ -24,6 +24,9 @@ export const WorkspaceContext = createContext<{
route: WorkspaceRoute; route: WorkspaceRoute;
curVersion: WorkflowVersion | null; curVersion: WorkflowVersion | null;
setCurVersion: (version: WorkflowVersion | null) => void; setCurVersion: (version: WorkflowVersion | null) => void;
setCurFlowIDAndName: (workflow: Workflow | null) => void;
session: Session | null;
updateSession: (session: Session) => void;
}>({ }>({
curFlowID: null, curFlowID: null,
loadWorkflowID: () => {}, loadWorkflowID: () => {},
@@ -37,6 +40,9 @@ export const WorkspaceContext = createContext<{
curVersion: null, curVersion: null,
setIsDirty: () => {}, setIsDirty: () => {},
setCurVersion: () => {}, setCurVersion: () => {},
setCurFlowIDAndName: () => {},
session: null,
updateSession: () => {},
}); });
export const RecentFilesContext = createContext<{ export const RecentFilesContext = createContext<{
+49 -34
View File
@@ -1,3 +1,4 @@
import { fetchApi } from "../Api";
import { COMFYSPACE_TRACKING_FIELD_NAME } from "../const"; import { COMFYSPACE_TRACKING_FIELD_NAME } from "../const";
import { indexdb } from "../db-tables/indexdb"; import { indexdb } from "../db-tables/indexdb";
import { Workflow } from "../types/dbTypes"; import { Workflow } from "../types/dbTypes";
@@ -13,7 +14,7 @@ export namespace TwowaySyncAPI {
newParentFolderRelPath: string, newParentFolderRelPath: string,
) { ) {
try { try {
const response = await fetch("/workspace/file/move", { const response = await fetchApi("/workspace/file/move", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -39,7 +40,7 @@ export namespace TwowaySyncAPI {
parentFolderID: string | null, parentFolderID: string | null,
): Promise<string | null> { ): Promise<string | null> {
try { try {
const response = await fetch("/workspace/file/gen_unique_name", { const response = await fetchApi("/workspace/file/gen_unique_name", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -65,7 +66,7 @@ export namespace TwowaySyncAPI {
newName: string, newName: string,
) { ) {
try { try {
const response = await fetch("/workspace/file/rename", { const response = await fetchApi("/workspace/file/rename", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -85,16 +86,6 @@ export namespace TwowaySyncAPI {
console.error("Error deleting file:", error); console.error("Error deleting file:", error);
} }
} }
interface DuplicatesResponse {
duplicates: {
[id: string]: Array<{
path: string;
createTime: number;
}>;
};
}
export async function saveWorkflow(workflow: Workflow) { export async function saveWorkflow(workflow: Workflow) {
const json = workflow.json; const json = workflow.json;
const flow = JSON.parse(json); const flow = JSON.parse(json);
@@ -102,7 +93,12 @@ export namespace TwowaySyncAPI {
flow.extra[COMFYSPACE_TRACKING_FIELD_NAME] = {}; flow.extra[COMFYSPACE_TRACKING_FIELD_NAME] = {};
} }
flow.extra[COMFYSPACE_TRACKING_FIELD_NAME].id = workflow.id; flow.extra[COMFYSPACE_TRACKING_FIELD_NAME].id = workflow.id;
const response = await fetch("/workspace/file/save", { flow.extra[COMFYSPACE_TRACKING_FIELD_NAME].saveLock = workflow.saveLock;
flow.extra[COMFYSPACE_TRACKING_FIELD_NAME].cloudID = workflow.cloudID;
flow.extra[COMFYSPACE_TRACKING_FIELD_NAME].coverMediaPath =
workflow.coverMediaPath;
const response = await fetchApi("/workspace/file/save", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -125,7 +121,7 @@ export namespace TwowaySyncAPI {
} }
export async function deleteWorkflow(workflow: Workflow) { export async function deleteWorkflow(workflow: Workflow) {
try { try {
const response = await fetch("/workspace/delete_file", { const response = await fetchApi("/workspace/delete_file", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -142,12 +138,8 @@ export namespace TwowaySyncAPI {
console.error("Error deleting file:", error); console.error("Error deleting file:", error);
} }
} }
export async function createWorkflow({ export async function createWorkflow(workflow: Workflow) {
parentFolderID, const { parentFolderID, name, json, id } = workflow;
name,
json,
id,
}: Workflow) {
let jsonObj: any = JSON.parse(json); let jsonObj: any = JSON.parse(json);
if (jsonObj.extra == null) { if (jsonObj.extra == null) {
jsonObj.extra = {}; jsonObj.extra = {};
@@ -156,6 +148,10 @@ export namespace TwowaySyncAPI {
jsonObj.extra[COMFYSPACE_TRACKING_FIELD_NAME] = {}; jsonObj.extra[COMFYSPACE_TRACKING_FIELD_NAME] = {};
} }
jsonObj.extra[COMFYSPACE_TRACKING_FIELD_NAME].id = id; // to avoid overwriting deps jsonObj.extra[COMFYSPACE_TRACKING_FIELD_NAME].id = id; // to avoid overwriting deps
jsonObj.extra[COMFYSPACE_TRACKING_FIELD_NAME].saveLock = workflow.saveLock;
jsonObj.extra[COMFYSPACE_TRACKING_FIELD_NAME].cloudID = workflow.cloudID;
jsonObj.extra[COMFYSPACE_TRACKING_FIELD_NAME].coverMediaPath =
workflow.coverMediaPath;
const input: { parentFolderPath: string; name: string; json: string } = { const input: { parentFolderPath: string; name: string; json: string } = {
parentFolderPath: sanitizeRelPath(parentFolderID ?? ""), parentFolderPath: sanitizeRelPath(parentFolderID ?? ""),
name: name, name: name,
@@ -163,7 +159,7 @@ export namespace TwowaySyncAPI {
}; };
try { try {
const response = await fetch("/workspace/create_workflow_file", { const response = await fetchApi("/workspace/create_workflow_file", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -195,12 +191,23 @@ export namespace TwowaySyncAPI {
id: string; id: string;
name: string; name: string;
}): Promise<{ }): Promise<{
json?: Object; json?: {
extra: {
[COMFYSPACE_TRACKING_FIELD_NAME]: {
id: string;
saveLock: boolean;
cloudID: string | null;
coverMediaPath: string | null;
};
};
};
createTime?: number;
updateTime?: number;
error?: string; error?: string;
}> { }> {
const relPath = joinRelPath(parentFolderID ?? "", name + ".json"); const relPath = joinRelPath(parentFolderID ?? "", name + ".json");
try { try {
const response = await fetch("/workspace/get_workflow_file", { const response = await fetchApi("/workspace/get_workflow_file", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -234,7 +241,11 @@ export type ScanLocalFile = {
type: "workflow"; type: "workflow";
name: string; name: string;
id: string; id: string;
path: string;
json: string; json: string;
saveLock: boolean;
cloudID: string | null;
coverMediaPath: string | null;
createTime: number; createTime: number;
updateTime: number; updateTime: number;
lastOpenedTime?: number; lastOpenedTime?: number;
@@ -243,6 +254,7 @@ export type ScanLocalFolder = {
id: string; id: string;
type: "folder"; type: "folder";
name: string; name: string;
path: string;
parentFolderID: string; parentFolderID: string;
}; };
export async function scanLocalFiles( export async function scanLocalFiles(
@@ -251,17 +263,20 @@ export async function scanLocalFiles(
metaInfoOnly = false, metaInfoOnly = false,
): Promise<Array<ScanLocalFile | ScanLocalFolder>> { ): Promise<Array<ScanLocalFile | ScanLocalFolder>> {
try { try {
const response = await fetch("/workspace/file/scan_my_workflows_folder", { const response = await fetchApi(
method: "POST", "/workspace/file/scan_my_workflows_folder",
headers: { {
"Content-Type": "application/json", method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
path: sanitizeRelPath(path),
recursive,
metaInfoOnly,
}),
}, },
body: JSON.stringify({ );
path: sanitizeRelPath(path),
recursive,
metaInfoOnly,
}),
});
const result = await response.json(); const result = await response.json();
return result; return result;
} catch (error) { } catch (error) {
+6 -5
View File
@@ -1,3 +1,4 @@
import { fetchApi } from "../Api";
import { Folder } from "../types/dbTypes"; import { Folder } from "../types/dbTypes";
import { sanitizeRelPath } from "../utils/OsPathUtils"; import { sanitizeRelPath } from "../utils/OsPathUtils";
@@ -13,7 +14,7 @@ export namespace TwowayFolderSyncAPI {
} }
export async function createFolder(folder: Folder) { export async function createFolder(folder: Folder) {
await fetch("/workspace/folder/create", { await fetchApi("/workspace/folder/create", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -27,7 +28,7 @@ export namespace TwowayFolderSyncAPI {
folderToBeMoved: string, folderToBeMoved: string,
newParentPath: string, newParentPath: string,
) { ) {
const resp = await fetch("/workspace/folder/move", { const resp = await fetchApi("/workspace/folder/move", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -45,7 +46,7 @@ export namespace TwowayFolderSyncAPI {
} }
export async function deleteFolder(relPath: string) { export async function deleteFolder(relPath: string) {
try { try {
const response = await fetch("/workspace/folder/delete", { const response = await fetchApi("/workspace/folder/delete", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -65,7 +66,7 @@ export namespace TwowayFolderSyncAPI {
folderRelPath: string, folderRelPath: string,
): Promise<number | null> { ): Promise<number | null> {
try { try {
const response = await fetch("/workspace/file/count_files", { const response = await fetchApi("/workspace/file/count_files", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@@ -90,7 +91,7 @@ export namespace TwowayFolderSyncAPI {
newName: string, newName: string,
): Promise<void> { ): Promise<void> {
try { try {
const response = await fetch("/workspace/folder/rename", { const response = await fetchApi("/workspace/folder/rename", {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
-19
View File
@@ -1,19 +0,0 @@
import { COMFYSPACE_AUTH_REDIRECT_URL } from "../const";
const COGNITO_DOMAIN = import.meta.env.VITE_AWS_COGNITO_DOMAIN;
const CLIENT_ID = import.meta.env.VITE_AWS_COGNITO_CLIENT_ID;
const redirectUri = encodeURIComponent(COMFYSPACE_AUTH_REDIRECT_URL);
export function openCognitoPopup() {
const cognitoUrl = `${COGNITO_DOMAIN}/login`;
const responseType = "token";
const popupUrl = `${cognitoUrl}?response_type=${responseType}&client_id=${CLIENT_ID}&redirect_uri=${redirectUri}`;
const popupWindow = window.open(
popupUrl,
"ComfyspaceLogin",
"width=800,height=600",
);
popupWindow?.focus();
}
@@ -0,0 +1,58 @@
import { HStack, MenuItem, Spinner, useToast } from "@chakra-ui/react";
import { IconLink } from "@tabler/icons-react";
import { useContext, useState } from "react";
import { WorkspaceContext } from "../WorkspaceContext";
import { copySharelink } from "./copySharelink";
import { Workflow } from "../types/dbTypes";
export default function CopyShareLinkMenuItem({
curFlow,
}: {
curFlow: Workflow;
}) {
const { session } = useContext(WorkspaceContext);
const toast = useToast();
const [loading, setloading] = useState(false);
return (
<MenuItem
onClick={async () => {
if (!curFlow) {
return;
}
if (!session?.shareKey) {
alert(
"Please set your share key first in Settings to enable cloud share.",
);
return;
}
setloading(true);
const res = await copySharelink(session.shareKey, curFlow!);
if (res?.link) {
navigator.clipboard.writeText(res.link);
toast({
title: "Link copied",
status: "success",
duration: 2000,
});
} else {
toast({
title: "Failed to copy link",
status: "error",
description: res?.error,
duration: null,
});
}
setloading(false);
}}
icon={loading ? <Spinner /> : <IconLink size={20} />}
iconSpacing={1}
alignItems={"center"}
isDisabled={loading}
>
<HStack>
<p>Copy share link</p>
</HStack>
</MenuItem>
);
}
+87 -28
View File
@@ -1,9 +1,7 @@
import { import {
Button, Button,
Modal, Modal,
ModalOverlay,
ModalContent, ModalContent,
ModalHeader,
ModalCloseButton, ModalCloseButton,
ModalBody, ModalBody,
ModalFooter, ModalFooter,
@@ -11,20 +9,30 @@ import {
FormLabel, FormLabel,
FormErrorMessage, FormErrorMessage,
Input, Input,
Stack,
useToast,
} from "@chakra-ui/react"; } from "@chakra-ui/react";
import { workflowVersionsTable } from "../db-tables/WorkspaceDB"; import { userSettingsTable, workflowsTable } from "../db-tables/WorkspaceDB";
import { useState, ChangeEvent } from "react"; import { useState, ChangeEvent, useContext } from "react";
// @ts-ignore import { WorkspaceContext } from "../WorkspaceContext";
import { app } from "/scripts/app.js"; import CreateVersionLogin from "../versionHistory/CreateVersionLogin";
import { ShareWorkflowData } from "../types/types";
import { app } from "../utils/comfyapp";
import { EWorkflowPrivacy } from "../types/dbTypes";
import { getCurDateString, getNodeDefs } from "../share/shareUtils";
interface Props { interface Props {
workflowId: string; workflowId: string;
onClose: () => void; onClose: () => void;
} }
export default function CreateVersionDialog({ workflowId, onClose }: Props) { export default function CreateVersionDialog({ onClose }: Props) {
const [newVersionName, setNewVersionName] = useState(""); const [newVersionName, setNewVersionName] = useState(
"v" + getCurDateString(),
);
const [submitError, setSubmitError] = useState(""); const [submitError, setSubmitError] = useState("");
const { session } = useContext(WorkspaceContext);
const toast = useToast();
const [submitting, setSubmitting] = useState(false);
const handleChange = (event: ChangeEvent<HTMLInputElement>) => { const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
setNewVersionName(event.target.value); setNewVersionName(event.target.value);
submitError && setSubmitError(""); submitError && setSubmitError("");
@@ -33,31 +41,81 @@ export default function CreateVersionDialog({ workflowId, onClose }: Props) {
const onSubmit = async () => { const onSubmit = async () => {
const trimName = newVersionName.trim(); const trimName = newVersionName.trim();
setNewVersionName(trimName); setNewVersionName(trimName);
const versionList = if (!workflowsTable?.curWorkflow) {
(await workflowVersionsTable?.listByWorkflowID(workflowId)) ?? []; throw new Error("No workflow selected");
if (versionList.some((version) => version.name === trimName)) {
setSubmitError(
"The name is duplicated, please modify it and submit again.",
);
} else {
const graphJson = JSON.stringify(app.graph.serialize());
await workflowVersionsTable?.add({
name: newVersionName,
workflowID: workflowId,
createTime: Date.now(),
json: graphJson,
});
onClose();
} }
setSubmitting(true);
const prompt = await app.graphToPrompt();
const graph = app.graph.serialize();
if (!graph.extra) {
graph.extra = {};
}
graph.extra.apiPrompt = prompt.output ?? null;
const input: ShareWorkflowData = {
workflow: {
name: workflowsTable?.curWorkflow?.name,
cloudID: workflowsTable?.curWorkflow?.cloudID,
},
version: {
name: trimName,
json: JSON.stringify(graph),
},
nodeDefs: getNodeDefs(),
privacy: EWorkflowPrivacy.PRIVATE,
};
const data = await fetch(
userSettingsTable?.settings?.cloudHost + "/api/createCloudflow",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${session?.shareKey}`,
},
body: JSON.stringify(input),
},
)
.then((resp) => resp.json())
.then(async (data) => {
if (data?.data) {
const cloudID = data.data.workflowID;
await workflowsTable?.updateMetaInfo(
workflowsTable?.curWorkflow?.id!,
{
cloudID,
},
);
toast({
title: "Version created",
status: "success",
duration: 3000,
});
onClose();
} else {
setSubmitError("Failed to create version. " + (data?.error ?? ""));
}
})
.catch((e) => {
setSubmitError("Failed to create version");
return null;
});
setSubmitting(false);
}; };
if (!session?.shareKey) {
return <CreateVersionLogin onClose={onClose} />;
}
const domain = new URL(userSettingsTable!.settings!.cloudHost).hostname;
return ( return (
<Modal isOpen={true} onClose={onClose}> <Modal isOpen={true} onClose={onClose}>
<ModalOverlay />
<ModalContent> <ModalContent>
<ModalHeader>Create Version</ModalHeader>
<ModalCloseButton /> <ModalCloseButton />
<ModalBody> <ModalBody>
<Stack mb={5}>
<p style={{ fontSize: 20, fontWeight: "bold" }}>Create Version</p>
<p style={{ color: "GrayText" }}>
Saving to{" "}
<a href={userSettingsTable?.settings?.cloudHost}> {domain}</a>
</p>
</Stack>
<FormControl isInvalid={!!submitError}> <FormControl isInvalid={!!submitError}>
<FormLabel>Name</FormLabel> <FormLabel>Name</FormLabel>
<Input <Input
@@ -79,7 +137,8 @@ export default function CreateVersionDialog({ workflowId, onClose }: Props) {
colorScheme="teal" colorScheme="teal"
mr={3} mr={3}
onClick={onSubmit} onClick={onSubmit}
isDisabled={!newVersionName || !!submitError} isDisabled={!newVersionName}
isLoading={submitting}
> >
Create Create
</Button> </Button>
+20 -24
View File
@@ -26,6 +26,7 @@ import {
DarkMode, DarkMode,
Tag, Tag,
HStack, HStack,
useToast,
} from "@chakra-ui/react"; } from "@chakra-ui/react";
import { import {
IconArrowBackUpDouble, IconArrowBackUpDouble,
@@ -43,11 +44,11 @@ import { Workflow } from "../types/dbTypes";
import CreateVersionDialog from "./CreateVersionDialog"; import CreateVersionDialog from "./CreateVersionDialog";
import HoverMenu from "./HoverMenu"; import HoverMenu from "./HoverMenu";
const ShareDialog = lazy(() => import("../share/ShareDialog")); const ShareDialog = lazy(() => import("../share/ShareDialog"));
// @ts-ignore
import { app } from "/scripts/app.js";
import { TOPBAR_BUTTON_HEIGHT } from "../const"; import { TOPBAR_BUTTON_HEIGHT } from "../const";
import DownloadSpaceJsonDialog from "../spacejson/DownloadSpaceJsonDialog";
import { downloadJsonFile } from "../utils/downloadJsonFile"; import { downloadJsonFile } from "../utils/downloadJsonFile";
import { SharedTopbarButton } from "../share/SharedTopbarButton";
import { app } from "../utils/comfyapp";
import CopyShareLinkMenuItem from "./CopyShareLinkMenuItem";
export default function DropdownTitle() { export default function DropdownTitle() {
const { const {
@@ -57,6 +58,7 @@ export default function DropdownTitle() {
saveCurWorkflow, saveCurWorkflow,
setRoute, setRoute,
route, route,
session,
} = useContext(WorkspaceContext); } = useContext(WorkspaceContext);
const [isOpenNewVersion, setIsOpenNewVersion] = useState(false); const [isOpenNewVersion, setIsOpenNewVersion] = useState(false);
@@ -84,7 +86,7 @@ export default function DropdownTitle() {
setNewFlowName(event.target.value); setNewFlowName(event.target.value);
submitError && setSubmitError(""); submitError && setSubmitError("");
}; };
const toast = useToast();
const onSubmit = async () => { const onSubmit = async () => {
if (!curFlowID) { if (!curFlowID) {
alert("Flow ID is required"); alert("Flow ID is required");
@@ -146,17 +148,15 @@ export default function DropdownTitle() {
> >
Save Save
</MenuItem> </MenuItem>
{!userSettingsTable?.settings?.autoSave && ( <Tooltip label="Revert workflow to your last saved version. You will lose all changes made since your last save.">
<Tooltip label="Revert workflow to your last saved version. You will lose all changes made since your last save."> <MenuItem
<MenuItem onClick={discardUnsavedChanges}
onClick={discardUnsavedChanges} icon={<IconArrowBackUpDouble size={20} />}
icon={<IconArrowBackUpDouble size={20} />} iconSpacing={1}
iconSpacing={1} >
> Discard unsaved changes
Discard unsaved changes </MenuItem>
</MenuItem> </Tooltip>
</Tooltip>
)}
<MenuItem <MenuItem
onClick={handleDownload} onClick={handleDownload}
icon={<IconDownload size={20} />} icon={<IconDownload size={20} />}
@@ -186,23 +186,20 @@ export default function DropdownTitle() {
> >
Versions History Versions History
</MenuItem> </MenuItem>
{/* <MenuItem
onClick={() => setRoute("downloadSpaceJson")}
icon={<IconDownload size={20} />}
iconSpacing={1}
>
Save runnable workflow🧪
</MenuItem> */}
<MenuItem <MenuItem
onClick={() => setRoute("downloadSpaceJson")} onClick={() => setRoute("share")}
icon={<IconShare2 size={20} />} icon={<IconShare2 size={20} />}
iconSpacing={1} iconSpacing={1}
alignItems={"center"} alignItems={"center"}
> >
<HStack> <HStack>
<p>Share</p> <Tag size={"sm"}>🧪beta</Tag> <p>Share</p> <Tag size={"sm"}>🧪beta</Tag>
<SharedTopbarButton />
</HStack> </HStack>
</MenuItem> </MenuItem>
{workflowsTable?.curWorkflow && (
<CopyShareLinkMenuItem curFlow={workflowsTable?.curWorkflow} />
)}
</MenuList> </MenuList>
</Menu> </Menu>
} }
@@ -211,7 +208,6 @@ export default function DropdownTitle() {
{route == "versionHistory" && ( {route == "versionHistory" && (
<VersionHistoryDrawer onClose={() => setRoute("root")} /> <VersionHistoryDrawer onClose={() => setRoute("root")} />
)} )}
{route == "downloadSpaceJson" && <DownloadSpaceJsonDialog />}
{route === "saveAsModal" && ( {route === "saveAsModal" && (
<Modal isOpen={true} onClose={handleOnCloseModal}> <Modal isOpen={true} onClose={handleOnCloseModal}>
<ModalOverlay /> <ModalOverlay />
+1 -1
View File
@@ -81,7 +81,7 @@ export default function EditFlowName({
as="div" as="div"
color="white" color="white"
onClick={startEdit} onClick={startEdit}
maxW={200} maxW={160}
fontWeight={500} fontWeight={500}
whiteSpace="nowrap" whiteSpace="nowrap"
overflow="hidden" overflow="hidden"
+1 -31
View File
@@ -52,35 +52,5 @@ export default function MediaPreview({
src={`/workspace/view_media?filename=${mediaLocalPath}`} src={`/workspace/view_media?filename=${mediaLocalPath}`}
alt="workflow image renamed or moved from output folder" alt="workflow image renamed or moved from output folder"
/> />
) : ( ) : null;
<div
style={{
width: size + "px",
height: size + `px`,
overflow: "hidden",
position: "relative",
}}
>
<video
width={size}
height={size}
src={`/workspace/view_media?filename=${mediaLocalPath}`}
loop={true}
autoPlay={autoPlay ?? false}
muted={true}
style={{
// for video to crop to center
objectFit: "cover",
width: "100%",
height: "100%",
// position: "absolute",
// top: "50%", // Align the center of the video with the center of the container vertically
// left: "50%", // Align the center of the video with the center of the container horizontally
// transform: "translate(-50%, -50%)", // Offset the video to ensure it is centered
}}
>
<track kind="captions" />
</video>
</div>
);
} }
+79 -24
View File
@@ -21,26 +21,28 @@ import {
import { IconX } from "@tabler/icons-react"; import { IconX } from "@tabler/icons-react";
import { import {
changelogsTable, changelogsTable,
userSettingsTable,
workflowsTable, workflowsTable,
workflowVersionsTable, workflowVersionsTable,
} from "../db-tables/WorkspaceDB"; } from "../db-tables/WorkspaceDB";
import { useContext, useEffect, useState } from "react"; import { useContext, useEffect, useState } from "react";
import { WorkspaceContext } from "../WorkspaceContext"; import { WorkspaceContext } from "../WorkspaceContext";
import { formatTimestamp } from "../utils";
// @ts-ignore
import { app } from "/scripts/app.js";
import { Changelog, WorkflowVersion } from "../types/dbTypes"; import { Changelog, WorkflowVersion } from "../types/dbTypes";
import DeleteConfirm from "./DeleteConfirm"; import DeleteConfirm from "./DeleteConfirm";
import { app } from "../utils/comfyapp";
export function VersionHistoryDrawer({ onClose }: { onClose: () => void }) { export function VersionHistoryDrawer({ onClose }: { onClose: () => void }) {
const toast = useToast(); const { isDirty, loadWorkflowID, curVersion, session } =
const { curFlowID, isDirty, loadWorkflowID, curVersion } =
useContext(WorkspaceContext); useContext(WorkspaceContext);
const [active, setActive] = useState(0); // 0: version、1: changelog const [active, setActive] = useState(0); // 0: version、1: changelog
const [selectedVersion, setSelectedVersion] = useState<string | null>(null); const [selectedVersion, setSelectedVersion] = useState<string | null>(null);
const [changelogs, setChangelogs] = useState<Changelog[]>([]); const [changelogs, setChangelogs] = useState<Changelog[]>([]);
const [versions, setVersions] = useState<WorkflowVersion[]>([]); const [versions, setVersions] = useState<
(WorkflowVersion & { isCloud?: boolean })[]
>([]);
const curFlow = workflowsTable?.curWorkflow;
const cloudHost = userSettingsTable?.settings?.cloudHost;
const [loading, setLoading] = useState(false);
const loadChangeLogs = async (flowId: string) => { const loadChangeLogs = async (flowId: string) => {
const workflow = await workflowsTable?.get(flowId); const workflow = await workflowsTable?.get(flowId);
const changelogs = await changelogsTable?.listByWorkflowID(flowId); const changelogs = await changelogsTable?.listByWorkflowID(flowId);
@@ -53,8 +55,38 @@ export function VersionHistoryDrawer({ onClose }: { onClose: () => void }) {
}; };
const loadVersions = async () => { const loadVersions = async () => {
const vers = let vers =
(await workflowVersionsTable?.listByWorkflowID(curFlowID!)) ?? []; (await workflowVersionsTable?.listByWorkflowID(curFlow!.id)) ?? [];
if (session?.shareKey && curFlow?.cloudID) {
setLoading(true);
await fetch(
userSettingsTable?.settings?.cloudHost! +
"/api/listWorkflowVersionsByWorkflowID?workflowID=" +
curFlow?.cloudID,
{
headers: {
authorization: `Bearer ${session?.shareKey}`,
},
},
)
.then((resp) => resp.json())
.then((data) => {
if (data.items) {
const cloudVers = data.items.map((v: any) => {
return {
...v,
isCloud: true,
};
});
vers = vers.concat(cloudVers as WorkflowVersion[]);
}
})
.catch((e) => {
console.error(e);
});
setLoading(false);
}
setVersions(vers); setVersions(vers);
}; };
@@ -70,7 +102,7 @@ export function VersionHistoryDrawer({ onClose }: { onClose: () => void }) {
loadVersions(); loadVersions();
break; break;
case 1: case 1:
loadChangeLogs(curFlowID!); loadChangeLogs(curFlow!.id);
break; break;
} }
}, [active]); }, [active]);
@@ -117,7 +149,16 @@ export function VersionHistoryDrawer({ onClose }: { onClose: () => void }) {
</TabList> </TabList>
<TabPanels> <TabPanels>
<TabPanel> <TabPanel>
{session?.shareKey && (
<Text color="GrayText" mb={3}>
Connected to{" "}
<a href={cloudHost} target="_blank">
{cloudHost}
</a>
</Text>
)}
<Stack divider={<StackDivider />} spacing={2}> <Stack divider={<StackDivider />} spacing={2}>
{loading && <Text>Loading...</Text>}
{versions?.map((version) => { {versions?.map((version) => {
return ( return (
<Flex <Flex
@@ -131,11 +172,27 @@ export function VersionHistoryDrawer({ onClose }: { onClose: () => void }) {
borderRadius={4} borderRadius={4}
> >
<Stack textAlign={"left"} gap={0}> <Stack textAlign={"left"} gap={0}>
<Text fontWeight={"500"}> {version.isCloud ? (
{version.name ?? "untitled"} <a
</Text> target="_blank"
href={`${cloudHost}/workflow/${version.workflowID}/${version.id}`}
>
{version.name ?? "untitled"}
</a>
) : (
<Text fontWeight={"500"}>
{version.name ?? "untitled"}
</Text>
)}
<Text color={"GrayText"} fontSize={"sm"}> <Text color={"GrayText"} fontSize={"sm"}>
Created: {formatTimestamp(version.createTime)} Created:{" "}
{new Date(
version.createTime ??
version.createdAt ??
version.created_at ??
"",
).toLocaleString()}
</Text> </Text>
</Stack> </Stack>
<Flex alignItems="center" gap={2}> <Flex alignItems="center" gap={2}>
@@ -149,18 +206,19 @@ export function VersionHistoryDrawer({ onClose }: { onClose: () => void }) {
return; return;
} }
app.loadGraphData(JSON.parse(version.json)); app.loadGraphData(JSON.parse(version.json));
loadWorkflowID(curFlowID!, version.id);
onClose(); onClose();
}} }}
> >
Load Load
</Button> </Button>
<DeleteConfirm {!version.isCloud && (
promptMessage="Are you sure you want to delete this version?" <DeleteConfirm
onDelete={() => { promptMessage="Are you sure you want to delete this version?"
onDelete(version.id); onDelete={() => {
}} onDelete(version.id);
/> }}
/>
)}
</Flex> </Flex>
</Flex> </Flex>
); );
@@ -185,9 +243,6 @@ export function VersionHistoryDrawer({ onClose }: { onClose: () => void }) {
return; return;
} }
app.loadGraphData(JSON.parse(c.json)); app.loadGraphData(JSON.parse(c.json));
workflowsTable?.updateFlow(curFlowID!, {
json: c.json,
});
onClose(); onClose();
}} }}
isActive={c.id === selectedVersion} isActive={c.id === selectedVersion}
+76
View File
@@ -0,0 +1,76 @@
import { userSettingsTable, workflowsTable } from "../db-tables/WorkspaceDB";
import { getNodeDefs } from "../share/shareUtils";
import { EWorkflowPrivacy, Workflow } from "../types/dbTypes";
import { ShareWorkflowData } from "../types/types";
import { app } from "../utils/comfyapp";
export async function copySharelink(
shareKey: string,
curWorkflow: Workflow,
): Promise<{
link?: string | null;
error?: string | null;
} | null> {
if (curWorkflow.cloudID) {
const link =
userSettingsTable?.settings?.cloudHost +
"/workflow/" +
curWorkflow.cloudID;
return {
link,
};
}
const prompt = await app.graphToPrompt();
const graph = app.graph.serialize();
if (!graph.extra) {
graph.extra = {};
}
graph.extra.apiPrompt = prompt.output ?? null;
const input: ShareWorkflowData = {
workflow: {
name: curWorkflow?.name ?? "Untitled",
cloudID: curWorkflow?.cloudID,
},
version: {
name: "v1",
json: JSON.stringify(graph),
},
nodeDefs: getNodeDefs(),
privacy: EWorkflowPrivacy.UNLISTED,
};
return await fetch(
userSettingsTable?.settings?.cloudHost + "/api/createCloudflow",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${shareKey}`,
},
body: JSON.stringify(input),
},
)
.then((resp) => resp.json())
.then((data) => {
if (data?.data) {
const cloudID = data.data.workflowID;
workflowsTable?.updateMetaInfo(curWorkflow?.id!, {
cloudID,
});
const link =
userSettingsTable?.settings?.cloudHost + "/workflow/" + cloudID;
return {
link,
};
} else {
return {
error: "Failed to create version. " + (data?.error ?? ""),
};
}
})
.catch((e) => {
return {
error: "Failed to create version. " + (e?.error ?? ""),
};
});
}
+1 -2
View File
@@ -44,9 +44,8 @@ export class ChangelogsTable extends TableBase<Changelog> {
createTime: Date.now(), createTime: Date.now(),
isAutoSave: input.isAutoSave, isAutoSave: input.isAutoSave,
}; };
await this.deleteLogsExceedLimit(input.workflowID);
await indexdb.changelogs.add(change); await indexdb.changelogs.add(change);
await this.saveDiskDB(); await this.deleteLogsExceedLimit(input.workflowID);
return change; return change;
} }
async deleteLogsExceedLimit(workflowID: string) { async deleteLogsExceedLimit(workflowID: string) {
-93
View File
@@ -1,59 +1,6 @@
import { deleteFile, updateFile } from "../Api";
import { foldersTable, workflowsTable, userSettingsTable } from "./WorkspaceDB"; import { foldersTable, workflowsTable, userSettingsTable } from "./WorkspaceDB";
import {
COMFYSPACE_TRACKING_FIELD_NAME,
LEGACY_COMFYSPACE_TRACKING_FIELD_NAME,
} from "../const";
import { toFileNameFriendly } from "../utils";
import { Folder, Workflow } from "../types/dbTypes";
import { TwowayFolderSyncAPI } from "../apis/TwowaySyncFolderApi"; import { TwowayFolderSyncAPI } from "../apis/TwowaySyncFolderApi";
export async function saveJsonFileMyWorkflows(workflow: Workflow) {
const file_path = await generateFilePath(workflow);
if (file_path == null) {
return;
}
const fullPath = await generateFilePathAbsolute(workflow);
await workflowsTable?.updateMetaInfo(workflow.id, {
filePath: fullPath ?? undefined,
});
const json = workflow.json;
const flow = JSON.parse(json);
flow.extra[COMFYSPACE_TRACKING_FIELD_NAME] = {
id: workflow.id,
name: workflow.name,
};
delete flow.extra[LEGACY_COMFYSPACE_TRACKING_FIELD_NAME];
await updateFile(file_path, JSON.stringify(flow));
}
export async function deleteJsonFileMyWorkflows(workflow: Workflow) {
if (workflow.name == null) {
return;
}
const file_path = await generateFilePath(workflow);
file_path != null && deleteFile(file_path);
}
export async function generateFilePath(
workflow: Workflow,
): Promise<string | null> {
let filePath = toFileNameFriendly(workflow.name) + ".json";
let curFolderID = workflow.parentFolderID;
while (curFolderID != null) {
const folder = await foldersTable?.get(curFolderID);
if (folder == null) {
break;
}
const folderName = folder.name;
filePath = `${folderName}/${filePath}`;
curFolderID = folder.parentFolderID ?? undefined;
}
return filePath ?? null;
}
export async function genFolderRelPath( export async function genFolderRelPath(
folderId: string | null, folderId: string | null,
): Promise<string> { ): Promise<string> {
@@ -71,46 +18,6 @@ export async function genFolderRelPath(
return filePath; return filePath;
} }
export async function generateFilePathAbsolute(
workflow: Workflow,
): Promise<string | null> {
const subPath = await generateFilePath(workflow);
let myWorkflowsDir = await userSettingsTable?.getSetting("myWorkflowsDir");
if (!myWorkflowsDir) {
console.error("myWorkflowsDir is not set");
return null;
}
if (!myWorkflowsDir.endsWith("/")) {
myWorkflowsDir = myWorkflowsDir + "/";
}
return myWorkflowsDir + subPath;
}
export async function generateFolderPath(id: string): Promise<string | null> {
const folder = await foldersTable?.get(id);
let parentFolderID = folder?.parentFolderID;
let folderPath = folder?.name;
while (parentFolderID) {
const folder = await foldersTable?.get(parentFolderID);
if (folder == null) {
break;
}
folderPath = `${folder.name}/${folderPath}`;
parentFolderID = folder.parentFolderID ?? undefined;
}
let myWorkflowsDir = await userSettingsTable?.getSetting("myWorkflowsDir");
if (!myWorkflowsDir) {
console.error("myWorkflowsDir is not set");
return null;
}
if (!myWorkflowsDir.endsWith("/")) {
myWorkflowsDir = myWorkflowsDir + "/";
}
return myWorkflowsDir + folderPath;
}
export async function getFileCountInFolder(folderId: string): Promise<number> { export async function getFileCountInFolder(folderId: string): Promise<number> {
const twoWaySyncEnabled = await userSettingsTable?.getSetting("twoWaySync"); const twoWaySyncEnabled = await userSettingsTable?.getSetting("twoWaySync");
-6
View File
@@ -1,6 +1,5 @@
import { userSettingsTable, workflowsTable } from "./WorkspaceDB"; import { userSettingsTable, workflowsTable } from "./WorkspaceDB";
import { EFlowOperationType, Folder } from "../types/dbTypes"; import { EFlowOperationType, Folder } from "../types/dbTypes";
import { validateOrSaveAllJsonFileMyWorkflows } from "../utils";
import { nanoid } from "nanoid"; import { nanoid } from "nanoid";
import { TableBase } from "./TableBase"; import { TableBase } from "./TableBase";
import { indexdb } from "./indexdb"; import { indexdb } from "./indexdb";
@@ -84,11 +83,6 @@ export class FoldersTable extends TableBase<Folder> {
} }
await indexdb.folders.update(id, input); await indexdb.folders.update(id, input);
this.saveDiskDB(); this.saveDiskDB();
// folder moved or renamed - move all workflows to the right directory(not required when folded state changes)
if (nameChanged || parentFolderChanged) {
validateOrSaveAllJsonFileMyWorkflows(true);
}
return newRecord; return newRecord;
} }
public async deleteFolder( public async deleteFolder(
-12
View File
@@ -2,7 +2,6 @@ import { Table, workflowsTable } from "./WorkspaceDB";
import { TableBase } from "./TableBase"; import { TableBase } from "./TableBase";
import { Media } from "../types/dbTypes"; import { Media } from "../types/dbTypes";
import { indexdb } from "./indexdb"; import { indexdb } from "./indexdb";
import { getMetadataFromUrl } from "../gallery/utils.ts";
export class MediaTable extends TableBase<Media> { export class MediaTable extends TableBase<Media> {
static readonly TABLE_NAME: Table = "media"; static readonly TABLE_NAME: Table = "media";
@@ -25,28 +24,17 @@ export class MediaTable extends TableBase<Media> {
const format = input.localPath.split(".").pop(); const format = input.localPath.split(".").pop();
if (format == null) return null; if (format == null) return null;
const res = await getMetadataFromUrl(
`/workspace/view_media?filename=${input.localPath}`,
).catch((e) => {
console.error("get meta error:", e);
return { prompt: "" };
});
const md: Media = { const md: Media = {
id: input.localPath, id: input.localPath,
localPath: input.localPath, localPath: input.localPath,
workflowID: input.workflowID, workflowID: input.workflowID,
createTime: Date.now(), createTime: Date.now(),
workflowJSON: JSON.stringify(res?.prompt),
format: format,
}; };
await workflowsTable?.updateMetaInfo(input.workflowID, { await workflowsTable?.updateMetaInfo(input.workflowID, {
latestImage: md.localPath, latestImage: md.localPath,
}); });
// save indexdb // save indexdb
indexdb.media.put(md); indexdb.media.put(md);
// save disk file db
this.saveDiskDB();
return md; return md;
} }
+2 -5
View File
@@ -12,6 +12,8 @@ export class TableBase<T extends TableBaseModel> {
this.tableName = tableName; this.tableName = tableName;
} }
protected async saveDiskDB() { protected async saveDiskDB() {
// diable save diskdb
return;
const objs = (await indexdb[this.tableName].toArray()) as TableBaseModel[]; const objs = (await indexdb[this.tableName].toArray()) as TableBaseModel[];
const backup: Record<string, TableBaseModel> = {}; const backup: Record<string, TableBaseModel> = {};
objs.forEach((f) => { objs.forEach((f) => {
@@ -43,23 +45,19 @@ export class TableBase<T extends TableBaseModel> {
newItem.createTime = Date.now(); newItem.createTime = Date.now();
} }
await indexdb[this.tableName].add(newItem as any); await indexdb[this.tableName].add(newItem as any);
await this.saveDiskDB();
return newItem as T; return newItem as T;
} }
public async put(newItem: T): Promise<T> { public async put(newItem: T): Promise<T> {
await indexdb[this.tableName].put(newItem as any); await indexdb[this.tableName].put(newItem as any);
await this.saveDiskDB();
return newItem; return newItem;
} }
public async bulkPut(newItems: T[]): Promise<void> { public async bulkPut(newItems: T[]): Promise<void> {
// @ts-ignore // @ts-ignore
await indexdb[this.tableName].bulkPut(newItems as any); await indexdb[this.tableName].bulkPut(newItems as any);
this.saveDiskDB();
} }
public async update(id: string, changes: Partial<T>): Promise<T | null> { public async update(id: string, changes: Partial<T>): Promise<T | null> {
await indexdb[this.tableName].update(id, changes); await indexdb[this.tableName].update(id, changes);
this.saveDiskDB();
return (await this.get(id)) ?? null; return (await this.get(id)) ?? null;
} }
@@ -106,7 +104,6 @@ export class TableBase<T extends TableBaseModel> {
public async delete(id: string) { public async delete(id: string) {
await indexdb[this.tableName].delete(id); await indexdb[this.tableName].delete(id);
this.saveDiskDB();
} }
public async listByIndex(index: keyof T, value: string): Promise<T[]> { public async listByIndex(index: keyof T, value: string): Promise<T[]> {
const list = await indexdb[this.tableName] const list = await indexdb[this.tableName]
+26 -19
View File
@@ -1,29 +1,19 @@
import type { UserSettings } from "../types/dbTypes"; import type { UserSettings } from "../types/dbTypes";
import { TableBase } from "./TableBase"; import { TableBase } from "./TableBase";
import { MODEL_TYPE_TO_FOLDER_MAPPING } from "../model-manager/install-models/util/modelTypes"; import { MODEL_TYPE_TO_FOLDER_MAPPING } from "../model-manager/install-models/util/modelTypes";
import { fetchMyWorkflowsDir } from "../Api"; import { fetchApi, fetchMyWorkflowsDir } from "../Api";
export class UserSettingsTable extends TableBase<UserSettings> { export class UserSettingsTable extends TableBase<UserSettings> {
public defaultSettings: UserSettings; public defaultSettings: UserSettings;
public readonly DEFAULT_USER = "guest"; public readonly DEFAULT_USER = "guest";
static readonly TABLE_NAME = "userSettings"; static readonly TABLE_NAME = "userSettings";
/**
* Because in App.js we will use window.addEventListener("beforeunload", handleBeforeUnload); to remind the user to save the workflow when the user leaves the page.
* The autoSave needs to be obtained in the handleBeforeUnload function. If it is obtained through getSetting, the handleBeforeUnload function will become an async function, which will cause the "beforeunload" event to fail.
* So we maintain an autoSave here that is always up to date.
*/
private _autoSave: boolean = false;
private _settings: UserSettings | undefined = undefined; private _settings: UserSettings | undefined = undefined;
get settings() { get settings() {
return this._settings; return this._settings;
} }
get autoSave() {
return this._autoSave;
}
constructor() { constructor() {
super("userSettings"); super("userSettings");
this.defaultSettings = { this.defaultSettings = {
@@ -43,8 +33,7 @@ export class UserSettingsTable extends TableBase<UserSettings> {
autoSaveDuration: 3, autoSaveDuration: 3,
twoWaySync: false, twoWaySync: false,
foldersOnTop: false, foldersOnTop: false,
cloudHost: "https://www.nodecafe.org", cloudHost: "https://www.nodecafe.co",
overwriteCurWorkflowWhenDroppingFileToCanvas: false,
maximumChangelogNumber: 80, maximumChangelogNumber: 80,
hideCoverImage: false, hideCoverImage: false,
disableUnsavedWarning: false, disableUnsavedWarning: false,
@@ -65,6 +54,14 @@ export class UserSettingsTable extends TableBase<UserSettings> {
} }
return currentUserSettings?.[key] ?? this.defaultSettings[key]; return currentUserSettings?.[key] ?? this.defaultSettings[key];
} }
public async get(_id: string): Promise<UserSettings | undefined> {
const obj = await fetchApi("/workspace/get_settings", {
headers: {
"Content-Type": "application/json",
},
}).then((res) => res.json());
return obj as any;
}
public async upsert(newPairs: Partial<UserSettings>) { public async upsert(newPairs: Partial<UserSettings>) {
const oldSettings = const oldSettings =
@@ -73,7 +70,13 @@ export class UserSettingsTable extends TableBase<UserSettings> {
...oldSettings, ...oldSettings,
...newPairs, ...newPairs,
}; };
await this.put(newSettings); await fetchApi("/workspace/save_settings", {
method: "POST",
body: JSON.stringify(newSettings),
headers: {
"Content-Type": "application/json",
},
});
this._settings = { this._settings = {
...this.defaultSettings, ...this.defaultSettings,
...newSettings, ...newSettings,
@@ -87,16 +90,20 @@ export class UserSettingsTable extends TableBase<UserSettings> {
instance.defaultSettings.myWorkflowsDir = myWorkflowsDir.path!; instance.defaultSettings.myWorkflowsDir = myWorkflowsDir.path!;
await instance.get(instance.DEFAULT_USER).then((res) => { await instance.get(instance.DEFAULT_USER).then((res) => {
instance._autoSave = res?.autoSave ?? false;
instance._settings = { instance._settings = {
...instance.defaultSettings, ...instance.defaultSettings,
...res, ...res,
}; };
}); });
// overwrite legacy comfyspace.art if (
await instance.upsert({ instance._settings?.cloudHost?.includes("nodecafe.org") ||
cloudHost: instance.defaultSettings.cloudHost, instance._settings?.cloudHost?.includes("comfyspace.art")
}); ) {
// overwrite legacy comfyspace.art
await instance.upsert({
cloudHost: instance.defaultSettings.cloudHost,
});
}
return instance; return instance;
} }
} }
+1 -34
View File
@@ -8,10 +8,6 @@ import { sortFileItem } from "../utils";
import { nanoid } from "nanoid"; import { nanoid } from "nanoid";
import { TableBase } from "./TableBase"; import { TableBase } from "./TableBase";
import { indexdb } from "./indexdb"; import { indexdb } from "./indexdb";
import {
deleteJsonFileMyWorkflows,
saveJsonFileMyWorkflows,
} from "./DiskFileUtils";
import { ESortTypes, ImportWorkflow } from "../RecentFilesDrawer/types"; import { ESortTypes, ImportWorkflow } from "../RecentFilesDrawer/types";
import { defaultGraph } from "../defaultGraph"; import { defaultGraph } from "../defaultGraph";
import { scanMyWorkflowsDir } from "../utils/twowaySyncUtils"; import { scanMyWorkflowsDir } from "../utils/twowaySyncUtils";
@@ -51,11 +47,7 @@ export class WorkflowsTable extends TableBase<Workflow> {
} }
/** /**
* Check whether the currently opened workflow is the latest version and is consistent with the DB. * Check whether the currently opened workflow is the latest version and is consistent with the DB
* Through updateTime comparison, if it is inconsistent, it means that a newer version already exists in the DB.
* If the automatic save function is turned on at this time, the latest version in the DB will be overwritten.
* Therefore, the user needs to confirm whether to continue to enable automatic saving.
* @returns boolean
*/ */
public async latestVersionCheck() { public async latestVersionCheck() {
if (this._curWorkflow) { if (this._curWorkflow) {
@@ -139,15 +131,11 @@ export class WorkflowsTable extends TableBase<Workflow> {
}; };
//add to IndexDB //add to IndexDB
await indexdb.workflows.add(newWorkflow); await indexdb.workflows.add(newWorkflow);
// add to disk file db
this.saveDiskDB();
// add to my_workflows/ // add to my_workflows/
const twoWaySyncEnabled = await userSettingsTable?.getSetting("twoWaySync"); const twoWaySyncEnabled = await userSettingsTable?.getSetting("twoWaySync");
if (twoWaySyncEnabled) { if (twoWaySyncEnabled) {
await TwowaySyncAPI.createWorkflow(newWorkflow); await TwowaySyncAPI.createWorkflow(newWorkflow);
return await this.get(newWorkflow.id); return await this.get(newWorkflow.id);
} else {
saveJsonFileMyWorkflows(newWorkflow);
} }
return newWorkflow; return newWorkflow;
} }
@@ -184,7 +172,6 @@ export class WorkflowsTable extends TableBase<Workflow> {
if (this._curWorkflow && this._curWorkflow.id === id) { if (this._curWorkflow && this._curWorkflow.id === id) {
this._curWorkflow = newWorkflow; this._curWorkflow = newWorkflow;
} }
this.saveDiskDB();
return newWorkflow; return newWorkflow;
} }
@@ -197,15 +184,6 @@ export class WorkflowsTable extends TableBase<Workflow> {
} }
if (twoWaySyncEnabled) { if (twoWaySyncEnabled) {
await TwowaySyncAPI.moveWorkflow(oldWorkflow, change.parentFolderID!); await TwowaySyncAPI.moveWorkflow(oldWorkflow, change.parentFolderID!);
} else {
await saveJsonFileMyWorkflows(newWorkflow);
await deleteJsonFileMyWorkflows(oldWorkflow);
// update parent folder updateTime
if (newWorkflow?.parentFolderID != null) {
await indexdb.folders?.update(newWorkflow.parentFolderID, {
updateTime: Date.now(),
});
}
} }
} }
public async genLastManualSavedJson(id: string) { public async genLastManualSavedJson(id: string) {
@@ -240,8 +218,6 @@ export class WorkflowsTable extends TableBase<Workflow> {
const twoWaySyncEnabled = await userSettingsTable?.getSetting("twoWaySync"); const twoWaySyncEnabled = await userSettingsTable?.getSetting("twoWaySync");
if (twoWaySyncEnabled) { if (twoWaySyncEnabled) {
after && (await TwowaySyncAPI.saveWorkflow(after)); after && (await TwowaySyncAPI.saveWorkflow(after));
} else {
after && (await saveJsonFileMyWorkflows(after));
} }
} }
@@ -294,13 +270,10 @@ export class WorkflowsTable extends TableBase<Workflow> {
} catch (e) { } catch (e) {
console.error("batchCreateFlows error", e); console.error("batchCreateFlows error", e);
} }
} else {
await saveJsonFileMyWorkflows(newWorkflow);
} }
} }
try { try {
await indexdb.workflows.bulkAdd(newWorkflows); await indexdb.workflows.bulkAdd(newWorkflows);
this.saveDiskDB();
} catch (e) { } catch (e) {
console.error("batchCreateFlows error", e); console.error("batchCreateFlows error", e);
} }
@@ -314,13 +287,10 @@ export class WorkflowsTable extends TableBase<Workflow> {
await userSettingsTable?.getSetting("twoWaySync"); await userSettingsTable?.getSetting("twoWaySync");
if (twoWaySyncEnabled) { if (twoWaySyncEnabled) {
await TwowaySyncAPI.deleteWorkflow(workflow); await TwowaySyncAPI.deleteWorkflow(workflow);
} else {
deleteJsonFileMyWorkflows({ ...workflow });
} }
} }
//add to IndexDB //add to IndexDB
await indexdb.workflows.delete(id); await indexdb.workflows.delete(id);
this.saveDiskDB();
} }
public async batchDeleteFlow(ids: string[]) { public async batchDeleteFlow(ids: string[]) {
@@ -331,12 +301,9 @@ export class WorkflowsTable extends TableBase<Workflow> {
await userSettingsTable?.getSetting("twoWaySync"); await userSettingsTable?.getSetting("twoWaySync");
if (twoWaySyncEnabled) { if (twoWaySyncEnabled) {
await TwowaySyncAPI.deleteWorkflow(flow); await TwowaySyncAPI.deleteWorkflow(flow);
} else {
deleteJsonFileMyWorkflows({ ...flow });
} }
} }
await indexdb.workflows.bulkDelete(ids); await indexdb.workflows.bulkDelete(ids);
this.saveDiskDB();
} }
public async listFolderContent( public async listFolderContent(
-82
View File
@@ -61,86 +61,4 @@ export async function loadDBs() {
loadMedia(), loadMedia(),
loadWorkflowVersions(), loadWorkflowVersions(),
]); ]);
if (localStorage.getItem("WORKSPACE_INDEXDB_BACKFILL") !== "true") {
await backfillIndexdb();
localStorage.setItem("WORKSPACE_INDEXDB_BACKFILL", "true");
}
}
export async function backfillIndexdb() {
const backfillWorkflows = async () => {
try {
const all = await workflowsTable?.getRecords();
all && (await indexdb.workflows.bulkPut(Object.values(all)));
} catch (error) {
console.error(error);
}
};
const backfillFolders = async () => {
try {
const all = await foldersTable?.getRecords();
all && (await indexdb.folders.bulkPut(Object.values(all)));
} catch (error) {
console.error(error);
}
};
const backfillMedia = async () => {
try {
const all = await mediaTable?.getRecords();
all && (await indexdb.media.bulkPut(Object.values(all)));
} catch (error) {
console.error(error);
}
};
const backfillChangelogs = async () => {
try {
const all = await changelogsTable?.getRecords();
all && (await indexdb.changelogs.bulkPut(Object.values(all)));
} catch (error) {
console.error(error);
}
};
const backfillTags = async () => {
try {
const all = await tagsTable?.getRecords();
all && (await indexdb.tags.bulkPut(Object.values(all)));
} catch (error) {
console.error(error);
}
};
const backfillUserSettings = async () => {
try {
const tableInstance = userSettingsTable!;
const backupData = await tableInstance.getRecords().then((data) => {
if (!data[tableInstance.DEFAULT_USER]) {
// legacy
return data;
}
return data[tableInstance.DEFAULT_USER];
});
await indexdb.userSettings.put({
...tableInstance.defaultSettings,
...backupData,
});
} catch (error) {
console.error(error);
}
};
const backfillWorkflowVersions = async () => {
try {
const all = await workflowVersionsTable?.getRecords();
all && (await indexdb.workflowVersions.bulkPut(Object.values(all)));
} catch (error) {
console.error(error);
}
};
await Promise.all([
backfillWorkflows(),
backfillFolders(),
backfillMedia(),
backfillChangelogs(),
backfillTags(),
backfillUserSettings(),
backfillWorkflowVersions(),
]);
} }
-3
View File
@@ -1,8 +1,5 @@
// @ts-expect-error ComfyUI import
import { app } from "/scripts/app.js";
import { import {
Checkbox, Checkbox,
Flex,
Heading, Heading,
HStack, HStack,
IconButton, IconButton,
@@ -1,6 +1,5 @@
import { FC } from "react"; import { FC } from "react";
import { Flex, Select } from "@chakra-ui/react"; import { Flex, Select } from "@chakra-ui/react";
import { FormItem } from "./types.ts";
import { PromptNodeInputItem } from "../MetaBox/utils.ts"; import { PromptNodeInputItem } from "../MetaBox/utils.ts";
export const SelectBase: FC< export const SelectBase: FC<
@@ -1,9 +1,9 @@
import { MetaData, getMetadataFromUrl } from "../../utils.ts"; import { getMetadataFromUrl } from "../../utils.ts";
import { Flex, HStack, Switch } from "@chakra-ui/react"; import { Flex, HStack, Switch } from "@chakra-ui/react";
import { Media } from "../../../types/dbTypes.ts"; import { Media } from "../../../types/dbTypes.ts";
import TopForm from "../TopForm/TopForm.tsx"; import TopForm from "../TopForm/TopForm.tsx";
import AllPromptForm from "../AllPromptForm/AllPromptForm.tsx"; import AllPromptForm from "../AllPromptForm/AllPromptForm.tsx";
import { useContext, useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { FormItem } from "../FormItem/types.ts"; import { FormItem } from "../FormItem/types.ts";
import { import {
calcInputListRecursive, calcInputListRecursive,
@@ -11,10 +11,7 @@ import {
PromptNodeInputItem, PromptNodeInputItem,
} from "./utils.ts"; } from "./utils.ts";
import { MetaBoxContext } from "./metaBoxContext.ts"; import { MetaBoxContext } from "./metaBoxContext.ts";
import { workflowsTable } from "../../../db-tables/WorkspaceDB.ts"; import { app } from "../../../utils/comfyapp.ts";
import { WorkspaceContext } from "../../../WorkspaceContext.ts";
// @ts-ignore
import { app } from "/scripts/app.js";
export type TopFieldType = { export type TopFieldType = {
promptKey: string | number; promptKey: string | number;
class_type?: string; class_type?: string;
@@ -35,7 +32,6 @@ export const isInTopField = (
export default function MetadataForm({ media }: { media: Media | null }) { export default function MetadataForm({ media }: { media: Media | null }) {
const [calcInputList, setCalcInputList] = useState<PromptNodeInputItem[]>([]); const [calcInputList, setCalcInputList] = useState<PromptNodeInputItem[]>([]);
const { curFlowID } = useContext(WorkspaceContext);
const [imagePrompt, setImagePrompt] = useState<ImagePrompt>(); const [imagePrompt, setImagePrompt] = useState<ImagePrompt>();
const [showAllInputs, setShowAllInputs] = useState(true); const [showAllInputs, setShowAllInputs] = useState(true);
const [showNodeName, setShowNodeName] = useState(true); const [showNodeName, setShowNodeName] = useState(true);
@@ -64,18 +60,6 @@ export default function MetadataForm({ media }: { media: Media | null }) {
const [topFields, setTopFields] = useState<TopFieldType[]>([]); const [topFields, setTopFields] = useState<TopFieldType[]>([]);
useEffect(() => {
(async () => {
if (curFlowID) {
const topFieldsConfig = (await workflowsTable?.get(curFlowID))
?.topFieldsConfig;
if (topFieldsConfig) {
setTopFields(topFieldsConfig);
setShowAllInputs(false);
}
}
})();
}, [curFlowID]);
const updateTopField = (field: TopFieldType) => { const updateTopField = (field: TopFieldType) => {
if ( if (
isInTopField(topFields, { isInTopField(topFields, {
@@ -88,19 +72,9 @@ export default function MetadataForm({ media }: { media: Media | null }) {
(v) => v.name !== field.name || v.promptKey !== field.promptKey, (v) => v.name !== field.name || v.promptKey !== field.promptKey,
); );
setTopFields(topFieldsConfig); setTopFields(topFieldsConfig);
if (curFlowID) {
workflowsTable?.updateTopFields(curFlowID, {
topFieldsConfig,
});
}
} else { } else {
const topFieldsConfig = [...topFields, field]; const topFieldsConfig = [...topFields, field];
setTopFields(topFieldsConfig); setTopFields(topFieldsConfig);
if (curFlowID) {
workflowsTable?.updateTopFields(curFlowID, {
topFieldsConfig,
});
}
} }
}; };
+52 -17
View File
@@ -1,12 +1,11 @@
import React, { Suspense } from "react"; import React, { Suspense } from "react";
import ReactDOM from "react-dom/client"; import ReactDOM from "react-dom/client";
import { ColorModeScript } from "@chakra-ui/react"; import { ColorModeScript, type StyleFunctionProps } from "@chakra-ui/react";
import { ChakraProvider, extendTheme } from "@chakra-ui/react"; import { ChakraProvider, extendTheme } from "@chakra-ui/react";
import { AlertDialogProvider } from "./components/AlertDialogProvider.tsx"; import { AlertDialogProvider } from "./components/AlertDialogProvider.tsx";
import CSSReset from "./MyCSSReset.tsx"; import CSSReset from "./MyCSSReset.tsx";
import { waitForApp } from "./utils/comfyapp.ts";
const topbar = document.createElement("div");
document.body.append(topbar);
const App = React.lazy(() => const App = React.lazy(() =>
import("./App.tsx").then(({ default: App }) => ({ import("./App.tsx").then(({ default: App }) => ({
default: App, default: App,
@@ -35,23 +34,22 @@ const zIndices = {
}; };
const theme = extendTheme({ const theme = extendTheme({
config: {
initialColorMode: "dark",
useSystemColorMode: false,
},
zIndices, zIndices,
components: {
Card: {
baseStyle: (props: StyleFunctionProps) => ({
container: {
backgroundColor: props.colorMode === "dark" ? "#171B21" : "#F6F8FA",
},
}),
},
},
}); });
ReactDOM.createRoot(topbar).render(
<React.StrictMode>
<ChakraProvider resetCSS={false} disableGlobalStyle={true} theme={theme}>
<CSSReset scope=".workspace_manager" />
<ColorModeScript initialColorMode="dark" />
<AlertDialogProvider>
<Suspense>
<App />
</Suspense>
</AlertDialogProvider>
</ChakraProvider>
</React.StrictMode>,
);
// hacky fix for chakra add extra className (chakra-ui-light) into body // hacky fix for chakra add extra className (chakra-ui-light) into body
// and resulted in user unable to copy new nodes into clipboard, because of this check: e.target.className === "litegraph" // and resulted in user unable to copy new nodes into clipboard, because of this check: e.target.className === "litegraph"
// (https://github.com/comfyanonymous/ComfyUI/blob/57926635e8d84ae9eea4a0416cc75e363f5ede45/web/scripts/app.js#L861) // (https://github.com/comfyanonymous/ComfyUI/blob/57926635e8d84ae9eea4a0416cc75e363f5ede45/web/scripts/app.js#L861)
@@ -83,3 +81,40 @@ const callback = function (
}; };
const observer = new MutationObserver(callback); const observer = new MutationObserver(callback);
observer.observe(targetNode, observerConfig); observer.observe(targetNode, observerConfig);
function waitForDocumentBody() {
return new Promise((resolve) => {
if (document.body) {
return resolve(document.body);
}
document.addEventListener("DOMContentLoaded", () => {
resolve(document.body);
});
});
}
// wait for document.body to load so that the top menu is loaded and my react component has a place to mount
waitForDocumentBody()
.then(() => waitForApp())
.then(() => {
const topbar = document.createElement("div");
document.body.append(topbar);
ReactDOM.createRoot(topbar).render(
<React.StrictMode>
<ChakraProvider
resetCSS={false}
disableGlobalStyle={true}
theme={theme}
>
<CSSReset scope=".workspace_manager" />
<ColorModeScript initialColorMode="dark" />
<AlertDialogProvider>
<Suspense>
<App />
</Suspense>
</AlertDialogProvider>
</ChakraProvider>
</React.StrictMode>,
);
});
@@ -59,11 +59,8 @@ export default function InatallModelsModal({
>(MODEL_TYPE_TO_FOLDER_MAPPING); >(MODEL_TYPE_TO_FOLDER_MAPPING);
const loadData = useCallback(async () => { const loadData = useCallback(async () => {
setLoading(true); setLoading(true);
// if (!searchQuery) { const models = await getModelFromCivitAPi(modelType, searchQuery);
// const models = await getModelFromCivitAPi(modelType); // const models = await getModelFromSearch(searchQuery, modelType);
// setModels(models);
// } else {
const models = await getModelFromSearch(searchQuery, modelType);
setModels(models); setModels(models);
const folders_list = await getAllFoldersList(); const folders_list = await getAllFoldersList();
folders_list && setFoldersList(folders_list); folders_list && setFoldersList(folders_list);
@@ -1,5 +1,4 @@
// @ts-ignore // @ts-ignore
import { api } from "/scripts/api.js";
import { import {
Button, Button,
HStack, HStack,
@@ -11,6 +10,7 @@ import {
} from "@chakra-ui/react"; } from "@chakra-ui/react";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { cancelDownload } from "../../Api"; import { cancelDownload } from "../../Api";
import { api } from "../../utils/comfyapp";
type Queue = { save_path: string; progress: number }; type Queue = { save_path: string; progress: number };
@@ -1,4 +1,3 @@
import { userSettingsTable } from "../../../db-tables/WorkspaceDB";
import { indexdb } from "../../../db-tables/indexdb"; import { indexdb } from "../../../db-tables/indexdb";
import { CivitiModel } from "../../types"; import { CivitiModel } from "../../types";
import { CACHE_EXPIRY_DAYS, MODEL_TYPE } from "./modelTypes"; import { CACHE_EXPIRY_DAYS, MODEL_TYPE } from "./modelTypes";
@@ -7,20 +6,19 @@ type CivitModelQueryParams = {
types?: MODEL_TYPE; types?: MODEL_TYPE;
query?: string; query?: string;
limit?: string; limit?: string;
nsfw?: boolean;
}; };
export async function getModelFromCivitAPi( export async function getModelFromCivitAPi(
types?: MODEL_TYPE, types?: MODEL_TYPE,
query?: string,
): Promise<CivitiModel[]> { ): Promise<CivitiModel[]> {
const showNsfwThumbnail = await userSettingsTable?.getSetting(
"showNsfwModelThumbnail",
);
const params: CivitModelQueryParams = { const params: CivitModelQueryParams = {
limit: "30", limit: "30",
nsfw: showNsfwThumbnail ?? false,
types, types,
}; };
if (query) {
params.query = query;
}
const queryString = new URLSearchParams(params).toString(); const queryString = new URLSearchParams(params).toString();
const fullURL = `https://civitai.com/api/v1/models?${queryString}`; const fullURL = `https://civitai.com/api/v1/models?${queryString}`;
@@ -9,7 +9,7 @@ export async function getModelFromSearch(
queries: [ queries: [
{ {
q: q, q: q,
indexUid: "models_v8", indexUid: "models_v9",
facets: [ facets: [
"category.name", "category.name",
"checkpointType", "checkpointType",
@@ -12,13 +12,12 @@ import {
import { IconExternalLink } from "@tabler/icons-react"; import { IconExternalLink } from "@tabler/icons-react";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { COMFYSPACE_TRACKING_FIELD_NAME } from "../../const"; import { COMFYSPACE_TRACKING_FIELD_NAME } from "../../const";
// @ts-ignore
import { app } from "/scripts/app.js";
import type { import type {
DepsResult, DepsResult,
ModelFile, ModelDep,
} from "../../spacejson/handleDownloadSpaceJson"; } from "../../spacejson/handleDownloadSpaceJson";
import { indexdb } from "../../db-tables/indexdb"; import { indexdb } from "../../db-tables/indexdb";
import { app } from "../../utils/comfyapp";
const HF_LOGO = const HF_LOGO =
"https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo.png"; "https://huggingface.co/datasets/huggingface/brand-assets/resolve/main/hf-logo.png";
@@ -33,8 +32,8 @@ export interface MissingModel {
interface Props { interface Props {
model: MissingModel; model: MissingModel;
setSelectedModelDeps: (deps: ModelFile[]) => void; setSelectedModelDeps: (deps: ModelDep[]) => void;
selectedModelDeps: ModelFile[]; selectedModelDeps: ModelDep[];
foldersList: Record<string, string[]>; foldersList: Record<string, string[]>;
setFoldersList: (folders: Record<string, string[]>) => void; setFoldersList: (folders: Record<string, string[]>) => void;
} }
@@ -47,7 +46,7 @@ export default function MissingModelItem({
setFoldersList, setFoldersList,
}: Props) { }: Props) {
const [suggestedModel, setSuggestedModel] = useState< const [suggestedModel, setSuggestedModel] = useState<
ModelFile | { existingModel: string } ModelDep | { existingModel: string }
>(); >();
const modelDeps: DepsResult["models"] = const modelDeps: DepsResult["models"] =
app.graph.extra?.[COMFYSPACE_TRACKING_FIELD_NAME]?.deps?.models; app.graph.extra?.[COMFYSPACE_TRACKING_FIELD_NAME]?.deps?.models;
@@ -77,7 +76,7 @@ export default function MissingModelItem({
const selectedModelNames = selectedModelDeps.map((dep) => dep.filename); const selectedModelNames = selectedModelDeps.map((dep) => dep.filename);
function isExistingModel( function isExistingModel(
model: ModelFile | { existingModel: string }, model: ModelDep | { existingModel: string },
): model is { existingModel: string } { ): model is { existingModel: string } {
return (model as { existingModel: string }).existingModel != null; return (model as { existingModel: string }).existingModel != null;
} }
@@ -10,15 +10,14 @@ import {
useToast, useToast,
} from "@chakra-ui/react"; } from "@chakra-ui/react";
import { useCallback, useContext, useEffect, useState } from "react"; import { useCallback, useContext, useEffect, useState } from "react";
// @ts-ignore
import { app } from "/scripts/app.js";
import MissingModelItem from "./MissingModelItem"; import MissingModelItem from "./MissingModelItem";
import { DRAWER_Z_INDEX } from "../../const"; import { DRAWER_Z_INDEX } from "../../const";
import type { ModelFile } from "../../spacejson/handleDownloadSpaceJson"; import type { ModelDep } from "../../spacejson/handleDownloadSpaceJson";
import { getAllFoldersList } from "../../Api"; import { getAllFoldersList } from "../../Api";
import { installModelsApi } from "../api/modelsApi"; import { installModelsApi } from "../api/modelsApi";
import { getCivitApiKey } from "../../utils/civitUtils"; import { getCivitApiKey } from "../../utils/civitUtils";
import { WorkspaceContext } from "../../WorkspaceContext"; import { WorkspaceContext } from "../../WorkspaceContext";
import { app } from "../../utils/comfyapp";
export interface MissingModel { export interface MissingModel {
class_type: string; class_type: string;
@@ -41,7 +40,7 @@ export default function MissingModelsListDrawer({
app.canvasEl.removeEventListener("click", onClose); app.canvasEl.removeEventListener("click", onClose);
}; };
}, []); }, []);
const [selectedModelDeps, setSelectedModelDeps] = useState<ModelFile[]>([]); const [selectedModelDeps, setSelectedModelDeps] = useState<ModelDep[]>([]);
const [foldersList, setFoldersList] = useState<Record<string, string[]>>({}); const [foldersList, setFoldersList] = useState<Record<string, string[]>>({});
const { setRoute } = useContext(WorkspaceContext); const { setRoute } = useContext(WorkspaceContext);
const loadData = useCallback(async () => { const loadData = useCallback(async () => {
@@ -78,7 +77,7 @@ export default function MissingModelsListDrawer({
} }
installModelsApi({ installModelsApi({
file_hash: model.fileHash ?? undefined, file_hash: model.fileHash ?? undefined,
filename: model.filename, filename: model.name,
save_path: foldersList[model.fileFolder][0], save_path: foldersList[model.fileFolder][0],
url, url,
force_filename: true, force_filename: true,
@@ -13,8 +13,6 @@ import Fuse from "fuse.js/min-basic";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { ModelsTags } from "./ModelsTags"; import { ModelsTags } from "./ModelsTags";
import { ModelsList } from "./ModelsList"; import { ModelsList } from "./ModelsList";
// @ts-expect-error ComfyUI imports
import { app } from "/scripts/app.js";
import InstallModelsButton from "../install-models/InstallModelsButton"; import InstallModelsButton from "../install-models/InstallModelsButton";
import { type ModelsListRespItem } from "../types"; import { type ModelsListRespItem } from "../types";
import { useUpdateModels } from "../hooks/useUpdateModels"; import { useUpdateModels } from "../hooks/useUpdateModels";
@@ -23,6 +21,7 @@ import ShowNsfwModelThumbnailSettings from "../../settings/ShowNsfwModelThumbnai
import { indexdb } from "../../db-tables/indexdb"; import { indexdb } from "../../db-tables/indexdb";
import { type Model } from "../../types/dbTypes"; import { type Model } from "../../types/dbTypes";
import ModelDropEventListener from "../topbar/ModelDropEventListener"; import ModelDropEventListener from "../topbar/ModelDropEventListener";
import { app } from "../../utils/comfyapp";
interface Props { interface Props {
onClose: () => void; onClose: () => void;
} }
@@ -1,13 +1,12 @@
import { Button } from "@chakra-ui/react"; import { Button } from "@chakra-ui/react";
// @ts-ignore // @ts-ignore
import { app } from "/scripts/app.js";
// @ts-ignore
import { api } from "/scripts/api.js"; import { api } from "/scripts/api.js";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import MissingModelsListDrawer, { import MissingModelsListDrawer, {
MissingModel, MissingModel,
} from "../missing-models-drawer/MissingModelsListDrawer"; } from "../missing-models-drawer/MissingModelsListDrawer";
import { COMFYSPACE_TRACKING_FIELD_NAME } from "../../const"; import { COMFYSPACE_TRACKING_FIELD_NAME } from "../../const";
import { app } from "../../utils/comfyapp";
interface Props {} interface Props {}
interface NodeError { interface NodeError {
@@ -1,6 +1,5 @@
import { useEffect, DragEvent } from "react"; import { useEffect, DragEvent } from "react";
// @ts-ignore import { app } from "../../utils/comfyapp";
import { app } from "/scripts/app.js";
export default function ModelDropEventListener() { export default function ModelDropEventListener() {
const handleModelDrop = async ( const handleModelDrop = async (
@@ -1,8 +1,6 @@
import { Button, DarkMode, Stack } from "@chakra-ui/react"; import { Button, DarkMode, Stack } from "@chakra-ui/react";
import { lazy, useEffect, DragEvent, useContext, Suspense } from "react"; import { lazy, useEffect, useContext, Suspense } from "react";
import ModelsListDrawer from "../models-list-drawer/ModelsListDrawer"; import ModelsListDrawer from "../models-list-drawer/ModelsListDrawer";
// @ts-ignore
import { app } from "/scripts/app.js";
import "./index.css"; import "./index.css";
import { WorkspaceContext } from "../../WorkspaceContext"; import { WorkspaceContext } from "../../WorkspaceContext";
// @ts-ignore // @ts-ignore
@@ -15,30 +13,10 @@ import type { ModelsListRespItemFromApi } from "../types";
import InatallModelsModal from "../install-models/InstallModelsModal"; import InatallModelsModal from "../install-models/InstallModelsModal";
import { TOPBAR_BUTTON_HEIGHT } from "../../const"; import { TOPBAR_BUTTON_HEIGHT } from "../../const";
const AddMissingModelsButton = lazy(
() => import("./InstallMissingModelsButton"),
);
export default function ModelManagerTopbar() { export default function ModelManagerTopbar() {
const { setRoute, route } = useContext(WorkspaceContext); const { setRoute, route } = useContext(WorkspaceContext);
const handleModelDrop = async (
e: DragEvent<HTMLCanvasElement> & { canvasX: number; canvasY: number },
) => {
const eventName = e.dataTransfer.getData("eventName");
if (eventName !== "WorkspaceManagerAddNode") {
return;
}
const modelRelativePath = e.dataTransfer.getData("modelRelativePath");
const nodeType = e.dataTransfer.getData("nodeType");
// @ts-ignore
const node = LiteGraph.createNode(nodeType);
node.pos = [e.canvasX, e.canvasY];
node.configure({ widgets_values: [modelRelativePath] });
app.graph.add(node);
};
useEffect(() => { useEffect(() => {
app.canvasEl.addEventListener("drop", handleModelDrop);
api.addEventListener( api.addEventListener(
"model_list", "model_list",
async (e: { detail: ModelsListRespItemFromApi[] }) => { async (e: { detail: ModelsListRespItemFromApi[] }) => {
@@ -77,30 +55,22 @@ export default function ModelManagerTopbar() {
window.dispatchEvent(new CustomEvent("model_list_updated")); window.dispatchEvent(new CustomEvent("model_list_updated"));
}, },
); );
return () => {
app.canvasEl.removeEventListener("drop", handleModelDrop);
};
}, []); }, []);
return ( return (
<Stack style={{ position: "relative" }}> <Stack style={{ position: "relative" }}>
<DarkMode> <Button
<Button size={"sm"}
size={"sm"} backgroundColor={"#434554"}
backgroundColor={"#434554"} color={"white"}
aria-label="My models" colorScheme="blue"
onClick={() => setRoute("modelList")} aria-label="My models"
px={1} onClick={() => setRoute("modelList")}
height={TOPBAR_BUTTON_HEIGHT + "px"} px={1}
> height={TOPBAR_BUTTON_HEIGHT + "px"}
Models >
</Button> Models
</DarkMode> </Button>
<div style={{ position: "absolute", top: "38px", left: "0px" }}>
<Suspense>
<AddMissingModelsButton />
</Suspense>
</div>
{route === "modelList" && ( {route === "modelList" && (
<ModelsListDrawer onClose={() => setRoute("root")} /> <ModelsListDrawer onClose={() => setRoute("root")} />
)} )}
-3
View File
@@ -1,8 +1,5 @@
// @ts-ignore // @ts-ignore
import { deleteFile } from "./Api"; import { deleteFile } from "./Api";
// @ts-ignore
import { app, ComfyApp } from "/scripts/app.js";
export function formatTimestamp( export function formatTimestamp(
unixTimestamp: number, unixTimestamp: number,
showSec: boolean = false, showSec: boolean = false,
+59
View File
@@ -0,0 +1,59 @@
import { Input, Stack, useToast, Text, Flex, Button } from "@chakra-ui/react";
import { useEffect, useState } from "react";
import { userSettingsTable } from "../db-tables/WorkspaceDB";
export default function CloudHostSetting() {
const toast = useToast();
const [text, setText] = useState("");
const getSettings = () => {
userSettingsTable?.getSetting("cloudHost").then((res) => {
setText(res ?? "");
});
};
useEffect(() => {
getSettings();
}, []);
const submitChange = async (text: string) => {
text = text.trim();
if (text.endsWith("/")) text = text.slice(0, -1);
await userSettingsTable?.upsert({ cloudHost: text });
getSettings();
toast({
title: "Setting saved. Please refresh to see the changes.",
status: "success",
duration: 4000,
});
};
return (
<Stack>
<Text>
For enterprise paid user only. Hosting site of the shared workflow.
</Text>
<Flex gap={2} alignItems={"center"}>
<Input
value={text}
onChange={(e) => setText(e.target.value)}
onBlur={() => submitChange(text)}
onKeyDown={(e) => {
if (e.key === "Enter") {
submitChange(text);
}
}}
/>
<Button
size={"sm"}
onClick={() => {
const cloudHost = userSettingsTable?.defaultSettings.cloudHost!;
setText(cloudHost);
submitChange(cloudHost);
}}
>
Reset
</Button>
</Flex>
</Stack>
);
}
@@ -32,6 +32,7 @@ export default function CommonCheckboxSettings({
<Checkbox <Checkbox
isChecked={checked} isChecked={checked}
onChange={async (e) => { onChange={async (e) => {
setChecked(e.target.checked);
await userSettingsTable?.upsert({ [settingKey]: e.target.checked }); await userSettingsTable?.upsert({ [settingKey]: e.target.checked });
getSetting(); getSetting();
toast({ toast({
+7
View File
@@ -108,6 +108,13 @@ export default function SelectMyWorkflowsDir() {
setCurrentDirectory(getNewPath); setCurrentDirectory(getNewPath);
isManualEntry && setNoPermission(false); isManualEntry && setNoPermission(false);
onCloseEditDirectory(); onCloseEditDirectory();
toast({
title: "Directory saved successfully. Please refresh the page.",
status: "success",
duration: 4000,
position: "top",
isClosable: true,
});
}; };
const onSubmit = async (manualEntry?: string) => { const onSubmit = async (manualEntry?: string) => {
+58
View File
@@ -0,0 +1,58 @@
import { Input, Stack, useToast, Text, Flex, Button } from "@chakra-ui/react";
import { useContext, useEffect, useState } from "react";
import { userSettingsTable } from "../db-tables/WorkspaceDB";
import { WorkspaceContext } from "../WorkspaceContext";
import { saveShareKey } from "../utils/saveShareKey";
export default function SharekeySetting() {
const toast = useToast();
const { session, updateSession } = useContext(WorkspaceContext);
const [text, setText] = useState("");
const cloudDomain = new URL(userSettingsTable?.settings?.cloudHost!).hostname;
useEffect(() => {
setText(session?.shareKey ?? "");
}, [session]);
const submitChange = async (text: string) => {
saveShareKey(text);
updateSession({ username: session?.username ?? null, shareKey: text });
toast({
title: "Setting saved. Please refresh to see the changes.",
status: "success",
duration: 4000,
});
};
return (
<Stack gap={3}>
<p style={{ fontWeight: "bold" }}>Cloud Backup [Beta]</p>
<p>
<a
href={userSettingsTable?.settings?.cloudHost + "/auth/shareKey"}
target="_blank"
style={{ textDecoration: "underline" }}
>
<Button size={"sm"}>👉Copy your share key from here</Button>
</a>{" "}
and paste it below to start saving workflow versions to cloud at{" "}
<a href={userSettingsTable?.settings?.cloudHost!} target="_blank">
{cloudDomain}
</a>
</p>
<Flex alignItems={"center"}>
<Input
value={text}
placeholder="Paste your share key here"
onChange={(e) => setText(e.target.value)}
onBlur={() => submitChange(text)}
onKeyDown={(e) => {
if (e.key === "Enter") {
submitChange(text);
}
}}
/>
</Flex>
</Stack>
);
}
+2 -3
View File
@@ -49,9 +49,8 @@ export default function TwoWaySyncSettings() {
return ( return (
<Stack> <Stack>
<Text> <Text>
Only for legacy two way sync users to get back their data. Do not Only for legacy two way sync users to get back their data. [DO NOT
disable two way sync if you have already enabled it. It may cause some DISABLE]
unexpected issues.
</Text> </Text>
<Checkbox isChecked={checked} onChange={onTwoWaySyncChange}> <Checkbox isChecked={checked} onChange={onTwoWaySyncChange}>
Enable two way sync Enable two way sync
+156 -109
View File
@@ -10,88 +10,98 @@ import {
ModalContent, ModalContent,
ModalHeader, ModalHeader,
ModalOverlay, ModalOverlay,
Radio,
RadioGroup, RadioGroup,
Stack, Stack,
Switch,
Tag, Tag,
Text, Text,
useToast, useToast,
} from "@chakra-ui/react"; } from "@chakra-ui/react";
import { Workflow, WorkflowPrivacy, WorkflowVersion } from "../types/dbTypes";
import { useEffect, useRef, useState } from "react";
import CustomSelector from "../components/CustomSelector";
import { IconCloud, IconCopy, IconExternalLink } from "@tabler/icons-react";
import { import {
userSettingsTable, EWorkflowPrivacy,
workflowVersionsTable, WorkflowPrivacy,
workflowsTable, WorkflowVersion,
} from "../db-tables/WorkspaceDB"; } from "../types/dbTypes";
import { useContext, useEffect, useState } from "react";
import CustomSelector from "../components/CustomSelector";
import { IconCopy, IconExternalLink } from "@tabler/icons-react";
import { userSettingsTable, workflowsTable } from "../db-tables/WorkspaceDB";
// @ts-ignore // @ts-ignore
import { api } from "/scripts/api.js"; import { api } from "/scripts/api.js";
// @ts-ignore
import { app } from "/scripts/app.js";
import { import {
PrivacyLabel, PrivacyLabel,
fetchCloudWorkflowPrivacy, fetchCloudWorkflowPrivacy,
generateRandomKey, generateRandomKey,
getCurDateString,
getNodeDefs, getNodeDefs,
privacyOptions, privacyOptions,
} from "./shareUtils"; } from "./shareUtils";
import ShareDialogWorkflowVersionRadio from "./ShareDialogWorkflowVersionRadio"; import ResourceDepsForm from "../spacejson/ResourceDepsForm";
import { app } from "../utils/comfyapp";
import { useStateRef } from "../customHooks/useStateRef";
import { WorkspaceContext } from "../WorkspaceContext";
import {
DepsResult,
WorkspaceInfoDeps,
extractAndFetchFileNames,
} from "../spacejson/handleDownloadSpaceJson";
import { fetchApi } from "../Api";
import { COMFYSPACE_TRACKING_FIELD_NAME } from "../const";
import { ShareWorkflowData } from "../types/types";
interface Props { interface Props {
onClose: () => void; onClose: () => void;
} }
export default function ShareDialog({ onClose }: Props) { export default function ShareDialog({ onClose }: Props) {
const [versionName, setVersionName] = useState("v" + getCurDateString()); const [versionName, setVersionName, versionNameRef] = useStateRef(
const [localVersions, setLocalVersions] = useState<WorkflowVersion[]>([]); "v" + getCurDateString(),
);
const { saveCurWorkflow } = useContext(WorkspaceContext);
const [deps, setDeps] = useState<DepsResult>();
const [uploadingImage, setUploadingImage] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [cloudHost, setCloudHost] = useState(""); const cloudHost = userSettingsTable?.settings?.cloudHost;
const [privacy, setPrivacy] = useState<WorkflowPrivacy>("PRIVATE"); const [privacy, setPrivacy, privacyRef] =
useStateRef<WorkflowPrivacy>("PRIVATE");
const [selectedVersion, setSelectedVersion] = useState< const [selectedVersion, setSelectedVersion] = useState<
string | "new_version" string | "new_version"
>("new_version"); >("new_version");
const cloudHostRef = useRef(""); const workflow = workflowsTable?.curWorkflow;
const [workflow, setWorkflow] = useState<Workflow>();
const toast = useToast(); const toast = useToast();
const [enableDeps, setEnableDeps] = useState(true);
const handleShareWorkflowSuccess = async (event: MessageEvent) => { const handleShareWorkflowSuccess = async (event: MessageEvent) => {
const detail = event.data; const detail = event.data;
if ( if (
event.origin !== cloudHostRef.current || // event.origin !== cloudHostRef.current ||
detail.type !== "share_workflow_success" detail.type !== "share_workflow_success" ||
!workflow
) { ) {
return; return;
} }
const localID = detail.localWorkflowID;
const localVerID = detail.localVersionID;
const cloudVersionID = detail.version.id; const cloudVersionID = detail.version.id;
const cloudID = detail.version.workflowID; const cloudID = detail.version.workflowID;
cloudID && cloudID &&
localID && (await workflowsTable?.updateMetaInfo(workflow.id, {
(await workflowsTable?.updateMetaInfo(localID, {
cloudID: cloudID, cloudID: cloudID,
cloudOrigin: event.origin,
privacy: privacy,
}));
localVerID &&
cloudVersionID &&
(await workflowVersionsTable?.update(localVerID, {
cloudID: cloudVersionID,
cloudOrigin: event.origin,
})); }));
loadData(); loadData();
window.open( window.open(
cloudHostRef.current + "/workflow/" + cloudID + "/" + cloudVersionID, cloudHost + "/workflow/" + cloudID + "/" + cloudVersionID,
"_blank", "_blank",
); );
setLoading(false); setLoading(false);
}; };
useEffect(() => { useEffect(() => {
loadData(); loadData();
const graph = app.graph.serialize();
extractAndFetchFileNames(graph.nodes ?? []).then((depsRes) => {
setDeps(depsRes);
});
window.addEventListener("message", handleShareWorkflowSuccess); window.addEventListener("message", handleShareWorkflowSuccess);
return () => { return () => {
window.removeEventListener("message", handleShareWorkflowSuccess); window.removeEventListener("message", handleShareWorkflowSuccess);
@@ -99,24 +109,11 @@ export default function ShareDialog({ onClose }: Props) {
}, []); }, []);
const loadData = async () => { const loadData = async () => {
const host =
import.meta.env.MODE === "production"
? await userSettingsTable?.getSetting("cloudHost")
: "http://localhost:3000";
if (host) {
setCloudHost(host);
cloudHostRef.current = host;
}
const workflow = workflowsTable?.curWorkflow ?? undefined;
setWorkflow(workflow);
if (workflow?.cloudID && workflow.cloudOrigin) { if (workflow?.cloudID && workflow.cloudOrigin) {
fetchCloudWorkflowPrivacy(workflow).then((privacy) => { fetchCloudWorkflowPrivacy(workflow).then((privacy) => {
setPrivacy(privacy); setPrivacy(privacy);
}); });
} }
workflowVersionsTable?.listByWorkflowID(workflow!.id).then((vers) => {
setLocalVersions(vers);
});
}; };
const copyTextToClipboard = (text: string) => { const copyTextToClipboard = (text: string) => {
navigator.clipboard navigator.clipboard
@@ -133,7 +130,24 @@ export default function ShareDialog({ onClose }: Props) {
console.error("Failed to copy text: ", err); console.error("Failed to copy text: ", err);
}); });
}; };
const onShare = async () => { const pushToCloud = async (imageDeps?: DepsResult["images"]) => {
const graph = app.graph.serialize();
(graph.extra ||= {})[COMFYSPACE_TRACKING_FIELD_NAME] ||= {};
graph.extra[COMFYSPACE_TRACKING_FIELD_NAME].deps = {
models: deps?.models ?? {},
images: imageDeps ?? {},
nodeRepos: deps?.nodeRepos ?? [],
} as WorkspaceInfoDeps;
await saveCurWorkflow();
await app
.graphToPrompt(app.graph)
.then((data: { output: any; workflow: any }) => {
graph.extra[COMFYSPACE_TRACKING_FIELD_NAME].apiPrompt = data.output;
return data.output;
});
const jsonToShare = JSON.stringify(graph);
setLoading(true); setLoading(true);
const secretKey = generateRandomKey(32); const secretKey = generateRandomKey(32);
const host = const host =
@@ -141,30 +155,11 @@ export default function ShareDialog({ onClose }: Props) {
? ((await userSettingsTable?.getSetting("cloudHost")) as string) ? ((await userSettingsTable?.getSetting("cloudHost")) as string)
: "http://localhost:3000"; : "http://localhost:3000";
let nodeDefs: Object; let nodeDefs: Object;
let version: WorkflowVersion | undefined; nodeDefs = getNodeDefs();
try { const version: Omit<WorkflowVersion, "id" | "workflowID" | "createTime"> = {
nodeDefs = getNodeDefs(); name: versionNameRef.current,
if (selectedVersion === "new_version") { json: jsonToShare ?? JSON.stringify(app.graph.serialize()),
version = await workflowVersionsTable?.add({ };
workflowID: workflow!.id,
name: versionName,
createTime: Date.now(),
json: JSON.stringify(app.graph.serialize()),
});
} else {
version = await workflowVersionsTable?.get(selectedVersion);
}
if (!version) {
alert(`Failed to find version: ${selectedVersion}, please try again.`);
setLoading(false);
return;
}
} catch (e) {
console.error(e);
setLoading(false);
alert("Failed to share workflow, please try again.");
return;
}
const protocol = window.location.protocol; const protocol = window.location.protocol;
const baseHost = window.location.host; const baseHost = window.location.host;
const baseUrl = `${protocol}//${baseHost}`; const baseUrl = `${protocol}//${baseHost}`;
@@ -178,28 +173,84 @@ export default function ShareDialog({ onClose }: Props) {
const handleChildReady = (event: MessageEvent) => { const handleChildReady = (event: MessageEvent) => {
if (event.origin === host && event.data === "child_ready") { if (event.origin === host && event.data === "child_ready") {
const curWorkflow = workflowsTable?.curWorkflow; const curWorkflow = workflowsTable?.curWorkflow;
// Send data to the new window after it loads if (!curWorkflow) {
sharePopup!.postMessage( return;
{ }
workflow: curWorkflow, const input: ShareWorkflowData = {
version: version, workflow: {
nodeDefs: nodeDefs, name: curWorkflow.name,
privacy: privacy, cloudID: curWorkflow.cloudID,
}, },
host, version: {
); name: versionNameRef.current,
json: jsonToShare,
},
nodeDefs: nodeDefs,
privacy: privacyRef.current as EWorkflowPrivacy,
};
// Send data to the new window after it loads
sharePopup!.postMessage(input, host);
window.removeEventListener("message", handleChildReady); window.removeEventListener("message", handleChildReady);
} }
}; };
window.addEventListener("message", handleChildReady); window.addEventListener("message", handleChildReady);
}; };
const onShare = async () => {
const imageDeps = deps?.images ?? {};
if (enableDeps) {
// upload images
setUploadingImage(true);
const imageDepsToUpload = Object.values(deps?.images ?? {})
// .filter((i) => !i.url)
.map((i) => i.filename);
if (imageDepsToUpload.length) {
try {
const uploadResp = await fetchApi("/workspace/upload_image", {
method: "POST",
body: JSON.stringify({
images: imageDepsToUpload,
}),
});
const json = (await uploadResp.json()) as Record<string, string>;
Object.keys(json).forEach((key) => {
if (imageDeps?.[key]) {
imageDeps[key].url = json[key];
}
});
} catch (error) {
console.error("Error uploading images:", error);
}
}
setUploadingImage(false);
}
pushToCloud(imageDeps);
};
const cloudWorkflowID = workflowsTable?.curWorkflow?.cloudID; const cloudWorkflowID = workflowsTable?.curWorkflow?.cloudID;
return ( return (
<Modal isOpen={true} onClose={onClose} size={"lg"}> <Modal isOpen={true} onClose={onClose} size={"lg"}>
<ModalOverlay /> <ModalOverlay />
<ModalContent width={["98%", "90%", "50%"]} maxWidth={"600px"}> <ModalContent width={["98%", "90%", "50%"]} maxWidth={"600px"}>
<ModalHeader>Share "{workflow?.name}"</ModalHeader> <ModalHeader>
<Flex justifyContent={"space-between"}>
<p>Share "{workflow?.name}"</p>
<Button
colorScheme="teal"
onClick={onShare}
size={"sm"}
isDisabled={loading}
>
{loading ? "Sharing" : "Share"}
</Button>
</Flex>
{cloudHost && (
<Text fontSize={16} color={"GrayText"} fontWeight={400}>
Share to {new URL(cloudHost).host}
</Text>
)}
</ModalHeader>
<ModalBody pb={10}> <ModalBody pb={10}>
<Stack gap={5}> <Stack gap={5}>
{cloudWorkflowID == null ? ( {cloudWorkflowID == null ? (
@@ -248,7 +299,6 @@ export default function ShareDialog({ onClose }: Props) {
</Button> </Button>
</HStack> </HStack>
)} )}
<Text>Choose a version to share:</Text>
<RadioGroup <RadioGroup
gap={4} gap={4}
onChange={(val) => { onChange={(val) => {
@@ -258,7 +308,6 @@ export default function ShareDialog({ onClose }: Props) {
> >
<Stack> <Stack>
<HStack mb={5} alignItems={"center"}> <HStack mb={5} alignItems={"center"}>
<Radio key={"new_version"} value="new_version" />
<Input <Input
value={versionName} value={versionName}
width={"60%"} width={"60%"}
@@ -270,39 +319,37 @@ export default function ShareDialog({ onClose }: Props) {
}} }}
/> />
<Flex color="green"> <Flex color="green">
<Badge colorScheme="purple">New version</Badge> <Badge colorScheme="purple">Version Name</Badge>
</Flex> </Flex>
</HStack> </HStack>
{localVersions.slice(0, 4).map((ver) => {
return (
<ShareDialogWorkflowVersionRadio
key={ver.id}
version={ver}
cloudHost={cloudHost}
cloudWorkflowID={cloudWorkflowID ?? null}
/>
);
})}
</Stack> </Stack>
</RadioGroup> </RadioGroup>
{Object.keys(deps?.images ?? {}).length > 0 && (
<Stack borderRadius={6} borderWidth={"1px"} p={2}>
<Switch
isChecked={enableDeps}
onChange={() => setEnableDeps(!enableDeps)}
fontWeight={"600"}
>
Share input images
</Switch>
<span style={{ color: "GrayText" }}>
If enabled your input images will be uploaded and shared to{" "}
{cloudHost}
</span>
{enableDeps && (
<ResourceDepsForm
deps={deps ?? null}
setDeps={setDeps}
uploadingImage={uploadingImage}
/>
)}
</Stack>
)}
</Stack> </Stack>
<HStack justifyContent={"flex-end"} mt={16}>
<Button colorScheme="teal" onClick={onShare} isDisabled={loading}>
{loading ? "Sharing" : "Share"}
</Button>
</HStack>
</ModalBody> </ModalBody>
</ModalContent> </ModalContent>
</Modal> </Modal>
); );
} }
function getCurDateString() {
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, "0"); // Months are 0-based in JS
const day = String(currentDate.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
+12 -6
View File
@@ -1,8 +1,8 @@
import { IconLink, IconLock, IconWorld } from "@tabler/icons-react"; import { IconLink, IconLock, IconWorld } from "@tabler/icons-react";
import { CustomSelectorOption } from "../components/CustomSelector"; import { CustomSelectorOption } from "../components/CustomSelector";
import { Workflow, WorkflowPrivacy } from "../types/dbTypes"; import { Workflow, WorkflowPrivacy } from "../types/dbTypes";
// @ts-expect-error import { app } from "../utils/comfyapp";
import { app } from "/scripts/app.js"; import { userSettingsTable } from "../db-tables/WorkspaceDB";
export function generateRandomKey(length: number) { export function generateRandomKey(length: number) {
// Generate a random array of bytes // Generate a random array of bytes
@@ -61,10 +61,7 @@ export const getNodeDefs = () => {
export async function fetchCloudWorkflowPrivacy( export async function fetchCloudWorkflowPrivacy(
workflow: Workflow, workflow: Workflow,
): Promise<WorkflowPrivacy> { ): Promise<WorkflowPrivacy> {
const cloudOrigin = workflow.cloudOrigin; const cloudOrigin = userSettingsTable?.settings?.cloudHost;
if (!cloudOrigin) {
throw Error("cloudURL is required");
}
return fetch(cloudOrigin + `/api/getWorkflow?id=${workflow.cloudID}`) return fetch(cloudOrigin + `/api/getWorkflow?id=${workflow.cloudID}`)
.then((res) => res.json()) .then((res) => res.json())
.then((json) => { .then((json) => {
@@ -100,3 +97,12 @@ export function PrivacyLabel({
} }
return <span>{text}</span>; return <span>{text}</span>;
} }
export function getCurDateString() {
const currentDate = new Date();
// const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, "0"); // Months are 0-based in JS
const day = String(currentDate.getDate()).padStart(2, "0");
return `${month}-${day}`;
}
@@ -1,56 +0,0 @@
import { useContext, useRef } from "react";
import { WorkspaceContext } from "../WorkspaceContext";
import {
Badge,
Button,
HStack,
Heading,
Modal,
ModalBody,
ModalContent,
Text,
Tooltip,
} from "@chakra-ui/react";
// @ts-ignore
import { app } from "/scripts/app.js";
import { IconInfoCircle } from "@tabler/icons-react";
import ResourceDepsForm from "./ResourceDepsForm";
export default function DownloadSpaceJsonDialog() {
const { setRoute } = useContext(WorkspaceContext);
const formRef = useRef<HTMLFormElement>(null);
return (
<Modal isOpen={true} onClose={() => setRoute("root")} size={"xl"}>
<ModalContent>
<ModalBody p={5} gap={5}>
<HStack>
<Heading size={"md"}>Add Resouce Dependencies</Heading>
<Tooltip
label="runnable workflows include all resource dependecy download urls
(models, cursom nodes, input images) and can be one-click
installed and run in any ComfyUI with workpace-manager installed."
>
<Badge borderRadius={10}>
<IconInfoCircle size={20} />
</Badge>
</Tooltip>
</HStack>
<Text color={"GrayText"}>Export runnable workflow</Text>
<ResourceDepsForm ref={formRef} />
<HStack justifyContent={"flex-end"}>
<Button
colorScheme="teal"
size="sm"
onClick={() => formRef.current?.requestSubmit()}
>
Next
</Button>
<Button size="sm" onClick={() => setRoute("share")}>
Skip
</Button>
</HStack>
</ModalBody>
</ModalContent>
</Modal>
);
}
+32 -320
View File
@@ -1,332 +1,44 @@
import { import { HStack, Heading, Image, Spinner, Stack } from "@chakra-ui/react";
forwardRef, import { DepsResult } from "./handleDownloadSpaceJson";
useCallback,
useContext,
useEffect,
useState,
} from "react";
import { WorkspaceContext } from "../WorkspaceContext";
import {
Button,
Flex,
HStack,
Heading,
IconButton,
Image,
Input,
Spinner,
Stack,
Tag,
Text,
Tooltip,
} from "@chakra-ui/react";
import {
DepsResult,
ModelFile,
WorkspaceInfoDeps,
extractAndFetchFileNames,
} from "./handleDownloadSpaceJson";
// @ts-ignore
import { app } from "/scripts/app.js";
import { IconExternalLink, IconPencil, IconRefresh } from "@tabler/icons-react";
import { getHgModelInfoUrlFromDownloadUrl } from "../utils/civitUtils";
import { getAllModelsList } from "../Api";
import { COMFYSPACE_TRACKING_FIELD_NAME } from "../const";
import { indexdb } from "../db-tables/indexdb";
export default forwardRef<HTMLFormElement>( export default function ResourceDepsForm({
function ResourceDepsForm(_props, ref) { deps,
const { saveCurWorkflow, setRoute } = useContext(WorkspaceContext); uploadingImage,
const [deps, setDeps] = useState<DepsResult>();
const [errors, setErrors] = useState<Record<string, string>>({});
const [uploadingImage, setUploadingImage] = useState(false);
const init = useCallback(async () => {
const graph = app.graph.serialize();
extractAndFetchFileNames(graph.nodes ?? []).then((depsRes) => {
setDeps(depsRes);
});
}, []);
const onRefreshModelsList = useCallback(async () => {
setDeps(undefined);
await getAllModelsList();
window.addEventListener("model_list_updated", () => {
init();
window.removeEventListener("model_list_updated", () => {});
});
}, []);
useEffect(() => {
init();
}, []);
const validateURL = (url: string) => {
const pattern = new RegExp(
"^(https?:\\/\\/)?" +
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" +
"((\\d{1,3}\\.){3}\\d{1,3}))" +
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" +
"(\\?[;&a-z\\d%_.~+=-]*)?" +
"(\\#[-a-z\\d_]*)?$",
"i",
);
return !!pattern.test(url);
};
const handleSubmit = async (event: any) => {
event.preventDefault();
event.stopPropagation();
const formData = new FormData(event.target);
// validate model deps and save model urls to db
const saveModelUrlDBPromises: Promise<ModelFile>[] =
Object.values(deps?.models ?? {}).map(async (model) => {
const inputDownloadUrl = formData.get(model.filename)?.toString();
if (inputDownloadUrl?.length) {
// because the models table is storing filename without extension as id, which should be migrated
const baseName = getBaseFileName(model.filename);
await indexdb.models.update(baseName + "@" + model.fileFolder, {
downloadUrl: inputDownloadUrl,
});
}
const infoUrl = model.infoUrl?.length
? model.infoUrl
: inputDownloadUrl
? getHgModelInfoUrlFromDownloadUrl(inputDownloadUrl)
: null;
return {
filename: model.filename,
nodeType: model.nodeType,
fileHash: model.fileHash,
fileFolder: model.fileFolder,
downloadUrl: inputDownloadUrl ?? model.downloadUrl ?? null,
infoUrl: infoUrl ?? null,
inputName: model.inputName,
};
}) ?? [];
const modelDepsArr = await Promise.all(saveModelUrlDBPromises);
if (!validateModelDeps(modelDepsArr)) {
return;
}
setErrors({});
// upload images
setUploadingImage(true);
const imageDepsToUpload = Object.values(deps?.images ?? {})
.filter((i) => !i.url)
.map((i) => i.filename);
const imageDeps = deps?.images ?? {};
if (imageDepsToUpload.length) {
const uploadResp = await fetch("/workspace/upload_image", {
method: "POST",
body: JSON.stringify({
images: imageDepsToUpload,
}),
});
const json = (await uploadResp.json()) as Record<string, string>;
Object.keys(json).forEach((key) => {
if (imageDeps?.[key]) {
imageDeps[key].url = json[key];
}
});
}
setUploadingImage(false);
// save deps to graph
const modelDeps: WorkspaceInfoDeps["models"] = {};
modelDepsArr.forEach((model) => {
modelDeps[model.filename] = model;
});
const graph = app.graph.serialize();
(graph.extra ||= {})[COMFYSPACE_TRACKING_FIELD_NAME] ||= {};
graph.extra[COMFYSPACE_TRACKING_FIELD_NAME].deps = {
models: modelDeps,
images: imageDeps ?? {},
nodeRepos: deps?.nodeRepos ?? [],
} as WorkspaceInfoDeps;
await app
.graphToPrompt(app.graph)
.then((data: { output: any; workflow: any }) => {
graph.extra[COMFYSPACE_TRACKING_FIELD_NAME].apiPrompt = data.output;
});
await saveCurWorkflow();
console.log("graph", graph);
setRoute("share");
};
const validateModelDeps = useCallback((modelDeps: ModelFile[]) => {
let isValid = true;
modelDeps.forEach((model) => {
const key = model.filename;
if (!model.downloadUrl) {
setErrors((prev) => ({
...prev,
[key]: "Invalid URL",
}));
isValid = false;
return;
}
if (!validateURL(model.downloadUrl)) {
setErrors((prev) => ({ ...prev, [key]: "Invalid URL" }));
isValid = false;
return;
}
if (!model.fileFolder) {
setErrors((prev) => ({
...prev,
[key]: "Model file not found, please re-scan models folder",
}));
isValid = false;
return;
}
});
return isValid;
}, []);
const imageDepsArr = Object.values(deps?.images ?? {});
const modelDepsArr = Object.values(deps?.models ?? []);
if (!deps) {
return <Spinner size="md" color="teal.400" />;
}
return (
<form onSubmit={handleSubmit} ref={ref}>
<Stack gap={5} mt={5}>
<Stack>
<Heading size={"sm"}>Models ({modelDepsArr.length})</Heading>
{modelDepsArr.map((modelFile, index) => (
<ModelDepsItem
modelFile={modelFile}
key={index}
errors={errors}
onClickRefetchModelList={onRefreshModelsList}
/>
))}
</Stack>
{imageDepsArr.length > 0 && (
<Stack>
<HStack>
<Heading size={"sm"}>Images ({imageDepsArr.length})</Heading>
{/* <Tag colorScheme="yellow">Will be uploaded as url</Tag> */}
<p style={{ color: "GrayText" }}>Will be uploaded as url</p>
</HStack>
{uploadingImage && (
<span>
<Spinner size="md" color="teal.400" /> Uploading
</span>
)}
{imageDepsArr.map((image) => (
<Stack key={image.filename}>
<p>{image.filename}</p>
<Image
width={250}
src={`/workspace/view_media?filename=${image.filename}&isPreview=true&isInput=true`}
/>
</Stack>
))}
</Stack>
)}
</Stack>
</form>
);
},
);
function getBaseFileName(filename: string) {
const parts = filename.split(".");
if (parts.length > 1) {
parts.pop();
return parts.join(".");
} else {
return filename;
}
}
function ModelDepsItem({
modelFile,
errors,
onClickRefetchModelList,
}: { }: {
modelFile: DepsResult["models"][0]; deps: DepsResult | null;
errors: Record<string, string>; setDeps: (deps: DepsResult) => void;
onClickRefetchModelList: () => void; uploadingImage: boolean;
}) { }) {
const inputKey = modelFile.filename; const imageDepsArr = Object.values(deps?.images ?? {});
const [isEditing, setIsEditing] = useState(!modelFile.downloadUrl); if (!deps) {
return <Spinner size="md" color="teal.400" />;
if (!modelFile.fileFolder) {
return (
<Stack>
<Flex gap={2}>
<p>{modelFile.filename}</p>
<Tag size={"sm"} colorScheme={"red"}>
Model file not found
</Tag>
</Flex>
<Button
size={"sm"}
leftIcon={<IconRefresh />}
width={"fit-content"}
borderColor={"red"}
borderWidth={errors[inputKey] != null ? 2 : 0}
onClick={onClickRefetchModelList}
>
Fetch model file
</Button>
</Stack>
);
} }
return ( return (
<Stack ml={2}> <Stack gap={5}>
<Flex key={modelFile.filename + modelFile.nodeType} gap={2}> {imageDepsArr.length > 0 && (
<Tag height={"fit-content"} colorScheme={"teal"}> <Stack>
{modelFile.fileFolder}
</Tag>
{modelFile.downloadUrl ? (
<HStack> <HStack>
<a <Heading size={"sm"}>Images ({imageDepsArr.length})</Heading>
href={modelFile.infoUrl ?? modelFile.downloadUrl} {/* <Tag colorScheme="yellow">Will be uploaded as url</Tag> */}
target="_blank" <p style={{ color: "GrayText" }}>Will be uploaded as url</p>
>
{modelFile.filename}
</a>
<IconExternalLink size={18} />
<IconButton
ml={3}
aria-label="edit"
icon={<IconPencil size={18} />}
size={"xs"}
onClick={() => setIsEditing(!isEditing)}
/>
</HStack> </HStack>
) : ( {uploadingImage && (
<Stack>
<span> <span>
{modelFile.filename} <span>❓</span> <Spinner size="md" color="teal.400" /> Uploading
</span> </span>
</Stack> )}
)} {imageDepsArr.map((image) => (
</Flex> <Stack key={image.filename}>
<p>{image.filename}</p>
<Stack style={{ display: isEditing ? "block" : "none" }}> <Image
<Tooltip width={250}
label={"Model download link, supports Huggingface and Civitai"} src={`/workspace/view_media?filename=${image.filename}&isPreview=true&isInput=true`}
> />
<Input </Stack>
name={inputKey} ))}
defaultValue={modelFile.downloadUrl ?? ""} </Stack>
size={"sm"} )}
isInvalid={errors[inputKey] != null}
placeholder={"https://civitai.com/api/download/models/324524"}
/>
</Tooltip>
</Stack>
<Text color={"red.400"}>{errors[inputKey]}</Text>
</Stack> </Stack>
); );
} }
+19 -25
View File
@@ -5,8 +5,7 @@ import {
getCivitModelPageUrl, getCivitModelPageUrl,
getHgModelInfoUrlFromDownloadUrl, getHgModelInfoUrlFromDownloadUrl,
} from "../utils/civitUtils"; } from "../utils/civitUtils";
// @ts-ignore import { app } from "../utils/comfyapp";
import { app } from "/scripts/app.js";
type LiteNode = { type LiteNode = {
id: number; id: number;
@@ -14,13 +13,18 @@ type LiteNode = {
widgets_values?: Array<string | number>; widgets_values?: Array<string | number>;
}; };
export type ModelFile = { export type ModelDep = {
filename: string; name: string;
fileFolder: string | null; folder: string | null;
fileHash: string | null; hash: string | null;
downloadUrl: string | null; url: string | null;
// TODO: will be deperecated
filename?: string;
fileFolder?: string | null;
fileHash?: string | null;
downloadUrl?: string | null;
// optional info // optional info
infoUrl: string | null; infoUrl?: string | null;
nodeType?: string; nodeType?: string;
inputName?: string; inputName?: string;
}; };
@@ -41,12 +45,12 @@ export type DepsResult = {
nodeRepos: NodeRepo[]; nodeRepos: NodeRepo[];
}; };
export type DepsResultModel = ModelFile & { export type DepsResultModel = ModelDep & {
length: number; length: number;
}; };
export type WorkspaceInfoDeps = { export type WorkspaceInfoDeps = {
models: Record<string, ModelFile>; models: Record<string, ModelDep>;
images: DepsResult["images"]; images: DepsResult["images"];
nodeRepos: DepsResult["nodeRepos"]; nodeRepos: DepsResult["nodeRepos"];
}; };
@@ -60,18 +64,15 @@ async function fetchModelData(
(await indexdb.models.where("fileName").equals(filename).toArray()) ?? []; (await indexdb.models.where("fileName").equals(filename).toArray()) ?? [];
const first = res.at(0); const first = res.at(0);
const modelFile: DepsResultModel = { const modelFile: DepsResultModel = {
filename, name: filename,
nodeType, nodeType,
fileHash: first?.fileHash ?? null, hash: first?.fileHash ?? null,
fileFolder: first?.fileFolder ?? null, folder: first?.fileFolder ?? null,
downloadUrl: first?.civitModelVersionID url: first?.civitModelVersionID
? getCivitModelDownloadUrl(first.civitModelVersionID) ? getCivitModelDownloadUrl(first.civitModelVersionID)
: first?.downloadUrl ?? null, : first?.downloadUrl ?? null,
inputName: inputName, inputName: inputName,
length: res.length, length: res.length,
infoUrl: first?.civitModelID
? getCivitModelPageUrl(first.civitModelID, first.civitModelVersionID)
: getHgModelInfoUrlFromDownloadUrl(first?.downloadUrl ?? "") ?? null,
}; };
return modelFile; return modelFile;
} }
@@ -95,13 +96,9 @@ export async function extractAndFetchFileNames(
if (typeof value != "string") return; if (typeof value != "string") return;
// Check if it's a model file // Check if it's a model file
if (modelFileExtensions.some((ext) => value.endsWith(ext))) { if (modelFileExtensions.some((ext) => value.endsWith(ext))) {
// if (curDeps?.models?.[value]) {
// modelPromises.push(Promise.resolve(curDeps.models[value]));
// } else {
modelPromises.push( modelPromises.push(
fetchModelData(value, node.class_type, inputName), fetchModelData(value, node.class_type, inputName),
); );
// }
} }
// Check if it's an image file // Check if it's an image file
if (imageFileExtensions.some((ext) => value.endsWith(ext))) { if (imageFileExtensions.some((ext) => value.endsWith(ext))) {
@@ -135,10 +132,7 @@ export async function extractAndFetchFileNames(
const models = await Promise.all(modelPromises); const models = await Promise.all(modelPromises);
const modelsMap: Record<string, DepsResultModel> = {}; const modelsMap: Record<string, DepsResultModel> = {};
models.forEach((model) => { models.forEach((model) => {
// if (model.nodeType) { modelsMap[model.name] = model;
// model.gitRepo = reposMapping[model.nodeType];
// }
modelsMap[model.filename] = model;
}); });
const nodeRepos: Record<string, NodeRepo> = {}; const nodeRepos: Record<string, NodeRepo> = {};
Object.values(reposMapping).forEach((repo) => { Object.values(reposMapping).forEach((repo) => {
+48 -77
View File
@@ -1,33 +1,31 @@
import { useContext, useEffect, useRef, useState } from "react"; import { useContext, useEffect, useRef } from "react";
// @ts-expect-error
import { app } from "/scripts/app.js";
import { WorkspaceContext } from "../WorkspaceContext"; import { WorkspaceContext } from "../WorkspaceContext";
import { import { workflowsTable } from "../db-tables/WorkspaceDB";
changelogsTable,
userSettingsTable,
workflowsTable,
} from "../db-tables/WorkspaceDB";
import { Tag, Tooltip, useToast } from "@chakra-ui/react";
import { matchShortcut } from "../utils"; import { matchShortcut } from "../utils";
import { EShortcutKeys } from "../types/dbTypes"; import { EShortcutKeys } from "../types/dbTypes";
import useDebounceFn from "../customHooks/useDebounceFn"; import useDebounceFn from "../customHooks/useDebounceFn";
import { deepJsonDiffCheck } from "../utils/deepJsonDiffCheck"; import {
import { SHORTCUT_TRIGGER_EVENT } from "../const"; COMFYSPACE_TRACKING_FIELD_NAME,
SHORTCUT_TRIGGER_EVENT,
} from "../const";
import { app } from "../utils/comfyapp";
export default function AppIsDirtyEventListener() { export default function AppIsDirtyEventListener() {
const { isDirty, setIsDirty, setRoute, saveCurWorkflow } = const {
useContext(WorkspaceContext); isDirty,
setIsDirty,
setRoute,
saveCurWorkflow,
setCurFlowIDAndName,
} = useContext(WorkspaceContext);
const isDirtRef = useRef(isDirty); const isDirtRef = useRef(isDirty);
const [isOutdated, setIsOutdated] = useState(false);
const toast = useToast();
const autoSaveTimer = useRef<number | null>(null);
useEffect(() => { useEffect(() => {
isDirtRef.current = isDirty; isDirtRef.current = isDirty;
}, [isDirty]); }, [isDirty]);
useEffect(() => { useEffect(() => {
const shortcutListener = (event: KeyboardEvent) => { const keydownListener = (event: KeyboardEvent) => {
if (document.visibilityState === "hidden") return; if (document.visibilityState === "hidden") return;
const matchResult = matchShortcut(event); const matchResult = matchShortcut(event);
if (matchResult) { if (matchResult) {
@@ -60,11 +58,27 @@ export default function AppIsDirtyEventListener() {
debounceOnIsDirty(); debounceOnIsDirty();
} }
}; };
const originalOnAfterChange = app.canvas.onAfterChange;
app.graph.onAfterChange = function () { const restoreCurWorkflow = async () => {
// Call the original onAfterChange method if (!app?.graph) {
originalOnAfterChange?.apply(this, arguments); console.error(
debounceOnIsDirty(); "🦄 Error in workspace manager! app.graph is not available in restoreCurWorkflow()",
);
return;
}
const id = app.graph.extra?.[COMFYSPACE_TRACKING_FIELD_NAME]?.id;
if (id) {
const flow = await workflowsTable?.get(id);
flow && setCurFlowIDAndName(flow);
if (
!flow?.saveLock &&
flow &&
flow.json !== JSON.stringify(app.graph.serialize())
) {
setIsDirty(true);
}
}
}; };
const originalOnConfigure = app.graph.onConfigure; const originalOnConfigure = app.graph.onConfigure;
@@ -72,14 +86,11 @@ export default function AppIsDirtyEventListener() {
originalOnConfigure?.apply(this, arguments); originalOnConfigure?.apply(this, arguments);
// delay check diff json cuz it takes time for graph.serialize() to settle up and return the correct json // delay check diff json cuz it takes time for graph.serialize() to settle up and return the correct json
setTimeout(() => { setTimeout(() => {
const deepCheck = deepJsonDiffCheck( const id = app.graph.extra?.[COMFYSPACE_TRACKING_FIELD_NAME]?.id;
app.graph.serialize(), if (id == null || id != workflowsTable?.curWorkflow?.id) {
JSON.parse(workflowsTable?.curWorkflow?.json ?? "{}"), setCurFlowIDAndName(null);
);
if (!deepCheck) {
debounceOnIsDirty();
} }
}, 1000); }, 500);
}; };
document.addEventListener("click", (e) => { document.addEventListener("click", (e) => {
@@ -92,63 +103,23 @@ export default function AppIsDirtyEventListener() {
debounceOnIsDirty(); debounceOnIsDirty();
} }
}); });
document.addEventListener("keydown", shortcutListener); document.addEventListener("keydown", keydownListener);
if (
userSettingsTable?.settings?.autoSave &&
userSettingsTable.settings.autoSaveDuration
) {
autoSaveTimer.current = setInterval(() => {
// auto save workflow every 5s
autoSaveWorkflow();
}, userSettingsTable.settings.autoSaveDuration * 1000);
}
restoreCurWorkflow();
return () => { return () => {
document.removeEventListener("keydown", shortcutListener); document.removeEventListener("keydown", keydownListener);
autoSaveTimer.current && clearInterval(autoSaveTimer.current);
}; };
}, []); }, []);
const autoSaveWorkflow = async () => {
// autosave workflow if enabled
if (
workflowsTable?.curWorkflow?.saveLock ||
!workflowsTable?.curWorkflow?.id ||
!isDirtRef.current
) {
return;
}
const graphJson = JSON.stringify(app.graph.serialize());
await workflowsTable?.updateFlow(workflowsTable.curWorkflow.id, {
json: graphJson,
});
changelogsTable?.create({
workflowID: workflowsTable.curWorkflow.id,
isAutoSave: true,
json: graphJson,
});
setIsDirty(false);
};
const onIsDirty = async () => { const onIsDirty = async () => {
if (workflowsTable?.curWorkflow?.saveLock || isDirtRef.current) return; if (workflowsTable?.curWorkflow?.saveLock || isDirtRef.current) return;
setIsDirty(true); const graph = app.graph.serialize();
if ( if (JSON.stringify(graph) === workflowsTable?.curWorkflow?.json) {
userSettingsTable?.settings?.autoSave && return;
workflowsTable?.curWorkflow?.id &&
!isOutdated
) {
const isLatest = await workflowsTable?.latestVersionCheck();
if (!isLatest) {
setIsOutdated(true);
}
} }
setIsDirty(true);
}; };
const [debounceOnIsDirty, _] = useDebounceFn(onIsDirty, 900); const [debounceOnIsDirty, _] = useDebounceFn(onIsDirty, 900);
return isOutdated ? ( return null;
<Tooltip label="This workflow was changed by another tab, so you are not working on the latest version. Please refresh page to see the latest version of this workflow.">
<Tag colorScheme="yellow">⚠️Outdated version</Tag>
</Tooltip>
) : null;
} }
+4 -26
View File
@@ -5,7 +5,6 @@ import {
IconFolder, IconFolder,
IconGripVertical, IconGripVertical,
IconPhoto, IconPhoto,
IconPlus,
IconTriangleInvertedFilled, IconTriangleInvertedFilled,
IconLock, IconLock,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
@@ -22,10 +21,10 @@ import EditFlowName from "../components/EditFlowName";
import { WorkspaceContext } from "../WorkspaceContext"; import { WorkspaceContext } from "../WorkspaceContext";
import { PanelPosition } from "../types/dbTypes"; import { PanelPosition } from "../types/dbTypes";
import "./Topbar.css"; import "./Topbar.css";
import { SharedTopbarButton } from "../share/SharedTopbarButton";
import VersionNameTopbar from "./VersionNameTopbar"; import VersionNameTopbar from "./VersionNameTopbar";
import { userSettingsTable, workflowsTable } from "../db-tables/WorkspaceDB"; import { userSettingsTable, workflowsTable } from "../db-tables/WorkspaceDB";
import { TOPBAR_BUTTON_HEIGHT } from "../const"; import { TOPBAR_BUTTON_HEIGHT } from "../const";
import TopbarNewWorkflowButton from "./TopbarNewWorkflowButton";
const AppIsDirtyEventListener = lazy(() => import("./AppIsDirtyEventListener")); const AppIsDirtyEventListener = lazy(() => import("./AppIsDirtyEventListener"));
const ModelManagerTopbar = lazy( const ModelManagerTopbar = lazy(
() => import("../model-manager/topbar/ModelManagerTopbar"), () => import("../model-manager/topbar/ModelManagerTopbar"),
@@ -37,14 +36,8 @@ interface Props {
setCurFlowName: (newName: string) => void; setCurFlowName: (newName: string) => void;
} }
export function Topbar({ curFlowName, setCurFlowName }: Props) { export function Topbar({ curFlowName, setCurFlowName }: Props) {
const { const { isDirty, saveCurWorkflow, setRoute, curFlowID, route } =
isDirty, useContext(WorkspaceContext);
loadNewWorkflow,
saveCurWorkflow,
setRoute,
curFlowID,
route,
} = useContext(WorkspaceContext);
const [positionStyle, setPositionStyle] = useState<PanelPosition>(); const [positionStyle, setPositionStyle] = useState<PanelPosition>();
const updatePanelPosition: ( const updatePanelPosition: (
position?: PanelPosition, position?: PanelPosition,
@@ -116,21 +109,7 @@ export function Topbar({ curFlowName, setCurFlowName }: Props) {
<Suspense fallback={<div style={{ width: "60px" }} />}> <Suspense fallback={<div style={{ width: "60px" }} />}>
<ModelManagerTopbar /> <ModelManagerTopbar />
</Suspense> </Suspense>
<Tooltip label="New workflow"> <TopbarNewWorkflowButton />
<Button
size={"sm"}
variant={"outline"}
colorScheme="teal"
aria-label="new workflow"
height={TOPBAR_BUTTON_HEIGHT + "px"}
onClick={() => loadNewWorkflow()}
px={1}
>
<HStack gap={0}>
<IconPlus size={16} color={"white"} />
</HStack>
</Button>
</Tooltip>
<EditFlowName <EditFlowName
isDirty={isDirty} isDirty={isDirty}
displayName={curFlowName ?? ""} displayName={curFlowName ?? ""}
@@ -172,7 +151,6 @@ export function Topbar({ curFlowName, setCurFlowName }: Props) {
) : ( ) : (
<div style={{ width: 1 }} /> <div style={{ width: 1 }} />
)} )}
<SharedTopbarButton />
<VersionNameTopbar /> <VersionNameTopbar />
<AppIsDirtyEventListener /> <AppIsDirtyEventListener />
<IconGripVertical <IconGripVertical
+49
View File
@@ -0,0 +1,49 @@
import { Tooltip, Button } from "@chakra-ui/react";
import { IconDeviceFloppy } from "@tabler/icons-react";
import { useContext } from "react";
import { WorkspaceContext } from "../WorkspaceContext";
import { COMFYSPACE_TRACKING_FIELD_NAME, TOPBAR_BUTTON_HEIGHT } from "../const";
import { app } from "../utils/comfyapp";
import { workflowsTable } from "../db-tables/WorkspaceDB";
import { nanoid } from "nanoid";
export default function TopbarNewWorkflowButton() {
const { setCurFlowIDAndName, curFlowID } = useContext(WorkspaceContext);
const saveNewWorkflow = async () => {
const workflowName = prompt("Enter workflow name", "Untitled");
if (!workflowName) return;
const id = nanoid();
const graph = app.graph.serialize();
if (!graph.extra) {
graph.extra = {};
}
if (!graph.extra[COMFYSPACE_TRACKING_FIELD_NAME]) {
graph.extra[COMFYSPACE_TRACKING_FIELD_NAME] = {};
}
graph.extra[COMFYSPACE_TRACKING_FIELD_NAME].id = id;
const flow = await workflowsTable?.createFlow({
id,
json: JSON.stringify(graph),
name: workflowName,
});
flow && setCurFlowIDAndName(flow);
};
if (curFlowID) {
return null;
}
return (
<Tooltip label={"Save workflow"}>
<Button
size={"sm"}
variant={"outline"}
colorScheme="teal"
aria-label="new workflow"
height={TOPBAR_BUTTON_HEIGHT + "px"}
onClick={() => saveNewWorkflow()}
px={1}
>
<IconDeviceFloppy size={16} color={"white"} />
</Button>
</Tooltip>
);
}
+8 -10
View File
@@ -10,17 +10,17 @@ export interface SortableItem {
export interface Workflow extends SortableItem { export interface Workflow extends SortableItem {
id: string; id: string;
json: string; json: string;
lastSavedJson?: string; // TODO will be deprecated
name: string; name: string;
coverMediaPath?: string | null;
saveLock?: boolean;
cloudID?: string | null;
createTime: number; createTime: number;
filePath?: string; // TODO will be deprecated
// will be deprecated
privacy?: WorkflowPrivacy; privacy?: WorkflowPrivacy;
tags?: string[]; tags?: string[];
parentFolderID?: string | null; //TODO remove undefined, use null only parentFolderID?: string | null; //TODO remove undefined, use null only
coverMediaPath?: string;
cloudID?: string; // TODO will be deprecated
cloudOrigin?: string; cloudOrigin?: string;
saveLock?: boolean;
latestImage?: string; latestImage?: string;
topFieldsConfig?: TopFieldType[]; topFieldsConfig?: TopFieldType[];
} }
@@ -66,9 +66,9 @@ export type WorkflowVersion = {
name: string; name: string;
workflowID: string; workflowID: string;
json: string; json: string;
createTime: number; createTime?: number;
cloudID?: string; createdAt?: string;
cloudOrigin?: string; created_at?: string;
authorID?: string; authorID?: string;
nodeDefs?: string; //for cloud workflow version nodeDefs?: string; //for cloud workflow version
}; };
@@ -96,7 +96,6 @@ export type UserSettings = {
foldersOnTop?: boolean; foldersOnTop?: boolean;
showNsfwModelThumbnail?: boolean; showNsfwModelThumbnail?: boolean;
cloudHost: string; cloudHost: string;
overwriteCurWorkflowWhenDroppingFileToCanvas: boolean;
defaultFolders: Record<MODEL_TYPE, string>; defaultFolders: Record<MODEL_TYPE, string>;
maximumChangelogNumber: number; maximumChangelogNumber: number;
hideCoverImage: boolean; hideCoverImage: boolean;
@@ -131,7 +130,6 @@ export type Media = {
workflowJSON?: string; workflowJSON?: string;
createTime: number; createTime: number;
localPath: string; localPath: string;
format: string;
}; };
/** /**
+20
View File
@@ -1,3 +1,5 @@
import { EWorkflowPrivacy } from "./dbTypes";
export type WorkspaceRoute = export type WorkspaceRoute =
| "root" | "root"
| "customNodes" | "customNodes"
@@ -10,3 +12,21 @@ export type WorkspaceRoute =
| "downloadSpaceJson" | "downloadSpaceJson"
| "installModels" | "installModels"
| "share"; | "share";
export type Session = {
username: string | null;
shareKey: string;
};
export type ShareWorkflowData = {
version: {
name: string;
json: string;
};
workflow: {
name: string;
cloudID?: string | null;
};
nodeDefs: Object;
privacy: EWorkflowPrivacy;
};
+3 -52
View File
@@ -1,22 +1,7 @@
import { deleteFile, updateFile } from "./Api";
import { ESortTypes } from "./RecentFilesDrawer/types"; import { ESortTypes } from "./RecentFilesDrawer/types";
import { workflowsTable, userSettingsTable } from "./db-tables/WorkspaceDB"; import { userSettingsTable } from "./db-tables/WorkspaceDB";
import { import { Workflow, EShortcutKeys, SortableItem } from "./types/dbTypes";
generateFilePathAbsolute, import { app } from "./utils/comfyapp";
saveJsonFileMyWorkflows,
} from "./db-tables/DiskFileUtils";
import {
Workflow,
EShortcutKeys,
EOtherKeys,
SortableItem,
} from "./types/dbTypes";
// @ts-expect-error ComfyUI import
import { app } from "/scripts/app.js";
import {
COMFYSPACE_TRACKING_FIELD_NAME,
LEGACY_COMFYSPACE_TRACKING_FIELD_NAME,
} from "./const";
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
declare let LiteGraph: any, LGraph: any, LGraphCanvas: any; declare let LiteGraph: any, LGraph: any, LGraphCanvas: any;
@@ -156,22 +141,6 @@ export function sortFlows(
return copyFlows; return copyFlows;
} }
export async function validateOrSaveAllJsonFileMyWorkflows(
deleteEmptyFolder = false,
) {
const twoWaySync = await userSettingsTable?.getSetting("twoWaySync");
if (twoWaySync) return; // disable this function in two way sync mode
const flowList = (await workflowsTable?.listAll()) ?? [];
for (const workflow of flowList) {
const fullPath = await generateFilePathAbsolute(workflow);
if (workflow.filePath != fullPath) {
// file path changed
workflow.filePath != null &&
(await deleteFile(workflow.filePath, deleteEmptyFolder));
await saveJsonFileMyWorkflows(workflow);
}
}
}
export const sortFileItem = <T extends SortableItem>( export const sortFileItem = <T extends SortableItem>(
items: T[], items: T[],
@@ -341,21 +310,3 @@ export const openWorkflowInNewTab = (workflowID: string) => {
const newHash = generateUrlHashWithFlowId(workflowID); const newHash = generateUrlHashWithFlowId(workflowID);
window.open(`${window.location.origin}/#${newHash}`); window.open(`${window.location.origin}/#${newHash}`);
}; };
export async function rewriteAllLocalFiles() {
const flowList = (await workflowsTable?.listAll()) ?? [];
for (const workflow of flowList) {
try {
const fullPath = await generateFilePathAbsolute(workflow);
const flow = JSON.parse(workflow.json);
flow.extra[COMFYSPACE_TRACKING_FIELD_NAME] = {
id: workflow.id,
name: workflow.name,
};
delete flow.extra[LEGACY_COMFYSPACE_TRACKING_FIELD_NAME];
fullPath && (await updateFile(fullPath, JSON.stringify(flow)));
} catch (error) {
console.error(error);
}
}
}
+12
View File
@@ -1,5 +1,13 @@
import type { Workflow } from "../types/dbTypes"; import type { Workflow } from "../types/dbTypes";
export const serverInfo: {
os: "Windows" | "Linux" | "Darwin" | "Java" | null;
} = {
os: null,
};
export const getPathSep = () => (serverInfo.os === "Windows" ? "\\" : "/");
export function joinRelPath(...segments: string[]) { export function joinRelPath(...segments: string[]) {
const rel = segments.filter((segment) => segment !== "").join("/"); const rel = segments.filter((segment) => segment !== "").join("/");
return sanitizeRelPath(rel); return sanitizeRelPath(rel);
@@ -15,6 +23,10 @@ export function sanitizeRelPath(path: string) {
// Remove leading slashes to ensure the path is treated as relative // Remove leading slashes to ensure the path is treated as relative
sanitizedPath = sanitizedPath.replace(/^\/+/, ""); sanitizedPath = sanitizedPath.replace(/^\/+/, "");
if (serverInfo.os === "Windows") {
sanitizedPath = segments.replace(/\//g, "\\");
}
return sanitizedPath; return sanitizedPath;
} }
+14 -4
View File
@@ -1,7 +1,17 @@
// @ts-ignore // @ts-ignore
export const app = window.app; export let app: any | null = null;
const api_base = location.pathname.split("/").slice(0, -1).join("/"); const api_base = location.pathname.split("/").slice(0, -1).join("/");
export const api = import(api_base + "/scripts/app.js").then((api) => { export let api: any | null = null;
return api;
}); export async function waitForApp() {
await Promise.all([
import(api_base + "/scripts/api.js").then((apiJs) => {
api = apiJs?.api;
}),
import(api_base + "/scripts/app.js").then((appJs) => {
app = appJs?.app;
}),
]);
}
+18
View File
@@ -0,0 +1,18 @@
// utils/encryptUtils
const defaultSalt = import.meta.env.VITE_SHARE_KEY_ENCODE_KEY;
export function encodeKey(text: string, salt: string = defaultSalt): string {
const randomLength = Math.floor(Math.random() * 13) + 1; // Random length between 1 and 13
const randomPadding = Math.random()
.toString(36)
.substring(2, 2 + randomLength);
const input = randomPadding + salt + text;
return btoa(encodeURIComponent(input));
}
export function decodeKey(encoded: string, salt: string = defaultSalt): string {
const decoded = decodeURIComponent(atob(encoded));
const saltIndex = decoded.indexOf(salt);
if (saltIndex === -1) throw new Error("Invalid encoded string or salt");
return decoded.slice(saltIndex + salt.length);
}
+6
View File
@@ -0,0 +1,6 @@
import { encodeKey } from "./encryptUtils";
export function saveShareKey(sharekey: string) {
const key = encodeKey(sharekey);
localStorage.setItem("workspace_manager_shareKey", key);
}
+17 -6
View File
@@ -4,7 +4,7 @@ import {
ScanLocalFolder, ScanLocalFolder,
scanLocalFiles, scanLocalFiles,
} from "../apis/TwowaySyncApi"; } from "../apis/TwowaySyncApi";
import { isFolder, userSettingsTable } from "../db-tables/WorkspaceDB"; import { isFolder } from "../db-tables/WorkspaceDB";
import { indexdb } from "../db-tables/indexdb"; import { indexdb } from "../db-tables/indexdb";
import { Folder, Workflow } from "../types/dbTypes"; import { Folder, Workflow } from "../types/dbTypes";
import { sortFileItem } from "../utils"; import { sortFileItem } from "../utils";
@@ -34,12 +34,23 @@ export async function scanMyWorkflowsDir(
return folder; return folder;
} else { } else {
// is workflow // is workflow
const existingWorkflow = (await indexdb.workflows?.get(file.id)) ?? {
createTime: Date.now(), const existingWorkflow = await indexdb.workflows
updateTime: Date.now(), ?.get(file.id)
}; .catch((err) => {
console.error(
"Error getting workflow from indexdb",
file.id,
relPath,
err,
);
return null;
});
const newWorkflow: Workflow = { const newWorkflow: Workflow = {
cloudID: file.cloudID,
coverMediaPath: file.coverMediaPath,
saveLock: file.saveLock,
...existingWorkflow, ...existingWorkflow,
id: file.id, id: file.id,
json: file.json ?? "{}", json: file.json ?? "{}",
@@ -48,7 +59,7 @@ export async function scanMyWorkflowsDir(
createTime: file.createTime, createTime: file.createTime,
// setting updateTime will result latestVersionChcek() always fail if in // setting updateTime will result latestVersionChcek() always fail if in
// workflow.get() not pull updateTime from file // workflow.get() not pull updateTime from file
// updateTime: file.updateTime, updateTime: file.updateTime,
}; };
return newWorkflow; return newWorkflow;
} }
@@ -0,0 +1,85 @@
import {
Button,
Flex,
Input,
Modal,
ModalBody,
ModalContent,
Stack,
useToast,
} from "@chakra-ui/react";
import { userSettingsTable } from "../db-tables/WorkspaceDB";
import { useContext } from "react";
import { WorkspaceContext } from "../WorkspaceContext";
import { saveShareKey } from "../utils/saveShareKey";
export default function CreateVersionLogin({
onClose,
}: {
onClose: () => void;
}) {
const cloudHost = userSettingsTable?.settings?.cloudHost;
const toast = useToast();
const { updateSession } = useContext(WorkspaceContext);
return (
<Modal isOpen={true} onClose={onClose} size={"xl"}>
<ModalContent width={"90vw"}>
<ModalBody>
<Stack p={"10px 10px"} gap={3}>
<h2
style={{
fontSize: "1.2rem",
fontWeight: "bold",
}}
>
✨New Version Control Exprience [beta]
</h2>
<p>
We have a new version control experience. Now your versions will
be stored <b>privately</b> and securely in cloud at{" "}
<a href="www.nodecafe.co">www.nodecafe.co</a>
</p>
<h3 style={{ fontWeight: "bold" }}>Why cloud?</h3>
<p>
Previously workflow versions are stored locally in your browser
storage. But people reported inconsistent versions when they
switched browser or device. Therefore we are moving to cloud. So
you can view your workflow versions from any devices, even your
phone.
</p>
<h3 style={{ fontWeight: "bold" }}>🤩Get Started</h3>
<Flex alignItems={"center"} gap={2} mb={3}>
<a href={cloudHost + "/auth/shareKey"} target="_blank">
<Button colorScheme="blue">Login</Button>
</a>
<p> then copy your share key to below</p>
</Flex>
<Input
placeholder="Paste your share key here"
onChange={(e) => {
if (
!e.target.value ||
e.target.value === "" ||
e.target.value.length < 20
) {
return;
}
saveShareKey(e.target.value);
updateSession({
shareKey: e.target.value,
username: null,
});
toast({
title: "Share key saved. You can create versions now.",
status: "success",
duration: 5000,
});
}}
/>
</Stack>
</ModalBody>
</ModalContent>
</Modal>
);
}

Some files were not shown because too many files have changed in this diff Show More