diff --git a/package-lock.json b/package-lock.json index 3cb66e79..5e235ccb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "@getalby/sdk": "^6.0.1", "@hookform/resolvers": "^3.9.0", "@isomorphic-git/lightning-fs": "^4.6.2", + "@modelcontextprotocol/sdk": "^1.22.0", "@mozilla/readability": "^0.6.0", "@nostrify/nostrify": "^0.47.1", "@nostrify/react": "^0.2.17", @@ -2866,6 +2867,60 @@ "integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==", "license": "BSD-2-Clause" }, + "node_modules/@modelcontextprotocol/sdk": { + "version": "1.22.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.22.0.tgz", + "integrity": "sha512-VUpl106XVTCpDmTBil2ehgJZjhyLY2QZikzF8NvTXtLRF1CvO5iEE2UNZdVIUer35vFOwMKYeUGbjJtvPWan3g==", + "license": "MIT", + "dependencies": { + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.0.1", + "express-rate-limit": "^7.5.0", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.23.8", + "zod-to-json-schema": "^3.24.1" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + } + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/ajv": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, "node_modules/@mozilla/readability": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.6.0.tgz", @@ -6103,6 +6158,19 @@ "integrity": "sha512-RYTOHHdWipFUliRFMCS4X2Yn2X8M87V/OpSqWzKKOGhzqyUxzyVmhHDH9sAvG+ZuQf/TAOFsLCpMw09I1ufUnA==", "license": "MIT" }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/acorn": { "version": "8.15.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", @@ -6152,6 +6220,45 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-formats/node_modules/ajv": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", + "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "license": "MIT" + }, "node_modules/ansi-regex": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", @@ -6500,6 +6607,26 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/body-parser": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.0.tgz", + "integrity": "sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^1.0.5", + "debug": "^4.4.0", + "http-errors": "^2.0.0", + "iconv-lite": "^0.6.3", + "on-finished": "^2.4.1", + "qs": "^6.14.0", + "raw-body": "^3.0.0", + "type-is": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/boolean": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz", @@ -6607,6 +6734,15 @@ "dev": true, "license": "MIT" }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/cac": { "version": "6.7.14", "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", @@ -7034,6 +7170,28 @@ "integrity": "sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==", "license": "MIT" }, + "node_modules/content-disposition": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.0.1.tgz", + "integrity": "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -7041,6 +7199,24 @@ "dev": true, "license": "MIT" }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, "node_modules/core-js-compat": { "version": "3.46.0", "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.46.0.tgz", @@ -7061,6 +7237,19 @@ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", "license": "MIT" }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/crc-32": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", @@ -7484,6 +7673,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/dequal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", @@ -7582,6 +7780,12 @@ "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", "license": "MIT" }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, "node_modules/ejs": { "version": "3.1.10", "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", @@ -7658,6 +7862,15 @@ "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", "license": "MIT" }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/end-of-stream": { "version": "1.4.5", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", @@ -7908,6 +8121,12 @@ "node": ">=6" } }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -8141,12 +8360,42 @@ "node": ">=0.10.0" } }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/eventemitter3": { "version": "4.0.7", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", "license": "MIT" }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz", + "integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/expect-type": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.2.1.tgz", @@ -8157,6 +8406,63 @@ "node": ">=12.0.0" } }, + "node_modules/express": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.1.0.tgz", + "integrity": "sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.0", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-rate-limit": { + "version": "7.5.1", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-7.5.1.tgz", + "integrity": "sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, "node_modules/extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", @@ -8200,7 +8506,6 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, "license": "MIT" }, "node_modules/fast-equals": { @@ -8264,7 +8569,6 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", - "dev": true, "funding": [ { "type": "github", @@ -8354,6 +8658,23 @@ "node": ">=8" } }, + "node_modules/finalhandler": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.0.tgz", + "integrity": "sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -8423,6 +8744,15 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/fraction.js": { "version": "4.3.7", "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", @@ -8437,6 +8767,15 @@ "url": "https://github.com/sponsors/rawify" } }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/fs-extra": { "version": "9.1.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", @@ -9213,6 +9552,26 @@ "dev": true, "license": "BSD-2-Clause" }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/http-proxy-agent": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", @@ -9290,7 +9649,6 @@ "version": "0.6.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dev": true, "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -9436,6 +9794,15 @@ "node": ">=12" } }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, "node_modules/is-array-buffer": { "version": "3.0.5", "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", @@ -9744,6 +10111,12 @@ "dev": true, "license": "MIT" }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, "node_modules/is-regex": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", @@ -10903,6 +11276,27 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", @@ -11522,6 +11916,31 @@ "node": ">=16" } }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/mimic-response": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", @@ -11638,6 +12057,15 @@ "dev": true, "license": "MIT" }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/node-releases": { "version": "2.0.26", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.26.tgz", @@ -11769,7 +12197,6 @@ "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", - "dev": true, "license": "MIT", "engines": { "node": ">= 0.4" @@ -11809,6 +12236,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -11980,6 +12419,15 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/path-browserify": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", @@ -12036,6 +12484,16 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/path-to-regexp": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.3.0.tgz", + "integrity": "sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -12095,6 +12553,15 @@ "node": ">= 6" } }, + "node_modules/pkce-challenge": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.0.tgz", + "integrity": "sha512-ueGLflrrnvwB3xuo/uGob5pd5FN7l0MsLf0Z87o/UQmRtwjvfylfc9MurIxRAWywCYTgrvpXBcqjV4OfCYGCIQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, "node_modules/pkg-types": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz", @@ -12405,6 +12872,19 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/pump": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz", @@ -12443,6 +12923,21 @@ "node": ">=10.13.0" } }, + "node_modules/qs": { + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", @@ -12486,6 +12981,46 @@ "safe-buffer": "^5.1.0" } }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/raw-body/node_modules/iconv-lite": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.0.tgz", + "integrity": "sha512-cf6L2Ds3h57VVmkZe+Pn+5APsT7FpqJtEhhieDCvrE2MK5Qk9MyffgQyuxQTm6BChfeZNtcOLHp9IcWRVcIcBQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/react": { "version": "18.3.1", "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", @@ -13075,7 +13610,6 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -13206,6 +13740,22 @@ "fsevents": "~2.3.2" } }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/rrweb-cssom": { "version": "0.8.0", "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", @@ -13315,7 +13865,6 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true, "license": "MIT" }, "node_modules/saxes": { @@ -13374,6 +13923,28 @@ "license": "MIT", "optional": true }, + "node_modules/send": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", + "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", + "license": "MIT", + "dependencies": { + "debug": "^4.3.5", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "mime-types": "^3.0.1", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/serialize-error": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz", @@ -13415,6 +13986,21 @@ "randombytes": "^2.1.0" } }, + "node_modules/serve-static": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + } + }, "node_modules/set-blocking": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", @@ -13475,6 +14061,12 @@ "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", "license": "MIT" }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, "node_modules/sha.js": { "version": "2.4.12", "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.12.tgz", @@ -13536,7 +14128,6 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", - "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -13556,7 +14147,6 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", - "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", @@ -13573,7 +14163,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", - "dev": true, "license": "MIT", "dependencies": { "call-bound": "^1.0.2", @@ -13592,7 +14181,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "dev": true, "license": "MIT", "dependencies": { "call-bound": "^1.0.2", @@ -13785,6 +14373,15 @@ "dev": true, "license": "MIT" }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/std-env": { "version": "3.9.0", "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.9.0.tgz", @@ -14509,6 +15106,15 @@ "node": ">=8.0" } }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, "node_modules/tough-cookie": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", @@ -14615,6 +15221,20 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", + "license": "MIT", + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/typed-array-buffer": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", @@ -14955,6 +15575,15 @@ "node": ">= 10.0.0" } }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/unplugin": { "version": "2.3.5", "resolved": "https://registry.npmjs.org/unplugin/-/unplugin-2.3.5.tgz", @@ -15124,6 +15753,15 @@ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "license": "MIT" }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/vaul": { "version": "0.9.9", "resolved": "https://registry.npmjs.org/vaul/-/vaul-0.9.9.tgz", @@ -16360,6 +16998,15 @@ "url": "https://github.com/sponsors/colinhacks" } }, + "node_modules/zod-to-json-schema": { + "version": "3.25.0", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.0.tgz", + "integrity": "sha512-HvWtU2UG41LALjajJrML6uQejQhNJx+JBO9IflpSja4R03iNWfKXrj6W2h7ljuLyc1nKS+9yDyL/9tD1U/yBnQ==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25 || ^4" + } + }, "node_modules/zwitch": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", diff --git a/package.json b/package.json index 33dbadbf..c9c28cda 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "@getalby/sdk": "^6.0.1", "@hookform/resolvers": "^3.9.0", "@isomorphic-git/lightning-fs": "^4.6.2", + "@modelcontextprotocol/sdk": "^1.22.0", "@mozilla/readability": "^0.6.0", "@nostrify/nostrify": "^0.47.1", "@nostrify/react": "^0.2.17", diff --git a/src/App.tsx b/src/App.tsx index 8c93c050..555c41fa 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -48,7 +48,7 @@ const queryClient = new QueryClient({ }); // Get OS-specific default paths for Electron -function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string } { +function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string; fsPathTemplates: string } { if (!globalThis.electron) { // Browser defaults - use virtual filesystem paths return { @@ -56,6 +56,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri fsPathConfig: "/config", fsPathTmp: "/tmp", fsPathPlugins: "/plugins", + fsPathTemplates: "/templates", }; } @@ -70,6 +71,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri fsPathConfig: "~/AppData/Local/shakespeare", fsPathTmp: "~/AppData/Local/Temp/shakespeare", fsPathPlugins: "~/AppData/Local/shakespeare/plugins", + fsPathTemplates: "~/AppData/Local/shakespeare/templates", }; } else if (platform.includes('mac')) { // macOS @@ -78,6 +80,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri fsPathConfig: "~/Library/Application Support/shakespeare", fsPathTmp: "/tmp/shakespeare", fsPathPlugins: "~/Library/Application Support/shakespeare/plugins", + fsPathTemplates: "~/Library/Application Support/shakespeare/templates", }; } else { // Linux and other Unix-like systems @@ -86,6 +89,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri fsPathConfig: "~/.config/shakespeare", fsPathTmp: "/tmp/shakespeare", fsPathPlugins: "~/.config/shakespeare/plugins", + fsPathTemplates: "~/.config/shakespeare/templates", }; } } @@ -114,6 +118,7 @@ const defaultConfig: AppConfig = { fsPathConfig: electronPaths.fsPathConfig, fsPathTmp: electronPaths.fsPathTmp, fsPathPlugins: electronPaths.fsPathPlugins, + fsPathTemplates: electronPaths.fsPathTemplates, sentryDsn: import.meta.env.VITE_SENTRY_DSN || "", sentryEnabled: true, }; diff --git a/src/components/AISettingsProvider.tsx b/src/components/AISettingsProvider.tsx index b808b098..3fe99666 100644 --- a/src/components/AISettingsProvider.tsx +++ b/src/components/AISettingsProvider.tsx @@ -1,6 +1,6 @@ import { useQueryClient } from '@tanstack/react-query'; import { ReactNode, useState, useEffect } from 'react'; -import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext'; +import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, type AISettingsContextType } from '@/contexts/AISettingsContext'; import { useFS } from '@/hooks/useFS'; import { useFSPaths } from '@/hooks/useFSPaths'; import { readAISettings, writeAISettings } from '@/lib/configUtils'; @@ -12,6 +12,7 @@ interface AISettingsProviderProps { const DEFAULT_SETTINGS: AISettings = { providers: [], recentlyUsedModels: [], + mcpServers: {}, }; export function AISettingsProvider({ children }: AISettingsProviderProps) { @@ -128,6 +129,27 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) { }); }; + const setMCPServer = (name: string, server: MCPServer) => { + setSettings(prev => ({ + ...prev, + mcpServers: { + ...(prev.mcpServers || {}), + [name]: server, + }, + })); + }; + + const removeMCPServer = (name: string) => { + setSettings(prev => { + const newMCPServers = { ...(prev.mcpServers || {}) }; + delete newMCPServers[name]; + return { + ...prev, + mcpServers: newMCPServers, + }; + }); + }; + const isConfigured = settings.providers.length > 0; const contextValue: AISettingsContextType = { @@ -137,6 +159,8 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) { removeProvider, setProviders, addRecentlyUsedModel, + setMCPServer, + removeMCPServer, isConfigured, }; diff --git a/src/components/AppProvider.tsx b/src/components/AppProvider.tsx index 0db9c91c..c9f5a66b 100644 --- a/src/components/AppProvider.tsx +++ b/src/components/AppProvider.tsx @@ -39,6 +39,7 @@ const AppConfigSchema = z.object({ fsPathConfig: z.string().min(1), fsPathTmp: z.string().min(1), fsPathPlugins: z.string().min(1), + fsPathTemplates: z.string().min(1), sentryDsn: z.string(), sentryEnabled: z.boolean(), }) satisfies z.ZodType; @@ -76,6 +77,7 @@ export function AppProvider(props: AppProviderProps) { config.fsPathProjects = expandPath(config.fsPathProjects); config.fsPathTmp = expandPath(config.fsPathTmp); config.fsPathPlugins = expandPath(config.fsPathPlugins); + config.fsPathTemplates = expandPath(config.fsPathTemplates); const appContextValue: AppContextType = { config, diff --git a/src/components/MCPServersSection.tsx b/src/components/MCPServersSection.tsx new file mode 100644 index 00000000..0a676188 --- /dev/null +++ b/src/components/MCPServersSection.tsx @@ -0,0 +1,339 @@ +import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { Server, Trash2, Check, Plus, X } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; +import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'; +import { Separator } from '@/components/ui/separator'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { useAISettings } from '@/hooks/useAISettings'; +import { useToast } from '@/hooks/useToast'; +import { useMCPServerStatus } from '@/hooks/useMCPServerStatus'; +import type { MCPServer } from '@/contexts/AISettingsContext'; +import { cn } from '@/lib/utils'; + +function MCPConnectionStatus({ server }: { server: MCPServer }) { + const status = useMCPServerStatus(server); + + return ( +
+
+ + {status} + +
+ ); +} + +interface HeadersEditorProps { + headers: Record | undefined; + onChange: (headers: Record | undefined) => void; +} + +function HeadersEditor({ headers, onChange }: HeadersEditorProps) { + const { t } = useTranslation(); + const [newHeaderName, setNewHeaderName] = useState(''); + const [newHeaderValue, setNewHeaderValue] = useState(''); + + const headerEntries = Object.entries(headers || {}); + + const handleAddHeader = () => { + if (!newHeaderName.trim() || !newHeaderValue.trim()) return; + + const updatedHeaders = { + ...(headers || {}), + [newHeaderName.trim()]: newHeaderValue.trim(), + }; + + onChange(updatedHeaders); + setNewHeaderName(''); + setNewHeaderValue(''); + }; + + const handleRemoveHeader = (name: string) => { + const updatedHeaders = { ...(headers || {}) }; + delete updatedHeaders[name]; + + // If no headers left, set to undefined + onChange(Object.keys(updatedHeaders).length > 0 ? updatedHeaders : undefined); + }; + + const handleUpdateHeader = (oldName: string, newName: string, newValue: string) => { + const updatedHeaders = { ...(headers || {}) }; + delete updatedHeaders[oldName]; + updatedHeaders[newName] = newValue; + onChange(updatedHeaders); + }; + + return ( +
+ +

+ {t('mcpServerHeadersDescription')} +

+ + {/* Existing Headers */} + {headerEntries.length > 0 && ( +
+ {headerEntries.map(([name, value]) => ( +
+ handleUpdateHeader(name, e.target.value, value)} + placeholder="Header name" + className="flex-1" + /> + handleUpdateHeader(name, name, e.target.value)} + placeholder="Header value" + className="flex-1" + /> + +
+ ))} +
+ )} + + {/* Add New Header */} +
+ setNewHeaderName(e.target.value)} + placeholder="Header name (e.g., Authorization)" + className="flex-1" + /> + setNewHeaderValue(e.target.value)} + placeholder="Header value" + className="flex-1" + /> + +
+
+ ); +} + +export function MCPServersSection() { + const { t } = useTranslation(); + const { settings, setMCPServer, removeMCPServer } = useAISettings(); + const { toast } = useToast(); + const [serverName, setServerName] = useState(''); + const [serverUrl, setServerUrl] = useState(''); + const [serverHeaders, setServerHeaders] = useState | undefined>(undefined); + const [serverType] = useState<'streamable-http'>('streamable-http'); // Only streamable-http is supported + + const mcpServers = settings.mcpServers || {}; + const serverEntries = Object.entries(mcpServers); + + const handleAddServer = () => { + if (!serverName.trim() || !serverUrl.trim()) return; + + if (mcpServers[serverName.trim()]) { + toast({ + title: t('error'), + description: t('mcpServerAddFailed'), + variant: 'destructive', + }); + return; + } + + const newServer: MCPServer = { + type: serverType, + url: serverUrl.trim(), + headers: serverHeaders, + }; + + setMCPServer(serverName.trim(), newServer); + + toast({ + title: t('mcpServerAdded'), + description: t('mcpServerAddedDescription', { name: serverName.trim() }), + }); + + setServerName(''); + setServerUrl(''); + setServerHeaders(undefined); + }; + + const handleRemoveServer = (name: string) => { + removeMCPServer(name); + + toast({ + title: t('mcpServerDeleted'), + description: t('mcpServerDeletedDescription', { name }), + }); + }; + + return ( +
+ {/* Divider */} + + + {/* MCP Servers Header */} +
+
+ +

{t('mcpServers')}

+
+

+ {t('mcpServersDescription')} +

+
+ + {/* Configured MCP Servers List */} + {serverEntries.length > 0 ? ( +
+ {serverEntries.map(([name, server]) => ( + + + +
+ + {name} + +
+
+ +
+
+ + +
+
+ + setMCPServer(name, { ...server, url: e.target.value })} + placeholder="https://example.com/mcp" + /> +
+ setMCPServer(name, { ...server, headers })} + /> + +
+
+
+
+ ))} +
+ ) : ( + + + {t('noMcpServersConfigured')} + + + )} + + {/* Add New MCP Server */} + + + +
+ + {t('addMcpServer')} +
+
+ +
+

+ {t('mcpServerDescription')} +

+
+ + setServerName(e.target.value)} + /> +
+
+ + +

+ Only Streamable HTTP transport is currently supported +

+
+
+ + setServerUrl(e.target.value)} + /> +
+ + + {mcpServers[serverName.trim()] && ( +

+ A server with this name already exists +

+ )} +
+
+
+
+
+ ); +} diff --git a/src/components/ModelSelector.test.tsx b/src/components/ModelSelector.test.tsx index 880afd98..d02c993c 100644 --- a/src/components/ModelSelector.test.tsx +++ b/src/components/ModelSelector.test.tsx @@ -42,14 +42,15 @@ describe('ModelSelector', () => { vi.clearAllMocks(); mockUseAISettings.mockReturnValue({ - settings: { providers: [], recentlyUsedModels: [] }, + settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, addRecentlyUsedModel: mockAddRecentlyUsedModel, isConfigured: true, updateSettings: vi.fn(), removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), - + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); mockUseProviderModels.mockReturnValue({ @@ -87,6 +88,8 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); @@ -140,6 +143,8 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); @@ -189,6 +194,8 @@ describe('ModelSelector', () => { removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); @@ -233,13 +240,15 @@ describe('ModelSelector', () => { }); mockUseAISettings.mockReturnValue({ - settings: { providers: [], recentlyUsedModels: [] }, // No recently used models + settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, // No recently used models addRecentlyUsedModel: mockAddRecentlyUsedModel, isConfigured: true, updateSettings: vi.fn(), removeProvider: vi.fn(), setProvider: vi.fn(), setProviders: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); diff --git a/src/components/SentryProvider.test.tsx b/src/components/SentryProvider.test.tsx index 70369f04..d98f7c24 100644 --- a/src/components/SentryProvider.test.tsx +++ b/src/components/SentryProvider.test.tsx @@ -39,6 +39,7 @@ describe('SentryProvider', () => { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', }; render( @@ -75,6 +76,7 @@ describe('SentryProvider', () => { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', }; render( @@ -112,6 +114,7 @@ describe('SentryProvider', () => { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', }; render( @@ -152,6 +155,7 @@ describe('SentryProvider', () => { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', }; render( diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 782be834..88529db3 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -14,6 +14,7 @@ import { useAppContext } from '@/hooks/useAppContext'; import { useAIChat } from '@/hooks/useAIChat'; import { useProviderModels } from '@/hooks/useProviderModels'; import { useSessionManager } from '@/hooks/useSessionManager'; +import { useMCPTools } from '@/hooks/useMCPTools'; import { AIMessageItem } from '@/components/AIMessageItem'; import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool'; import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool'; @@ -35,6 +36,7 @@ import { ShellTool } from '@/lib/tools/ShellTool'; import { TypecheckTool } from '@/lib/tools/TypecheckTool'; import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool'; import { SkillTool } from '@/lib/tools/SkillTool'; +import { createMCPTools } from '@/lib/tools/MCPTool'; import { ProjectPreviewConsoleError } from '@/lib/consoleMessages'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; @@ -148,8 +150,12 @@ export const ChatPane = forwardRef(({ sessionManager.emit('fileChanged', projectId, filePath); }, [sessionManager, projectId]); - const customTools = useMemo(() => { - const baseTools = { + // Fetch MCP tools + const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools(); + + // Separate built-in tools from MCP tools for clarity + const builtInTools = useMemo(() => { + const tools: Record> = { git_commit: new GitCommitTool(fs, cwd, git), text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }), text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }), @@ -166,30 +172,42 @@ export const ChatPane = forwardRef(({ nostr_read_nips_index: new NostrReadNipsIndexTool(), nostr_generate_kind: new NostrGenerateKindTool(), nostr_publish_events: new NostrPublishEventsTool(), - shell: new ShellTool(fs, cwd, git, projectsPath, config.corsProxy, user?.signer), + shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer), read_console_messages: new ReadConsoleMessagesTool(), skill: new SkillTool(fs, pluginsPath), }; // Add deploy tool only if user is logged in if (user && user.signer) { - return { - ...baseTools, - deploy_project: new DeployProjectTool(fs, cwd, user.signer, projectId), - }; + tools.deploy_project = new DeployProjectTool(fs, cwd, user.signer, projectId); } - return baseTools; + return tools; }, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]); - // Convert tools to OpenAI format + // MCP tools wrapped for execution + const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]); + + // Combined tool executors (for SessionManager to call) + const customTools = useMemo(() => ({ + ...builtInTools, + ...mcpToolWrappers, + }), [builtInTools, mcpToolWrappers]); + + // Convert tools to OpenAI format for AI provider const tools = useMemo(() => { const result: Record = {}; - for (const [name, tool] of Object.entries(customTools)) { + + // Convert built-in tools to OpenAI format + for (const [name, tool] of Object.entries(builtInTools)) { result[name] = toolToOpenAI(name, tool as Tool); } + + // Add MCP tools (already in OpenAI format from useMCPTools) + Object.assign(result, mcpOpenAITools); + return result; - }, [customTools]); + }, [builtInTools, mcpOpenAITools]); // Keep-alive functionality to prevent tab throttling during AI processing const { updateMetadata } = useKeepAlive({ diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 29ad34f9..a24e9115 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -801,7 +801,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
- +
) : ( @@ -895,7 +895,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
{desktopCodeView === 'terminal' ? (
- +
) : ( <> diff --git a/src/components/Terminal.tsx b/src/components/Terminal.tsx index 2fccd501..a7934fbe 100644 --- a/src/components/Terminal.tsx +++ b/src/components/Terminal.tsx @@ -5,14 +5,13 @@ import { Copy } from 'lucide-react'; import { cn } from '@/lib/utils'; import { ShellTool } from '@/lib/tools/ShellTool'; import { useFS } from '@/hooks/useFS'; -import { useFSPaths } from '@/hooks/useFSPaths'; import { useGit } from '@/hooks/useGit'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useAppContext } from '@/hooks/useAppContext'; import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml'; interface TerminalProps { - projectId: string; + cwd: string; className?: string; } @@ -23,7 +22,7 @@ interface TerminalLine { timestamp: Date; } -export function Terminal({ projectId, className }: TerminalProps) { +export function Terminal({ cwd, className }: TerminalProps) { const [lines, setLines] = useState([]); const [currentInput, setCurrentInput] = useState(''); const [isExecuting, setIsExecuting] = useState(false); @@ -35,14 +34,13 @@ export function Terminal({ projectId, className }: TerminalProps) { const shellToolRef = useRef(null); const { fs } = useFS(); - const { projectsPath } = useFSPaths(); const { git } = useGit(); const { user } = useCurrentUser(); const { config } = useAppContext(); // Initialize ShellTool useEffect(() => { - shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, config.corsProxy, user?.signer); + shellToolRef.current = new ShellTool(fs, cwd, git, config.corsProxy, user?.signer); // Add welcome message setLines([{ @@ -51,7 +49,7 @@ export function Terminal({ projectId, className }: TerminalProps) { content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`, timestamp: new Date() }]); - }, [projectId, fs, git, projectsPath, config.corsProxy, user?.signer]); + }, [cwd, fs, git, config.corsProxy, user?.signer]); // Auto-scroll to bottom when new lines are added or execution state changes useEffect(() => { @@ -108,10 +106,8 @@ export function Terminal({ projectId, className }: TerminalProps) { // Check if running in Electron - use real shell if (window.electron?.shell) { - // Use the full path (with ~ if present) - Electron will expand it - const fullCwd = `${projectsPath}/${projectId}`; - - const result = await window.electron.shell.exec(command, fullCwd); + // Use the provided cwd (Electron will expand ~ if present) + const result = await window.electron.shell.exec(command, cwd); // Format output let output = ''; @@ -159,7 +155,7 @@ export function Terminal({ projectId, className }: TerminalProps) { } finally { setIsExecuting(false); } - }, [addLine, commandHistory, projectId, projectsPath]); + }, [addLine, commandHistory, cwd]); const handleSubmit = useCallback((e: React.FormEvent) => { e.preventDefault(); diff --git a/src/components/TerminalTest.tsx b/src/components/TerminalTest.tsx index 0f7574e8..4fe01acc 100644 --- a/src/components/TerminalTest.tsx +++ b/src/components/TerminalTest.tsx @@ -6,7 +6,7 @@ import { Terminal } from './Terminal'; export function TerminalTest() { return (
- +
); } diff --git a/src/contexts/AISettingsContext.ts b/src/contexts/AISettingsContext.ts index 85d5d7cd..77984638 100644 --- a/src/contexts/AISettingsContext.ts +++ b/src/contexts/AISettingsContext.ts @@ -8,9 +8,20 @@ export interface AIProvider { proxy?: boolean; } +export interface MCPServer { + type: 'streamable-http'; + url: string; + headers?: Record; +} + +export interface MCPServers { + [key: string]: MCPServer; +} + export interface AISettings { providers: AIProvider[]; recentlyUsedModels: string[]; + mcpServers?: MCPServers; } export interface AISettingsContextType { @@ -20,6 +31,8 @@ export interface AISettingsContextType { removeProvider: (id: string) => void; setProviders: (providers: AIProvider[]) => void; addRecentlyUsedModel: (modelId: string) => void; + setMCPServer: (name: string, server: MCPServer) => void; + removeMCPServer: (name: string) => void; isConfigured: boolean; } diff --git a/src/contexts/AppContext.ts b/src/contexts/AppContext.ts index 9523ac66..8664e1cb 100644 --- a/src/contexts/AppContext.ts +++ b/src/contexts/AppContext.ts @@ -40,6 +40,8 @@ export interface AppConfig { fsPathTmp: string; /** VFS path for plugins directory */ fsPathPlugins: string; + /** VFS path for templates directory */ + fsPathTemplates: string; /** Sentry DSN for error reporting (empty string = disabled) */ sentryDsn: string; /** Whether the user has enabled Sentry error reporting */ diff --git a/src/hooks/useAIProjectId.test.ts b/src/hooks/useAIProjectId.test.ts index 26026962..3443db42 100644 --- a/src/hooks/useAIProjectId.test.ts +++ b/src/hooks/useAIProjectId.test.ts @@ -56,6 +56,7 @@ describe('useAIProjectId', () => { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', sentryDsn: '', sentryEnabled: false, }; @@ -93,13 +94,15 @@ describe('useAIProjectId', () => { it('should return not configured when AI settings are not configured', () => { mockUseAISettings.mockReturnValue({ - settings: { providers: [], recentlyUsedModels: [] }, + settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, isConfigured: false, updateSettings: vi.fn(), setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), addRecentlyUsedModel: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); const { result } = renderHook(() => useAIProjectId()); @@ -110,7 +113,7 @@ describe('useAIProjectId', () => { it('should throw error when trying to generate ID without configuration', async () => { mockUseAISettings.mockReturnValue({ - settings: { providers: [], recentlyUsedModels: [] }, + settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, isConfigured: false, updateSettings: vi.fn(), setProvider: vi.fn(), @@ -118,6 +121,8 @@ describe('useAIProjectId', () => { setProviders: vi.fn(), addRecentlyUsedModel: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); const { result } = renderHook(() => useAIProjectId()); @@ -142,6 +147,8 @@ describe('useAIProjectId', () => { setProviders: vi.fn(), addRecentlyUsedModel: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); const { result } = renderHook(() => useAIProjectId()); @@ -166,6 +173,8 @@ describe('useAIProjectId', () => { setProviders: vi.fn(), addRecentlyUsedModel: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); const { result } = renderHook(() => useAIProjectId()); @@ -189,6 +198,8 @@ describe('useAIProjectId', () => { setProviders: vi.fn(), addRecentlyUsedModel: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); const { result } = renderHook(() => useAIProjectId()); @@ -221,6 +232,8 @@ describe('useAIProjectId', () => { setProviders: vi.fn(), addRecentlyUsedModel: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); // Mock AI response - returns a project name that already exists @@ -274,6 +287,8 @@ describe('useAIProjectId', () => { setProviders: vi.fn(), addRecentlyUsedModel: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); // Mock AI to return a project name that already exists @@ -329,6 +344,8 @@ describe('useAIProjectId', () => { setProviders: vi.fn(), addRecentlyUsedModel: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); // Mock AI to return a very long project name (over 50 characters) @@ -379,6 +396,8 @@ describe('useAIProjectId', () => { setProviders: vi.fn(), addRecentlyUsedModel: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); // Mock AI to return an invalid project name (doesn't match regex) @@ -429,6 +448,8 @@ describe('useAIProjectId', () => { setProviders: vi.fn(), addRecentlyUsedModel: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); // Mock AI to return a project name that already exists @@ -486,6 +507,8 @@ describe('useAIProjectId', () => { setProviders: vi.fn(), addRecentlyUsedModel: vi.fn(), + setMCPServer: vi.fn(), + removeMCPServer: vi.fn(), }); const { result } = renderHook(() => useAIProjectId()); diff --git a/src/hooks/useFSPaths.ts b/src/hooks/useFSPaths.ts index d9ec08ea..9fd95618 100644 --- a/src/hooks/useFSPaths.ts +++ b/src/hooks/useFSPaths.ts @@ -17,5 +17,7 @@ export function useFSPaths() { tmpPath: config.fsPathTmp, /** Plugins directory path (default: /plugins) */ pluginsPath: config.fsPathPlugins, + /** Templates directory path (default: /templates) */ + templatesPath: config.fsPathTemplates, }; } diff --git a/src/hooks/useGit.test.ts b/src/hooks/useGit.test.ts index 748bf7cb..76d4b6f9 100644 --- a/src/hooks/useGit.test.ts +++ b/src/hooks/useGit.test.ts @@ -49,6 +49,7 @@ function createWrapper(corsProxy: string) { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', sentryDsn: '', sentryEnabled: false, }; diff --git a/src/hooks/useMCPServerStatus.ts b/src/hooks/useMCPServerStatus.ts new file mode 100644 index 00000000..9d6eaafe --- /dev/null +++ b/src/hooks/useMCPServerStatus.ts @@ -0,0 +1,45 @@ +import { useEffect, useState } from 'react'; +import { MCPClient } from '@/lib/MCPClient'; +import type { MCPServer } from '@/contexts/AISettingsContext'; + +/** + * Hook to check the connection status of an MCP server. + * Returns 'connected', 'offline', or 'checking'. + */ +export function useMCPServerStatus(server: MCPServer): 'connected' | 'offline' | 'checking' { + const [status, setStatus] = useState<'connected' | 'offline' | 'checking'>('checking'); + + useEffect(() => { + let cancelled = false; + + async function checkConnection() { + setStatus('checking'); + + try { + const client = new MCPClient(server); + await client.connect(); + + // Try to list tools to verify the connection is working + await client.listTools(); + + await client.close(); + + if (!cancelled) { + setStatus('connected'); + } + } catch { + if (!cancelled) { + setStatus('offline'); + } + } + } + + checkConnection(); + + return () => { + cancelled = true; + }; + }, [server]); // Re-check when server config changes + + return status; +} diff --git a/src/hooks/useMCPTools.ts b/src/hooks/useMCPTools.ts new file mode 100644 index 00000000..ac3d1fc4 --- /dev/null +++ b/src/hooks/useMCPTools.ts @@ -0,0 +1,39 @@ +import { useQuery } from '@tanstack/react-query'; +import { useAISettings } from './useAISettings'; +import { discoverMCPTools } from '@/lib/MCPClient'; +import type OpenAI from 'openai'; +import type { MCPClient } from '@/lib/MCPClient'; + +interface UseMCPToolsResult { + tools: Record; + clients: Record; + isLoading: boolean; + error: Error | null; +} + +/** + * Hook to discover and manage MCP tools from configured servers. + */ +export function useMCPTools(): UseMCPToolsResult { + const { settings } = useAISettings(); + const mcpServers = settings.mcpServers || {}; + + const { data, isLoading, error } = useQuery({ + queryKey: ['mcp-tools', mcpServers], + queryFn: async () => { + if (Object.keys(mcpServers).length === 0) { + return { tools: {}, clients: {} }; + } + return await discoverMCPTools(mcpServers); + }, + staleTime: 5 * 60 * 1000, // Cache for 5 minutes + retry: 1, + }); + + return { + tools: data?.tools || {}, + clients: data?.clients || {}, + isLoading, + error: error as Error | null, + }; +} diff --git a/src/hooks/useProjectsManager.ts b/src/hooks/useProjectsManager.ts index 8f15bd95..9a871852 100644 --- a/src/hooks/useProjectsManager.ts +++ b/src/hooks/useProjectsManager.ts @@ -11,11 +11,11 @@ import { useGit } from './useGit'; export function useProjectsManager() { const { fs } = useFS(); const { git } = useGit(); - const { projectsPath } = useFSPaths(); + const { projectsPath, templatesPath } = useFSPaths(); const projectsManager = useMemo(() => { - return new ProjectsManager({ fs, git, projectsPath }); - }, [fs, git, projectsPath]); + return new ProjectsManager({ fs, git, projectsPath, templatesPath }); + }, [fs, git, projectsPath, templatesPath]); return projectsManager; } \ No newline at end of file diff --git a/src/lib/MCPClient.ts b/src/lib/MCPClient.ts new file mode 100644 index 00000000..c430f245 --- /dev/null +++ b/src/lib/MCPClient.ts @@ -0,0 +1,167 @@ +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import type { MCPServer } from '@/contexts/AISettingsContext'; +import type OpenAI from 'openai'; + +/** + * MCP (Model Context Protocol) Client for discovering and executing tools from MCP servers. + * Uses the official @modelcontextprotocol/sdk library. + */ +export class MCPClient { + private client: Client; + private transport: StreamableHTTPClientTransport; + private connected = false; + + constructor(server: MCPServer) { + // Create the client + this.client = new Client({ + name: 'shakespeare', + version: '1.0.0', + }, { + capabilities: {} + }); + + // Create HTTP transport with optional custom headers + this.transport = new StreamableHTTPClientTransport(new URL(server.url), { + requestInit: server.headers ? { + headers: server.headers, + } : undefined, + }); + } + + /** + * Connect to the MCP server. + */ + async connect(): Promise { + if (this.connected) return; + + await this.client.connect(this.transport); + this.connected = true; + } + + /** + * List all available tools from the MCP server. + */ + async listTools(): Promise; + required?: string[]; + }; + }>> { + await this.connect(); + + const result = await this.client.listTools(); + return result.tools; + } + + /** + * Call a tool on the MCP server. + */ + async callTool(name: string, args: Record): Promise { + await this.connect(); + + const result = await this.client.callTool({ + name, + arguments: args, + }); + + const content = Array.isArray(result.content) ? result.content : []; + + if (result.isError) { + const errorText = content + .filter((c): c is { type: 'text'; text: string } => c.type === 'text') + .map(c => c.text) + .join('\n'); + throw new Error(`MCP tool error: ${errorText}`); + } + + // Concatenate all text content from the response + return content + .filter((c): c is { type: 'text'; text: string } => c.type === 'text') + .map(c => c.text) + .join('\n'); + } + + /** + * Close the connection to the MCP server. + */ + async close(): Promise { + if (!this.connected) return; + + await this.client.close(); + this.connected = false; + } + + /** + * Convert MCP tools to OpenAI tool format. + */ + static toOpenAITools(mcpTools: Array<{ + name: string; + description?: string; + inputSchema: { + type: 'object'; + properties?: Record; + required?: string[]; + }; + }>): Record { + const tools: Record = {}; + + for (const tool of mcpTools) { + tools[tool.name] = { + type: 'function', + function: { + name: tool.name, + description: tool.description || '', + parameters: tool.inputSchema as Record, + }, + } as OpenAI.Chat.Completions.ChatCompletionTool; + } + + return tools; + } +} + +/** + * Discover tools from all configured MCP servers. + */ +export async function discoverMCPTools( + mcpServers: Record +): Promise<{ + tools: Record; + clients: Record; +}> { + const allTools: Record = {}; + const clients: Record = {}; + + for (const [serverName, serverConfig] of Object.entries(mcpServers)) { + try { + const client = new MCPClient(serverConfig); + const mcpTools = await client.listTools(); + const openAITools = MCPClient.toOpenAITools(mcpTools); + + // Store tools with server prefix to avoid name collisions + for (const [toolName, tool] of Object.entries(openAITools)) { + const prefixedName = `${serverName}__${toolName}`; + const functionTool = tool as OpenAI.Chat.Completions.ChatCompletionTool & { + function: { name: string; description: string; parameters: Record } + }; + allTools[prefixedName] = { + type: 'function', + function: { + ...functionTool.function, + name: prefixedName, + description: `[${serverName}] ${functionTool.function.description}`, + }, + } as OpenAI.Chat.Completions.ChatCompletionTool; + clients[prefixedName] = client; + } + } catch (error) { + console.error(`Failed to discover tools from MCP server "${serverName}":`, error); + } + } + + return { tools: allTools, clients }; +} diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index 22b59ea6..2f87d6a2 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -219,7 +219,7 @@ describe('ProjectsManager', () => { fs = new MockFS() as unknown as JSRuntimeFS; nostr = createMockNostr(); git = new Git({ fs, nostr }); - projectsManager = new ProjectsManager({ fs, git }); + projectsManager = new ProjectsManager({ fs, git, projectsPath: '/projects', templatesPath: '/templates' }); }); describe('getProjects', () => { diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 9013acea..c9f38121 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -20,18 +20,22 @@ export interface ProjectsManagerOptions { fs: JSRuntimeFS; git: Git; /** Projects directory path (default: /projects) */ - projectsPath?: string; + projectsPath: string; + /** Templates directory path (default: /templates) */ + templatesPath: string; } export class ProjectsManager { fs: JSRuntimeFS; git: Git; dir: string; + templatesDir: string; constructor(options: ProjectsManagerOptions) { this.fs = options.fs; this.git = options.git; - this.dir = options.projectsPath || '/projects'; + this.dir = options.projectsPath; + this.templatesDir = options.templatesPath; } async init() { @@ -40,58 +44,239 @@ export class ProjectsManager { } catch { // Directory might already exist } + try { + await this.fs.mkdir(this.templatesDir); + } catch { + // Directory might already exist + } } - async createProject(name: string, templateUrl: string, customId?: string): Promise { - const project = await this.cloneProject(name, templateUrl, customId, { depth: 1 }); + /** + * Ensure a template is cached locally and up-to-date. + * Returns the path to the cached template. + * + * @param templateUrl - Git repository URL of the template + * @param onUpdateError - Optional callback when template update fails (non-critical) + * @returns Path to the cached template directory + */ + async updateTemplate(templateUrl: string, onUpdateError?: (error: Error) => void): Promise { + // Generate a safe directory name from the template URL + const templateName = this.getTemplateNameFromUrl(templateUrl); + const templatePath = `${this.templatesDir}/${templateName}`; - // Delete README.md if it exists try { - await this.fs.unlink(`${project.path}/README.md`); + // Check if template already exists + await this.fs.stat(templatePath); + + // Template exists, try to update it with force pull + try { + await this.forcePullTemplate(templatePath); + } catch (updateError) { + // Update failed, but we can continue with the existing template + console.warn(`Failed to update template at ${templatePath}:`, updateError); + if (onUpdateError) { + onUpdateError(updateError instanceof Error ? updateError : new Error(String(updateError))); + } + } } catch { - // README.md might not exist, ignore error - } + // Template doesn't exist, clone it shallowly + await this.fs.mkdir(templatePath, { recursive: true }); - // Delete .git directory and reinitialize - try { - await this.deleteDirectory(`${project.path}/.git`); - } catch { - // .git directory might not exist, ignore error - } - - // Initialize new git repository - await this.git.init({ - dir: project.path, - defaultBranch: 'main', - }); - - // Add all files to git - const files = await this.getAllFiles(project.path); - for (const file of files) { - // Skip .git directory - if (!file.startsWith('.git/')) { - await this.git.add({ - dir: project.path, - filepath: file, + try { + await this.git.clone({ + dir: templatePath, + url: templateUrl, + singleBranch: true, + depth: 1, }); + } catch (cloneError) { + // Clean up on clone failure + try { + await this.deleteDirectory(templatePath); + } catch { + // Ignore cleanup errors + } + throw cloneError; } } - // Make initial commit - await this.git.commit({ - dir: project.path, - message: 'New project created with Shakespeare', + return templatePath; + } + + /** + * Force pull the template repository to match remote, discarding any local changes. + * This ensures the template is always up-to-date with the remote. + */ + private async forcePullTemplate(templatePath: string): Promise { + // Fetch the latest changes from remote + const fetchResult = await this.git.fetch({ + dir: templatePath, + singleBranch: true, + depth: 1, }); - // Automatically request persistent storage after project creation - try { - await ensurePersistentStorage(); - } catch (error) { - // Don't fail project creation if persistent storage request fails - console.warn('Failed to request persistent storage after project creation:', error); + // Get the current branch name + const branch = fetchResult.defaultBranch; + + if (!branch) { + throw new Error('Could not determine current branch'); } - return project; + // Reset hard to the remote branch, discarding all local changes + await this.git.checkout({ + dir: templatePath, + ref: branch, + force: true, + }); + } + + /** + * Generate a safe directory name from a template URL + */ + private getTemplateNameFromUrl(url: string): string { + // Extract a meaningful name from the URL + // e.g., "https://gitlab.com/soapbox-pub/mkstack.git" -> "mkstack" + // e.g., "nostr://alex@gleasonator.dev/shakespeare.diy/mkstack" -> "mkstack" + + let name = url; + + // Remove .git suffix if present + name = name.replace(/\.git$/, ''); + + // Remove trailing slash + name = name.replace(/\/$/, ''); + + // Extract the last part of the path + const parts = name.split('/'); + name = parts[parts.length - 1] || ''; + + // Sanitize the name to be filesystem-safe + name = name + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); + + if (!name) { + throw new Error(`Could not derive template name from URL: ${url}`); + } + + return name; + } + + /** + * Copy a directory recursively from source to destination + */ + private async copyDirectory(sourcePath: string, destPath: string): Promise { + // Ensure destination directory exists + await this.fs.mkdir(destPath, { recursive: true }); + + const entries = await this.fs.readdir(sourcePath); + + for (const entry of entries) { + // Skip .git directory + if (entry === '.git') continue; + + const sourceFullPath = `${sourcePath}/${entry}`; + const destFullPath = `${destPath}/${entry}`; + + try { + const stat = await this.fs.lstat(sourceFullPath); + + if (stat.isDirectory()) { + // Recursively copy subdirectories + await this.copyDirectory(sourceFullPath, destFullPath); + } else if (stat.isFile()) { + // Copy file + const content = await this.fs.readFile(sourceFullPath); + await this.fs.writeFile(destFullPath, content); + } + } catch (error) { + console.warn(`Failed to copy ${sourceFullPath}:`, error); + // Continue copying other files + } + } + } + + async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void): Promise { + const id = customId || await this.generateUniqueProjectId(name); + + // Check if project with this ID already exists when using custom ID + if (customId && await this.projectExists(id)) { + throw new Error(`Project with ID "${id}" already exists`); + } + + const projectPath = `${this.dir}/${id}`; + + // Ensure template is cached and up-to-date + const templatePath = await this.updateTemplate(templateUrl, onTemplateUpdateError); + + // Create project directory + await this.fs.mkdir(projectPath, { recursive: true }); + + try { + // Copy template to project directory (excluding .git) + await this.copyDirectory(templatePath, projectPath); + + // Delete README.md if it exists + try { + await this.fs.unlink(`${projectPath}/README.md`); + } catch { + // README.md might not exist, ignore error + } + + // Initialize new git repository + await this.git.init({ + dir: projectPath, + defaultBranch: 'main', + }); + + // Add all files to git + const files = await this.getAllFiles(projectPath); + for (const file of files) { + // Skip .git directory + if (!file.startsWith('.git/')) { + await this.git.add({ + dir: projectPath, + filepath: file, + }); + } + } + + // Make initial commit + await this.git.commit({ + dir: projectPath, + message: 'New project created with Shakespeare', + }); + + // Get filesystem stats for timestamps + const stats = await this.fs.stat(projectPath); + const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date(); + + // Automatically request persistent storage after project creation + try { + await ensurePersistentStorage(); + } catch (error) { + // Don't fail project creation if persistent storage request fails + console.warn('Failed to request persistent storage after project creation:', error); + } + + return { + id, + name: this.formatProjectName(id), + path: projectPath, + lastModified: timestamp, + }; + } catch (error) { + // Clean up the directory that was created if project creation fails + try { + await this.deleteDirectory(projectPath); + } catch (cleanupError) { + // Log cleanup error but don't mask the original error + console.warn('Failed to clean up directory after project creation failure:', cleanupError); + } + // Re-throw the original error + throw error; + } } async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise { diff --git a/src/lib/SessionManager.test.ts b/src/lib/SessionManager.test.ts index ee15cf3b..401c46bd 100644 --- a/src/lib/SessionManager.test.ts +++ b/src/lib/SessionManager.test.ts @@ -53,6 +53,7 @@ const testConfig: AppConfig = { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', sentryDsn: '', sentryEnabled: false, }; diff --git a/src/lib/commands/README.md b/src/lib/commands/README.md index 5bf08cfa..9a8d45f2 100644 --- a/src/lib/commands/README.md +++ b/src/lib/commands/README.md @@ -609,7 +609,7 @@ Commands are executed through the `ShellTool` which handles: import { ShellTool } from '@/lib/tools/ShellTool'; // Create shell tool with filesystem and working directory -const shell = new ShellTool(fs, '/project/root'); +const shell = new ShellTool(fs, '/project/root', ...rest); // Execute commands const result = await shell.execute({ command: 'cat package.json' }); diff --git a/src/lib/commands/git.ts b/src/lib/commands/git.ts index 78dafe79..a2260ba7 100644 --- a/src/lib/commands/git.ts +++ b/src/lib/commands/git.ts @@ -28,13 +28,12 @@ export interface GitSubcommand { name: string; description: string; usage: string; - execute(args: string[]): Promise; + execute(args: string[], cwd: string): Promise; } export interface GitSubcommandOptions { git: Git; fs: JSRuntimeFS; - pwd: string; signer?: NostrSigner; } @@ -71,7 +70,6 @@ export class GitCommand implements ShellCommand { const subcommandOptions: GitSubcommandOptions = { git: this.git, fs: this.fs, - pwd: this.cwd, signer: this.signer, }; @@ -99,7 +97,7 @@ export class GitCommand implements ShellCommand { this.subcommands.set(subcommand.name, subcommand); } - async execute(args: string[], _cwd: string, _input?: string): Promise { + async execute(args: string[], cwd: string, _input?: string): Promise { try { // Handle no arguments or help if (args.length === 0 || args[0] === '--help' || args[0] === '-h') { @@ -120,8 +118,9 @@ export class GitCommand implements ShellCommand { return createErrorResult(`git: '${subcommandName}' is not a git command. See 'git --help'.`); } - // Execute the subcommand - return await subcommand.execute(subcommandArgs); + // Execute the subcommand, passing the current working directory + // This ensures git commands use the correct directory after 'cd' commands + return await subcommand.execute(subcommandArgs, cwd); } catch (error) { return createErrorResult(`git: ${error instanceof Error ? error.message : 'Unknown error'}`); diff --git a/src/lib/commands/git/add.test.ts b/src/lib/commands/git/add.test.ts index 61df2b44..05aedc98 100644 --- a/src/lib/commands/git/add.test.ts +++ b/src/lib/commands/git/add.test.ts @@ -57,7 +57,6 @@ describe('GitAddCommand', () => { addCommand = new GitAddCommand({ git: mockGit, fs: mockFS, - pwd: testCwd, }); }); @@ -71,14 +70,14 @@ describe('GitAddCommand', () => { // Mock stat to throw error for .git directory vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT')); - const result = await addCommand.execute(['file.txt']); + const result = await addCommand.execute(['file.txt'], testCwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('fatal: not a git repository'); }); it('should return error when no files specified', async () => { - const result = await addCommand.execute([]); + const result = await addCommand.execute([], testCwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('Nothing specified, nothing added'); @@ -95,7 +94,7 @@ describe('GitAddCommand', () => { ['staged.txt', 1, 2, 2], // Already staged file ]); - const result = await addCommand.execute(['--all']); + const result = await addCommand.execute(['--all'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); // Git add is silent on success @@ -118,7 +117,7 @@ describe('GitAddCommand', () => { ['deleted.txt', 1, 0, 1], // Deleted file (not staged) ]); - const result = await addCommand.execute(['--all']); + const result = await addCommand.execute(['--all'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); @@ -132,7 +131,7 @@ describe('GitAddCommand', () => { }); it('should add specific file', async () => { - const result = await addCommand.execute(['file.txt']); + const result = await addCommand.execute(['file.txt'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); @@ -151,7 +150,7 @@ describe('GitAddCommand', () => { ['deleted.txt', 1, 0, 1], // Deleted file ]); - const result = await addCommand.execute(['.']); + const result = await addCommand.execute(['.'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); @@ -174,7 +173,7 @@ describe('GitAddCommand', () => { }); it('should reject absolute paths', async () => { - const result = await addCommand.execute(['/absolute/path/file.txt']); + const result = await addCommand.execute(['/absolute/path/file.txt'], testCwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('absolute paths are not supported'); @@ -205,7 +204,7 @@ describe('GitAddCommand', () => { // Mock git.remove to also throw error (file doesn't exist in git either) vi.mocked(mockGit.remove).mockRejectedValueOnce(new Error('File not found')); - const result = await addCommand.execute(['nonexistent.txt']); + const result = await addCommand.execute(['nonexistent.txt'], testCwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('pathspec \'nonexistent.txt\' did not match any files'); @@ -216,7 +215,7 @@ describe('GitAddCommand', () => { ['modified.txt', 1, 2, 1], // Modified file ]); - const result = await addCommand.execute(['-A']); + const result = await addCommand.execute(['-A'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); @@ -233,7 +232,7 @@ describe('GitAddCommand', () => { ['modified.txt', 1, 2, 1], // Modified file ]); - const result = await addCommand.execute(['--all', 'specific.txt']); + const result = await addCommand.execute(['--all', 'specific.txt'], testCwd); expect(result.exitCode).toBe(0); @@ -242,7 +241,7 @@ describe('GitAddCommand', () => { }); it('should handle double dash separator', async () => { - const result = await addCommand.execute(['--', 'file.txt']); + const result = await addCommand.execute(['--', 'file.txt'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); @@ -267,7 +266,7 @@ describe('GitAddCommand', () => { return Promise.resolve(); }); - const result = await addCommand.execute(['--all']); + const result = await addCommand.execute(['--all'], testCwd); expect(result.exitCode).toBe(0); // Should still succeed overall expect(mockGit.add).toHaveBeenCalledTimes(2); diff --git a/src/lib/commands/git/add.ts b/src/lib/commands/git/add.ts index 5829bf4d..f1406bfb 100644 --- a/src/lib/commands/git/add.ts +++ b/src/lib/commands/git/add.ts @@ -12,19 +12,17 @@ export class GitAddCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -33,12 +31,12 @@ export class GitAddCommand implements GitSubcommand { if (options.all) { // Add all files (git add -A) - return await this.addAllFiles(); + return await this.addAllFiles(cwd); } else if (paths.length === 0) { return createErrorResult('Nothing specified, nothing added.\nMaybe you wanted to say \'git add .\'?'); } else { // Add specific files - return await this.addSpecificFiles(paths); + return await this.addSpecificFiles(paths, cwd); } } catch (error) { @@ -70,11 +68,11 @@ export class GitAddCommand implements GitSubcommand { return { options, paths }; } - private async addAllFiles(): Promise { + private async addAllFiles(cwd: string): Promise { try { // Get status to find all changed files const statusMatrix = await this.git.statusMatrix({ - dir: this.pwd, + dir: cwd, }); for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { @@ -82,15 +80,13 @@ export class GitAddCommand implements GitSubcommand { if (workdirStatus === 0 && headStatus === 1) { // File was deleted in working directory await this.git.remove({ - - dir: this.pwd, + dir: cwd, filepath, }); } else if (workdirStatus === 2 && stageStatus !== 2) { // File exists and has changes that aren't staged yet await this.git.add({ - - dir: this.pwd, + dir: cwd, filepath, }); } @@ -108,7 +104,7 @@ export class GitAddCommand implements GitSubcommand { } } - private async addSpecificFiles(paths: string[]): Promise { + private async addSpecificFiles(paths: string[], cwd: string): Promise { const addedFiles: string[] = []; const errors: string[] = []; @@ -117,8 +113,7 @@ export class GitAddCommand implements GitSubcommand { if (path === '.') { // Add current directory (all files in it) const statusMatrix = await this.git.statusMatrix({ - - dir: this.pwd, + dir: cwd, }); for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { @@ -126,16 +121,14 @@ export class GitAddCommand implements GitSubcommand { if (workdirStatus === 0 && headStatus === 1) { // File was deleted in working directory await this.git.remove({ - - dir: this.pwd, + dir: cwd, filepath, }); addedFiles.push(filepath); } else if (workdirStatus === 2 && stageStatus !== 2) { // File exists and has changes that aren't staged yet await this.git.add({ - - dir: this.pwd, + dir: cwd, filepath, }); addedFiles.push(filepath); @@ -151,7 +144,7 @@ export class GitAddCommand implements GitSubcommand { continue; } - const absolutePath = join(this.pwd, path); + const absolutePath = join(cwd, path); // Check if file/directory exists try { @@ -159,12 +152,11 @@ export class GitAddCommand implements GitSubcommand { if (stats.isDirectory()) { // Add all files in directory - await this.addDirectory(path, addedFiles); + await this.addDirectory(path, addedFiles, cwd); } else { // Add single file await this.git.add({ - - dir: this.pwd, + dir: cwd, filepath: path, }); addedFiles.push(path); @@ -173,8 +165,7 @@ export class GitAddCommand implements GitSubcommand { // Check if it's a deleted file try { await this.git.remove({ - - dir: this.pwd, + dir: cwd, filepath: path, }); addedFiles.push(path); @@ -196,8 +187,8 @@ export class GitAddCommand implements GitSubcommand { return createSuccessResult(''); } - private async addDirectory(dirPath: string, addedFiles: string[]): Promise { - const absolutePath = join(this.pwd, dirPath); + private async addDirectory(dirPath: string, addedFiles: string[], cwd: string): Promise { + const absolutePath = join(cwd, dirPath); const entries = await this.fs.readdir(absolutePath, { withFileTypes: true }); for (const entry of entries) { @@ -208,12 +199,11 @@ export class GitAddCommand implements GitSubcommand { const entryPath = join(dirPath, entry.name); if (entry.isDirectory()) { - await this.addDirectory(entryPath, addedFiles); + await this.addDirectory(entryPath, addedFiles, cwd); } else { try { await this.git.add({ - - dir: this.pwd, + dir: cwd, filepath: entryPath, }); addedFiles.push(entryPath); @@ -223,4 +213,4 @@ export class GitAddCommand implements GitSubcommand { } } } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/branch.ts b/src/lib/commands/git/branch.ts index db7cfa32..5fc12dee 100644 --- a/src/lib/commands/git/branch.ts +++ b/src/lib/commands/git/branch.ts @@ -11,19 +11,17 @@ export class GitBranchCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -32,13 +30,13 @@ export class GitBranchCommand implements GitSubcommand { switch (action) { case 'list': - return await this.listBranches(); + return await this.listBranches(cwd); case 'create': - return await this.createBranch(branchName!); + return await this.createBranch(branchName!, cwd); case 'delete': - return await this.deleteBranch(branchName!, options.force); + return await this.deleteBranch(branchName!, options.force, cwd); default: - return await this.listBranches(); + return await this.listBranches(cwd); } } catch (error) { @@ -83,10 +81,10 @@ export class GitBranchCommand implements GitSubcommand { return { action, branchName, options }; } - private async listBranches(): Promise { + private async listBranches(cwd: string): Promise { try { const branches = await this.git.listBranches({ - dir: this.pwd, + dir: cwd, }); if (branches.length === 0) { @@ -98,7 +96,7 @@ export class GitBranchCommand implements GitSubcommand { try { currentBranch = await this.git.currentBranch({ - dir: this.pwd, + dir: cwd, }) || null; } catch { // Might be in detached HEAD state @@ -120,11 +118,11 @@ export class GitBranchCommand implements GitSubcommand { } } - private async createBranch(branchName: string): Promise { + private async createBranch(branchName: string, cwd: string): Promise { try { // Check if branch already exists const branches = await this.git.listBranches({ - dir: this.pwd, + dir: cwd, }); if (branches.includes(branchName)) { @@ -136,7 +134,7 @@ export class GitBranchCommand implements GitSubcommand { try { currentRef = await this.git.resolveRef({ - dir: this.pwd, + dir: cwd, ref: 'HEAD', }); } catch { @@ -145,7 +143,7 @@ export class GitBranchCommand implements GitSubcommand { // Create the new branch await this.git.branch({ - dir: this.pwd, + dir: cwd, ref: branchName, object: currentRef, }); @@ -157,11 +155,11 @@ export class GitBranchCommand implements GitSubcommand { } } - private async deleteBranch(branchName: string, force: boolean): Promise { + private async deleteBranch(branchName: string, force: boolean, cwd: string): Promise { try { // Check if branch exists const branches = await this.git.listBranches({ - dir: this.pwd, + dir: cwd, }); if (!branches.includes(branchName)) { @@ -173,19 +171,19 @@ export class GitBranchCommand implements GitSubcommand { try { currentBranch = await this.git.currentBranch({ - dir: this.pwd, + dir: cwd, }) || null; } catch { // Continue } if (currentBranch === branchName) { - return createErrorResult(`error: Cannot delete branch '${branchName}' checked out at '${this.pwd}'`); + return createErrorResult(`error: Cannot delete branch '${branchName}' checked out at '${cwd}'`); } // Delete the branch await this.git.deleteBranch({ - dir: this.pwd, + dir: cwd, ref: branchName, }); @@ -198,4 +196,4 @@ export class GitBranchCommand implements GitSubcommand { return createErrorResult(`Failed to delete branch: ${error instanceof Error ? error.message : 'Unknown error'}`); } } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/checkout.ts b/src/lib/commands/git/checkout.ts index ace96b39..5a9ac187 100644 --- a/src/lib/commands/git/checkout.ts +++ b/src/lib/commands/git/checkout.ts @@ -11,19 +11,17 @@ export class GitCheckoutCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -32,11 +30,11 @@ export class GitCheckoutCommand implements GitSubcommand { switch (action) { case 'switch': - return await this.switchBranch(target!); + return await this.switchBranch(target!, cwd); case 'create': - return await this.createAndSwitchBranch(target!); + return await this.createAndSwitchBranch(target!, cwd); case 'restore': - return await this.restoreFiles(target!); + return await this.restoreFiles(target!, cwd); default: return createErrorResult('error: pathspec did not match any file(s) known to git'); } @@ -82,11 +80,11 @@ export class GitCheckoutCommand implements GitSubcommand { return { action, target, options }; } - private async switchBranch(branchName: string): Promise { + private async switchBranch(branchName: string, cwd: string): Promise { try { // Check if branch exists const branches = await this.git.listBranches({ - dir: this.pwd, + dir: cwd, }); if (!branches.includes(branchName)) { @@ -97,8 +95,7 @@ export class GitCheckoutCommand implements GitSubcommand { let currentBranch: string | null = null; try { currentBranch = await this.git.currentBranch({ - - dir: this.pwd, + dir: cwd, }) || null; } catch { // Continue @@ -110,7 +107,7 @@ export class GitCheckoutCommand implements GitSubcommand { // Check for uncommitted changes const statusMatrix = await this.git.statusMatrix({ - dir: this.pwd, + dir: cwd, }); const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => { @@ -123,7 +120,7 @@ export class GitCheckoutCommand implements GitSubcommand { // Switch to the branch await this.git.checkout({ - dir: this.pwd, + dir: cwd, ref: branchName, force: true, }); @@ -135,11 +132,11 @@ export class GitCheckoutCommand implements GitSubcommand { } } - private async createAndSwitchBranch(branchName: string): Promise { + private async createAndSwitchBranch(branchName: string, cwd: string): Promise { try { // Check if branch already exists const branches = await this.git.listBranches({ - dir: this.pwd, + dir: cwd, }); if (branches.includes(branchName)) { @@ -150,8 +147,7 @@ export class GitCheckoutCommand implements GitSubcommand { let currentRef: string; try { currentRef = await this.git.resolveRef({ - - dir: this.pwd, + dir: cwd, ref: 'HEAD', }); } catch { @@ -160,14 +156,14 @@ export class GitCheckoutCommand implements GitSubcommand { // Create the branch await this.git.branch({ - dir: this.pwd, + dir: cwd, ref: branchName, object: currentRef, }); // Switch to the new branch await this.git.checkout({ - dir: this.pwd, + dir: cwd, ref: branchName, force: true, }); @@ -179,7 +175,7 @@ export class GitCheckoutCommand implements GitSubcommand { } } - private async restoreFiles(filePath: string): Promise { + private async restoreFiles(filePath: string, cwd: string): Promise { try { // This is a simplified implementation // In a full git implementation, this would restore files from the index or HEAD @@ -187,8 +183,7 @@ export class GitCheckoutCommand implements GitSubcommand { // Get the file from HEAD try { await this.git.checkout({ - - dir: this.pwd, + dir: cwd, ref: 'HEAD', filepaths: [filePath], }); @@ -205,4 +200,4 @@ export class GitCheckoutCommand implements GitSubcommand { return createErrorResult(`Failed to restore file: ${error instanceof Error ? error.message : 'Unknown error'}`); } } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/clone.ts b/src/lib/commands/git/clone.ts index 3996b82d..93cdef1e 100644 --- a/src/lib/commands/git/clone.ts +++ b/src/lib/commands/git/clone.ts @@ -12,15 +12,13 @@ export class GitCloneCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { const { options, repository, directory } = this.parseArgs(args); @@ -37,7 +35,7 @@ export class GitCloneCommand implements GitSubcommand { targetDir = repoName.replace(/\.git$/, ''); // Remove .git suffix if present } - const targetPath = `${this.pwd}/${targetDir}`; + const targetPath = `${cwd}/${targetDir}`; // Check if target directory already exists try { @@ -117,4 +115,4 @@ export class GitCloneCommand implements GitSubcommand { return { options, repository, directory }; } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/commit.test.ts b/src/lib/commands/git/commit.test.ts index 9f2d941a..fe12657d 100644 --- a/src/lib/commands/git/commit.test.ts +++ b/src/lib/commands/git/commit.test.ts @@ -75,12 +75,11 @@ describe('GitCommitCommand', () => { commitCommand = new GitCommitCommand({ git: mockGit as Git, fs: mockFS as JSRuntimeFS, - pwd: mockPwd, }); }); it('should commit with a message', async () => { - const result = await commitCommand.execute(['-m', 'Test commit']); + const result = await commitCommand.execute(['-m', 'Test commit'], mockPwd); expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({ dir: mockPwd, @@ -92,7 +91,7 @@ describe('GitCommitCommand', () => { }); it('should fail without a message', async () => { - const result = await commitCommand.execute([]); + const result = await commitCommand.execute([], mockPwd); expect(mockGit.commit).not.toHaveBeenCalled(); @@ -101,7 +100,7 @@ describe('GitCommitCommand', () => { }); it('should handle --amend flag', async () => { - const result = await commitCommand.execute(['--amend', '-m', 'Amended commit']); + const result = await commitCommand.execute(['--amend', '-m', 'Amended commit'], mockPwd); expect(mockGit.log).toHaveBeenCalledWith({ dir: mockPwd, @@ -119,7 +118,7 @@ describe('GitCommitCommand', () => { }); it('should handle --amend flag without message', async () => { - const result = await commitCommand.execute(['--amend']); + const result = await commitCommand.execute(['--amend'], mockPwd); expect(mockGit.log).toHaveBeenCalledWith({ dir: mockPwd, @@ -135,7 +134,7 @@ describe('GitCommitCommand', () => { }); it('should handle -a flag to stage all tracked modified files', async () => { - const result = await commitCommand.execute(['-a', '-m', 'Commit with auto-stage']); + const result = await commitCommand.execute(['-a', '-m', 'Commit with auto-stage'], mockPwd); // Should call add for the modified tracked file expect(mockGit.add).toHaveBeenCalledWith({ @@ -165,7 +164,7 @@ describe('GitCommitCommand', () => { }); it('should handle -am flag for combined auto-stage and message', async () => { - const result = await commitCommand.execute(['-am', 'Combined flag commit']); + const result = await commitCommand.execute(['-am', 'Combined flag commit'], mockPwd); // Should call add for the modified tracked file expect(mockGit.add).toHaveBeenCalledWith({ @@ -192,7 +191,7 @@ describe('GitCommitCommand', () => { // Mock empty status mockGit.statusMatrix = vi.fn().mockResolvedValue([]); - const result = await commitCommand.execute(['--allow-empty', '-m', 'Empty commit']); + const result = await commitCommand.execute(['--allow-empty', '-m', 'Empty commit'], mockPwd); expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({ dir: mockPwd, @@ -209,7 +208,7 @@ describe('GitCommitCommand', () => { ['file1.txt', 1, 2, 1], // modified in workdir only ]); - const result = await commitCommand.execute(['-m', 'Should fail']); + const result = await commitCommand.execute(['-m', 'Should fail'], mockPwd); expect(mockGit.commit).not.toHaveBeenCalled(); @@ -220,7 +219,7 @@ describe('GitCommitCommand', () => { it('should handle not being in a git repository', async () => { mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory')); - const result = await commitCommand.execute(['-m', 'Test commit']); + const result = await commitCommand.execute(['-m', 'Test commit'], mockPwd); expect(mockGit.commit).not.toHaveBeenCalled(); diff --git a/src/lib/commands/git/commit.ts b/src/lib/commands/git/commit.ts index 9df27488..30650200 100644 --- a/src/lib/commands/git/commit.ts +++ b/src/lib/commands/git/commit.ts @@ -11,19 +11,17 @@ export class GitCommitCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -36,12 +34,12 @@ export class GitCommitCommand implements GitSubcommand { // If -a flag is provided, stage all tracked files with modifications if (options.addAll) { - await this.stageTrackedChanges(); + await this.stageTrackedChanges(cwd); } // Get current status const statusMatrix = await this.git.statusMatrix({ - dir: this.pwd, + dir: cwd, }); // Check for staged changes @@ -58,8 +56,7 @@ export class GitCommitCommand implements GitSubcommand { // Get the last commit message if amending try { const commits = await this.git.log({ - - dir: this.pwd, + dir: cwd, depth: 1, }); if (commits.length > 0 && !message) { @@ -77,8 +74,7 @@ export class GitCommitCommand implements GitSubcommand { let currentBranch = 'main'; try { currentBranch = await this.git.currentBranch({ - - dir: this.pwd, + dir: cwd, }) || 'main'; } catch { // Use default @@ -90,7 +86,7 @@ export class GitCommitCommand implements GitSubcommand { message: string; parent?: string[]; } = { - dir: this.pwd, + dir: cwd, message: commitMessage || 'Empty commit', }; @@ -98,7 +94,7 @@ export class GitCommitCommand implements GitSubcommand { // For amend, we need to reset to the parent of the current commit try { const commits = await this.git.log({ - dir: this.pwd, + dir: cwd, depth: 2, }); if (commits.length > 1) { @@ -151,11 +147,11 @@ export class GitCommitCommand implements GitSubcommand { * Stage all tracked files with modifications * This is used when the -a flag is provided */ - private async stageTrackedChanges(): Promise { + private async stageTrackedChanges(cwd: string): Promise { try { // Get the status matrix const statusMatrix = await this.git.statusMatrix({ - dir: this.pwd, + dir: cwd, }); // Process each file based on its status @@ -165,13 +161,13 @@ export class GitCommitCommand implements GitSubcommand { if (workdirStatus === 0) { // File was deleted, use remove await this.git.remove({ - dir: this.pwd, + dir: cwd, filepath, }); } else { // File was modified, use add await this.git.add({ - dir: this.pwd, + dir: cwd, filepath, }); } @@ -218,4 +214,4 @@ export class GitCommitCommand implements GitSubcommand { return { options, message }; } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/config.ts b/src/lib/commands/git/config.ts index 9667cbc3..ba919dfc 100644 --- a/src/lib/commands/git/config.ts +++ b/src/lib/commands/git/config.ts @@ -11,22 +11,20 @@ export class GitConfigCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { const { action, key, value, options } = this.parseArgs(args); // Check if we're in a git repository (unless --global is used) if (!options.global) { try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -34,11 +32,11 @@ export class GitConfigCommand implements GitSubcommand { switch (action) { case 'list': - return await this.listConfig(options.global); + return await this.listConfig(options.global, cwd); case 'get': - return await this.getConfig(key!, options.global); + return await this.getConfig(key!, options.global, cwd); case 'set': - return await this.setConfig(key!, value!, options.global); + return await this.setConfig(key!, value!, options.global, cwd); default: return createErrorResult('usage: git config [--global] [] | git config [--global] --list'); } @@ -80,7 +78,7 @@ export class GitConfigCommand implements GitSubcommand { return { action, key, value, options }; } - private async listConfig(global: boolean): Promise { + private async listConfig(global: boolean, cwd: string): Promise { try { // For simplicity, we'll only show the most common config values // isomorphic-git doesn't have a direct way to list all config @@ -97,8 +95,7 @@ export class GitConfigCommand implements GitSubcommand { for (const key of commonKeys) { try { const value = await this.git.getConfig({ - - dir: global ? undefined : this.pwd, + dir: global ? undefined : cwd, path: key, }); if (value !== undefined) { @@ -116,11 +113,10 @@ export class GitConfigCommand implements GitSubcommand { } } - private async getConfig(key: string, global: boolean): Promise { + private async getConfig(key: string, global: boolean, cwd: string): Promise { try { const value = await this.git.getConfig({ - - dir: global ? undefined : this.pwd, + dir: global ? undefined : cwd, path: key, }); @@ -135,10 +131,10 @@ export class GitConfigCommand implements GitSubcommand { } } - private async setConfig(key: string, value: string, global: boolean): Promise { + private async setConfig(key: string, value: string, global: boolean, cwd: string): Promise { try { await this.git.setConfig({ - dir: global ? undefined : this.pwd, + dir: global ? undefined : cwd, path: key, value: value, }); @@ -149,4 +145,4 @@ export class GitConfigCommand implements GitSubcommand { return createErrorResult(`Failed to set config: ${error instanceof Error ? error.message : 'Unknown error'}`); } } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/diff.test.ts b/src/lib/commands/git/diff.test.ts index 0b721ab6..165dea2a 100644 --- a/src/lib/commands/git/diff.test.ts +++ b/src/lib/commands/git/diff.test.ts @@ -50,7 +50,6 @@ const mockFS = { const mockOptions: GitSubcommandOptions = { git: mockGit, fs: mockFS, - pwd: '/test/repo', }; describe('GitDiffCommand', () => { @@ -106,14 +105,14 @@ describe('GitDiffCommand', () => { } as unknown as JSRuntimeFS, }); - const result = await commandWithoutGit.execute([]); + const result = await commandWithoutGit.execute([], '/test/repo'); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('fatal: not a git repository'); }); it('should show working directory diff for modified files', async () => { - const result = await command.execute([]); + const result = await command.execute([], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt'); @@ -125,7 +124,7 @@ describe('GitDiffCommand', () => { }); it('should NOT show untracked files in diff', async () => { - const result = await command.execute([]); + const result = await command.execute([], '/test/repo'); expect(result.exitCode).toBe(0); // Untracked files should not appear in git diff output @@ -135,7 +134,7 @@ describe('GitDiffCommand', () => { }); it('should show deleted files in diff', async () => { - const result = await command.execute([]); + const result = await command.execute([], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('diff --git a/deleted.txt b/deleted.txt'); @@ -146,7 +145,7 @@ describe('GitDiffCommand', () => { }); it('should show staged diff with --cached option', async () => { - const result = await command.execute(['--cached']); + const result = await command.execute(['--cached'], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('diff --git a/staged.txt b/staged.txt'); @@ -166,7 +165,7 @@ describe('GitDiffCommand', () => { } as unknown as Git, }); - const result = await commandWithStagedNew.execute(['--cached']); + const result = await commandWithStagedNew.execute(['--cached'], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('diff --git a/new-staged.txt b/new-staged.txt'); @@ -184,14 +183,14 @@ describe('GitDiffCommand', () => { } as unknown as Git, }); - const result = await commandWithNoChanges.execute([]); + const result = await commandWithNoChanges.execute([], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); }); it('should filter by path when specified', async () => { - const result = await command.execute(['--', 'modified.txt']); + const result = await command.execute(['--', 'modified.txt'], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt'); diff --git a/src/lib/commands/git/diff.ts b/src/lib/commands/git/diff.ts index 0e7bd61e..b3866ca7 100644 --- a/src/lib/commands/git/diff.ts +++ b/src/lib/commands/git/diff.ts @@ -12,19 +12,17 @@ export class GitDiffCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -33,16 +31,16 @@ export class GitDiffCommand implements GitSubcommand { if (options.cached || options.staged) { // Show staged changes (index vs HEAD) - return await this.showStagedDiff(paths); + return await this.showStagedDiff(paths, cwd); } else if (commits.length === 0) { // Show working directory changes vs index - return await this.showWorkingDirectoryDiff(paths); + return await this.showWorkingDirectoryDiff(paths, cwd); } else if (commits.length === 1) { // Show changes between commit and working directory - return await this.showCommitDiff(commits[0], paths); + return await this.showCommitDiff(commits[0], paths, cwd); } else if (commits.length === 2) { // Show changes between two commits - return await this.showCommitRangeDiff(commits[0], commits[1], paths); + return await this.showCommitRangeDiff(commits[0], commits[1], paths, cwd); } else { return createErrorResult('usage: git diff [] [] [-- ...]'); } @@ -82,11 +80,11 @@ export class GitDiffCommand implements GitSubcommand { return { commits, paths, options }; } - private async showWorkingDirectoryDiff(paths: string[]): Promise { + private async showWorkingDirectoryDiff(paths: string[], cwd: string): Promise { try { // Get status to find changed files const statusMatrix = await this.git.statusMatrix({ - dir: this.pwd, + dir: cwd, }); // Filter for files with working directory changes @@ -120,7 +118,7 @@ export class GitDiffCommand implements GitSubcommand { // For files in the index, read from HEAD as the baseline // This represents the last committed version for comparison const headBlob = await this.git.readBlob({ - dir: this.pwd, + dir: cwd, oid: 'HEAD', filepath, }); @@ -135,7 +133,7 @@ export class GitDiffCommand implements GitSubcommand { let workdirContent = ''; if (workdirStatus === 2) { try { - workdirContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8'); + workdirContent = await this.fs.readFile(`${cwd}/${filepath}`, 'utf8'); } catch { // File might be deleted workdirContent = ''; @@ -156,12 +154,12 @@ export class GitDiffCommand implements GitSubcommand { if (workdirStatus === 0 && (stageStatus === 1 || stageStatus === 2)) { // Deleted file diffLines.push('deleted file mode 100644'); - diffLines.push(`index ${this.getShortHash(indexContent)}..0000000`); + diffLines.push(`index ${this.getShortHash(indexContent, cwd)}..0000000`); diffLines.push(`--- a/${filepath}`); diffLines.push('+++ /dev/null'); } else { // Modified file - diffLines.push(`index ${this.getShortHash(indexContent)}..${this.getShortHash(workdirContent)} 100644`); + diffLines.push(`index ${this.getShortHash(indexContent, cwd)}..${this.getShortHash(workdirContent, cwd)} 100644`); diffLines.push(`--- a/${filepath}`); diffLines.push(`+++ b/${filepath}`); } @@ -211,12 +209,11 @@ export class GitDiffCommand implements GitSubcommand { } } - private async showCommitDiff(commit: string, _paths: string[]): Promise { + private async showCommitDiff(commit: string, _paths: string[], cwd: string): Promise { try { // For simplicity, show the commit message and changed files const commits = await this.git.log({ - - dir: this.pwd, + dir: cwd, depth: 1, ref: commit, }); @@ -245,16 +242,16 @@ export class GitDiffCommand implements GitSubcommand { } } - private async showCommitRangeDiff(_commit1: string, _commit2: string, _paths: string[]): Promise { + private async showCommitRangeDiff(_commit1: string, _commit2: string, _paths: string[], _cwd: string): Promise { // This would require complex implementation to compare two commits return createErrorResult('Commit range diff is not implemented in this git command'); } - private async showStagedDiff(paths: string[]): Promise { + private async showStagedDiff(paths: string[], cwd: string): Promise { try { // Get status to find staged files const statusMatrix = await this.git.statusMatrix({ - dir: this.pwd, + dir: cwd, }); // Filter for files with staged changes (index differs from HEAD) @@ -282,7 +279,7 @@ export class GitDiffCommand implements GitSubcommand { if (headStatus === 1) { try { const headBlob = await this.git.readBlob({ - dir: this.pwd, + dir: cwd, oid: 'HEAD', filepath, }); @@ -296,7 +293,7 @@ export class GitDiffCommand implements GitSubcommand { let stagedContent = ''; if (stageStatus === 1 || stageStatus === 2) { try { - stagedContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8'); + stagedContent = await this.fs.readFile(`${cwd}/${filepath}`, 'utf8'); } catch { stagedContent = ''; } @@ -308,18 +305,18 @@ export class GitDiffCommand implements GitSubcommand { if (headStatus === 0 && stageStatus === 2) { // New file staged diffLines.push('new file mode 100644'); - diffLines.push(`index 0000000..${this.getShortHash(stagedContent)}`); + diffLines.push(`index 0000000..${this.getShortHash(stagedContent, cwd)}`); diffLines.push('--- /dev/null'); diffLines.push(`+++ b/${filepath}`); } else if (headStatus === 1 && stageStatus === 0) { // File deleted from stage diffLines.push('deleted file mode 100644'); - diffLines.push(`index ${this.getShortHash(headContent)}..0000000`); + diffLines.push(`index ${this.getShortHash(headContent, cwd)}..0000000`); diffLines.push(`--- a/${filepath}`); diffLines.push('+++ /dev/null'); } else { // Modified file - diffLines.push(`index ${this.getShortHash(headContent)}..${this.getShortHash(stagedContent)} 100644`); + diffLines.push(`index ${this.getShortHash(headContent, cwd)}..${this.getShortHash(stagedContent, cwd)} 100644`); diffLines.push(`--- a/${filepath}`); diffLines.push(`+++ b/${filepath}`); } @@ -367,7 +364,7 @@ export class GitDiffCommand implements GitSubcommand { } } - private getShortHash(content: string): string { + private getShortHash(content: string, _cwd: string): string { // Simple hash for demo purposes - not a real git hash let hash = 0; for (let i = 0; i < content.length; i++) { @@ -377,4 +374,4 @@ export class GitDiffCommand implements GitSubcommand { } return Math.abs(hash).toString(16).substring(0, 7).padStart(7, '0'); } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/fetch.test.ts b/src/lib/commands/git/fetch.test.ts index b9caa07f..f278cd13 100644 --- a/src/lib/commands/git/fetch.test.ts +++ b/src/lib/commands/git/fetch.test.ts @@ -26,7 +26,6 @@ const mockFS = { const mockOptions: GitSubcommandOptions = { git: mockGit, fs: mockFS, - pwd: '/test/repo', }; describe('GitFetchCommand', () => { @@ -144,21 +143,21 @@ describe('GitFetchCommand', () => { } as unknown as JSRuntimeFS, }); - const result = await commandWithoutGit.execute([]); + const result = await commandWithoutGit.execute([], '/test/repo'); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('fatal: not a git repository'); }); it('should fail when remote does not exist', async () => { - const result = await command.execute(['nonexistent']); + const result = await command.execute(['nonexistent'], '/test/repo'); expect(result.exitCode).toBe(1); expect(result.stderr).toContain("fatal: 'nonexistent' does not appear to be a git repository"); }); it('should fetch from default remote successfully', async () => { - const result = await command.execute([]); + const result = await command.execute([], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('From https://github.com/user/repo.git'); @@ -166,7 +165,7 @@ describe('GitFetchCommand', () => { }); it('should fetch from specific remote successfully', async () => { - const result = await command.execute(['upstream']); + const result = await command.execute(['upstream'], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('From https://github.com/upstream/repo.git'); @@ -174,7 +173,7 @@ describe('GitFetchCommand', () => { }); it('should fetch specific refs successfully', async () => { - const result = await command.execute(['origin', 'main']); + const result = await command.execute(['origin', 'main'], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('From https://github.com/user/repo.git'); @@ -182,7 +181,7 @@ describe('GitFetchCommand', () => { }); it('should fetch multiple specific refs successfully', async () => { - const result = await command.execute(['origin', 'main', 'develop']); + const result = await command.execute(['origin', 'main', 'develop'], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('From https://github.com/user/repo.git'); @@ -201,7 +200,7 @@ describe('GitFetchCommand', () => { } as unknown as Git, }); - const result = await commandWithAuthError.execute([]); + const result = await commandWithAuthError.execute([], '/test/repo'); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('fatal: Authentication failed'); @@ -218,7 +217,7 @@ describe('GitFetchCommand', () => { } as unknown as Git, }); - const result = await commandWithNetworkError.execute([]); + const result = await commandWithNetworkError.execute([], '/test/repo'); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('fatal: unable to access remote repository'); diff --git a/src/lib/commands/git/fetch.ts b/src/lib/commands/git/fetch.ts index 5428bf13..90dcfc34 100644 --- a/src/lib/commands/git/fetch.ts +++ b/src/lib/commands/git/fetch.ts @@ -11,19 +11,17 @@ export class GitFetchCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -34,7 +32,7 @@ export class GitFetchCommand implements GitSubcommand { let remoteUrl: string; try { const remotes = await this.git.listRemotes({ - dir: this.pwd, + dir: cwd, }); const targetRemote = remotes.find(r => r.remote === remote); @@ -52,7 +50,7 @@ export class GitFetchCommand implements GitSubcommand { // Fetch specific refs for (const ref of refs) { await this.git.fetch({ - dir: this.pwd, + dir: cwd, remote: remote, ref: ref, }); @@ -60,7 +58,7 @@ export class GitFetchCommand implements GitSubcommand { } else { // Fetch all refs (default behavior) await this.git.fetch({ - dir: this.pwd, + dir: cwd, remote: remote, }); } @@ -74,7 +72,7 @@ export class GitFetchCommand implements GitSubcommand { for (const ref of refs) { try { await this.git.resolveRef({ - dir: this.pwd, + dir: cwd, ref: `refs/remotes/${remote}/${ref}`, }); lines.push(` * branch ${ref} -> ${remote}/${ref}`); @@ -170,4 +168,4 @@ export class GitFetchCommand implements GitSubcommand { return { remote, refs, options }; } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/init.ts b/src/lib/commands/git/init.ts index 585b247e..e94b4b72 100644 --- a/src/lib/commands/git/init.ts +++ b/src/lib/commands/git/init.ts @@ -11,19 +11,17 @@ export class GitInitCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Parse arguments const { options, directory } = this.parseArgs(args); - const targetDir = directory || this.pwd; + const targetDir = directory || cwd; // Check if directory exists, create if needed if (directory) { @@ -88,4 +86,4 @@ export class GitInitCommand implements GitSubcommand { return { options, directory }; } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/log.ts b/src/lib/commands/git/log.ts index 2d16d055..baa62045 100644 --- a/src/lib/commands/git/log.ts +++ b/src/lib/commands/git/log.ts @@ -11,19 +11,17 @@ export class GitLogCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -32,8 +30,7 @@ export class GitLogCommand implements GitSubcommand { try { const commits = await this.git.log({ - - dir: this.pwd, + dir: cwd, depth: limit, }); @@ -42,9 +39,9 @@ export class GitLogCommand implements GitSubcommand { } if (options.oneline) { - return this.formatOnelineLog(commits); + return this.formatOnelineLog(commits, cwd); } else { - return this.formatFullLog(commits, options.graph); + return this.formatFullLog(commits, options.graph, cwd); } } catch (error) { @@ -103,7 +100,7 @@ export class GitLogCommand implements GitSubcommand { return { options, limit }; } - private formatOnelineLog(commits: Array<{ oid: string; commit: { message: string } }>): ShellCommandResult { + private formatOnelineLog(commits: Array<{ oid: string; commit: { message: string } }>, _cwd: string): ShellCommandResult { const lines: string[] = []; for (const commit of commits) { @@ -115,7 +112,7 @@ export class GitLogCommand implements GitSubcommand { return createSuccessResult(lines.join('\n') + '\n'); } - private formatFullLog(commits: Array<{ oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number } } }>, showGraph: boolean): ShellCommandResult { + private formatFullLog(commits: Array<{ oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number } } }>, showGraph: boolean, _cwd: string): ShellCommandResult { const lines: string[] = []; for (let i = 0; i < commits.length; i++) { diff --git a/src/lib/commands/git/pull.test.ts b/src/lib/commands/git/pull.test.ts index 1e47b6e7..ba60ccc8 100644 --- a/src/lib/commands/git/pull.test.ts +++ b/src/lib/commands/git/pull.test.ts @@ -21,7 +21,6 @@ const mockFS = { const mockOptions: GitSubcommandOptions = { git: mockGit, fs: mockFS, - pwd: '/test/repo', }; describe('GitPullCommand', () => { @@ -107,10 +106,9 @@ describe('GitPullCommand', () => { const commandWithChanges = new GitPullCommand({ git: mockGitWithChanges, fs: mockFSWithGit, - pwd: '/test/repo', }); - const result = await commandWithChanges.execute(['origin', 'main']); + const result = await commandWithChanges.execute(['origin', 'main'], '/test/repo'); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('error: Your local changes to the following files would be overwritten by merge:'); diff --git a/src/lib/commands/git/pull.ts b/src/lib/commands/git/pull.ts index 0bf813aa..1b8480d1 100644 --- a/src/lib/commands/git/pull.ts +++ b/src/lib/commands/git/pull.ts @@ -11,19 +11,17 @@ export class GitPullCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -35,8 +33,7 @@ export class GitPullCommand implements GitSubcommand { let currentBranch: string | null = null; try { currentBranch = await this.git.currentBranch({ - - dir: this.pwd, + dir: cwd, }) || null; if (!targetBranch) { targetBranch = currentBranch || 'main'; @@ -51,8 +48,7 @@ export class GitPullCommand implements GitSubcommand { let remoteUrl: string; try { const remotes = await this.git.listRemotes({ - - dir: this.pwd, + dir: cwd, }); const targetRemote = remotes.find(r => r.remote === remote); @@ -66,7 +62,7 @@ export class GitPullCommand implements GitSubcommand { // Check for uncommitted changes const statusMatrix = await this.git.statusMatrix({ - dir: this.pwd, + dir: cwd, }); const modifiedFiles = statusMatrix @@ -84,7 +80,7 @@ export class GitPullCommand implements GitSubcommand { try { // Fetch from remote await this.git.fetch({ - dir: this.pwd, + dir: cwd, remote: remote, ref: targetBranch, }); @@ -94,8 +90,7 @@ export class GitPullCommand implements GitSubcommand { let remoteOid: string; try { remoteOid = await this.git.resolveRef({ - - dir: this.pwd, + dir: cwd, ref: remoteRef, }); } catch { @@ -106,15 +101,13 @@ export class GitPullCommand implements GitSubcommand { let currentOid: string; try { currentOid = await this.git.resolveRef({ - - dir: this.pwd, + dir: cwd, ref: 'HEAD', }); } catch { // Empty repository, just checkout the remote branch await this.git.checkout({ - - dir: this.pwd, + dir: cwd, ref: targetBranch, }); return createSuccessResult(`From ${remoteUrl}\n * branch ${targetBranch} -> FETCH_HEAD\nUpdating empty repository\nFast-forward\n`); @@ -127,8 +120,7 @@ export class GitPullCommand implements GitSubcommand { // Perform fast-forward merge (simplified) await this.git.merge({ - - dir: this.pwd, + dir: cwd, ours: currentBranch || 'HEAD', theirs: remoteRef, fastForwardOnly: true, @@ -172,4 +164,4 @@ export class GitPullCommand implements GitSubcommand { return { remote, branch }; } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/push.test.ts b/src/lib/commands/git/push.test.ts index aac97c4f..266e920a 100644 --- a/src/lib/commands/git/push.test.ts +++ b/src/lib/commands/git/push.test.ts @@ -25,7 +25,6 @@ describe('GitPushCommand', () => { pushCommand = new GitPushCommand({ git: mockGit as Git, fs: mockFS as JSRuntimeFS, - pwd: mockPwd, }); }); @@ -37,17 +36,16 @@ describe('GitPushCommand', () => { const cmd = new GitPushCommand({ git: mockGit as Git, fs: mockFSNoRepo as JSRuntimeFS, - pwd: '/non-existent', }); - const result = await cmd.execute(['origin', 'main']); + const result = await cmd.execute(['origin', 'main'], mockPwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('not a git repository'); }); it('should fail when no remote is configured', async () => { - const result = await pushCommand.execute(['origin', 'main']); + const result = await pushCommand.execute(['origin', 'main'], mockPwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('does not appear to be a git repository'); @@ -59,7 +57,7 @@ describe('GitPushCommand', () => { { remote: 'origin', url: 'https://example.com/repo.git' }, ]); - await pushCommand.execute(['origin', 'main', '--force']); + await pushCommand.execute(['origin', 'main', '--force'], mockPwd); // Verify that git.push was called with force: true expect(mockGit.push).toHaveBeenCalledWith( @@ -75,7 +73,7 @@ describe('GitPushCommand', () => { { remote: 'origin', url: 'https://example.com/repo.git' }, ]); - await pushCommand.execute(['origin', 'main', '-f']); + await pushCommand.execute(['origin', 'main', '-f'], mockPwd); // Verify that git.push was called with force: true expect(mockGit.push).toHaveBeenCalledWith( @@ -91,7 +89,7 @@ describe('GitPushCommand', () => { { remote: 'origin', url: 'https://example.com/repo.git' }, ]); - await pushCommand.execute(['origin', 'main']); + await pushCommand.execute(['origin', 'main'], mockPwd); // Verify that git.push was called with force: false expect(mockGit.push).toHaveBeenCalledWith( diff --git a/src/lib/commands/git/push.ts b/src/lib/commands/git/push.ts index 03f2cf4d..3e7f3450 100644 --- a/src/lib/commands/git/push.ts +++ b/src/lib/commands/git/push.ts @@ -14,21 +14,19 @@ export class GitPushCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; private signer?: NostrSigner; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; this.signer = options.signer; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -40,8 +38,7 @@ export class GitPushCommand implements GitSubcommand { if (!targetBranch) { try { targetBranch = await this.git.currentBranch({ - - dir: this.pwd, + dir: cwd, }) || undefined; if (!targetBranch) { return createErrorResult('fatal: You are not currently on a branch.'); @@ -55,7 +52,7 @@ export class GitPushCommand implements GitSubcommand { let remoteUrl: string; try { const remotes = await this.git.listRemotes({ - dir: this.pwd, + dir: cwd, }); const targetRemote = remotes.find(r => r.remote === remote); @@ -71,7 +68,7 @@ export class GitPushCommand implements GitSubcommand { try { await this.git.push({ - dir: this.pwd, + dir: cwd, remote: remote, ref: targetBranch, remoteRef: targetBranch, @@ -138,4 +135,4 @@ export class GitPushCommand implements GitSubcommand { return { remote, branch, options }; } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/remote.ts b/src/lib/commands/git/remote.ts index 203c402f..414d58ad 100644 --- a/src/lib/commands/git/remote.ts +++ b/src/lib/commands/git/remote.ts @@ -12,19 +12,17 @@ export class GitRemoteCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -33,13 +31,13 @@ export class GitRemoteCommand implements GitSubcommand { switch (action) { case 'list': - return await this.listRemotes(options.verbose); + return await this.listRemotes(options.verbose, cwd); case 'add': - return await this.addRemote(name!, url!); + return await this.addRemote(name!, url!, cwd); case 'remove': - return await this.removeRemote(name!); + return await this.removeRemote(name!, cwd); default: - return await this.listRemotes(options.verbose); + return await this.listRemotes(options.verbose, cwd); } } catch (error) { @@ -85,10 +83,10 @@ export class GitRemoteCommand implements GitSubcommand { return { action, name, url, options }; } - private async listRemotes(verbose: boolean): Promise { + private async listRemotes(verbose: boolean, cwd: string): Promise { try { const remotes = await this.git.listRemotes({ - dir: this.pwd, + dir: cwd, }); if (remotes.length === 0) { @@ -115,7 +113,7 @@ export class GitRemoteCommand implements GitSubcommand { } } - private async addRemote(name: string, url: string): Promise { + private async addRemote(name: string, url: string, cwd: string): Promise { try { if (!name || !url) { return createErrorResult('usage: git remote add '); @@ -125,7 +123,7 @@ export class GitRemoteCommand implements GitSubcommand { try { const remotes = await this.git.listRemotes({ - dir: this.pwd, + dir: cwd, }); const existingRemote = remotes.find(r => r.remote === name); @@ -138,7 +136,7 @@ export class GitRemoteCommand implements GitSubcommand { // Add the remote await this.git.addRemote({ - dir: this.pwd, + dir: cwd, remote: name, url: url, }); @@ -150,7 +148,7 @@ export class GitRemoteCommand implements GitSubcommand { } } - private async removeRemote(name: string): Promise { + private async removeRemote(name: string, cwd: string): Promise { try { if (!name) { return createErrorResult('usage: git remote remove '); @@ -160,7 +158,7 @@ export class GitRemoteCommand implements GitSubcommand { try { const remotes = await this.git.listRemotes({ - dir: this.pwd, + dir: cwd, }); const existingRemote = remotes.find(r => r.remote === name); @@ -173,7 +171,7 @@ export class GitRemoteCommand implements GitSubcommand { // Remove the remote await this.git.deleteRemote({ - dir: this.pwd, + dir: cwd, remote: name, }); @@ -183,4 +181,4 @@ export class GitRemoteCommand implements GitSubcommand { return createErrorResult(`Failed to remove remote: ${error instanceof Error ? error.message : 'Unknown error'}`); } } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/reset.test.ts b/src/lib/commands/git/reset.test.ts index aff418fa..34d0ca31 100644 --- a/src/lib/commands/git/reset.test.ts +++ b/src/lib/commands/git/reset.test.ts @@ -56,7 +56,6 @@ const mockFS = { const mockOptions: GitSubcommandOptions = { git: mockGit, fs: mockFS, - pwd: '/test/repo', }; describe('GitResetCommand', () => { @@ -146,14 +145,14 @@ describe('GitResetCommand', () => { } as unknown as JSRuntimeFS, }); - const result = await commandWithoutGit.execute([]); + const result = await commandWithoutGit.execute([], '/test/repo'); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('fatal: not a git repository'); }); it('should unstage all files when called without arguments', async () => { - const result = await command.execute([]); + const result = await command.execute([], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Unstaged changes after reset:'); @@ -165,7 +164,7 @@ describe('GitResetCommand', () => { }); it('should unstage all files when called with HEAD', async () => { - const result = await command.execute(['HEAD']); + const result = await command.execute(['HEAD'], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Unstaged changes after reset:'); @@ -174,7 +173,7 @@ describe('GitResetCommand', () => { }); it('should unstage specific files when called with HEAD and file paths', async () => { - const result = await command.execute(['HEAD', 'staged.txt']); + const result = await command.execute(['HEAD', 'staged.txt'], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Unstaged changes after reset:'); @@ -194,7 +193,7 @@ describe('GitResetCommand', () => { } as unknown as Git, }); - const result = await commandWithNoStaged.execute([]); + const result = await commandWithNoStaged.execute([], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); @@ -214,35 +213,35 @@ describe('GitResetCommand', () => { } as unknown as Git, }); - const result = await commandWithError.execute(['HEAD', 'nonexistent.txt']); + const result = await commandWithError.execute(['HEAD', 'nonexistent.txt'], '/test/repo'); expect(result.exitCode).toBe(1); expect(result.stderr).toContain("error: pathspec 'nonexistent.txt' did not match any file(s) known to git"); }); it('should handle commit reset with hard mode', async () => { - const result = await command.execute(['--hard', 'HEAD~1']); + const result = await command.execute(['--hard', 'HEAD~1'], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('HEAD is now at def456a'); }); it('should handle commit reset with mixed mode', async () => { - const result = await command.execute(['--mixed', 'HEAD~1']); + const result = await command.execute(['--mixed', 'HEAD~1'], '/test/repo'); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('HEAD is now at def456a'); }); it('should return error for soft reset (not implemented)', async () => { - const result = await command.execute(['--soft', 'HEAD~1']); + const result = await command.execute(['--soft', 'HEAD~1'], '/test/repo'); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('--soft reset is not implemented'); }); it('should handle invalid commit reference', async () => { - const result = await command.execute(['abcdef12345']); + const result = await command.execute(['abcdef12345'], '/test/repo'); expect(result.exitCode).toBe(1); expect(result.stderr).toContain("fatal: ambiguous argument 'abcdef12345'"); diff --git a/src/lib/commands/git/reset.ts b/src/lib/commands/git/reset.ts index bad562eb..c75d87d9 100644 --- a/src/lib/commands/git/reset.ts +++ b/src/lib/commands/git/reset.ts @@ -12,19 +12,17 @@ export class GitResetCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -33,10 +31,10 @@ export class GitResetCommand implements GitSubcommand { if (isFileReset) { // Reset specific files or all files (unstage) - return await this.resetFiles(files); + return await this.resetFiles(files, cwd); } else { // Reset to commit - return await this.resetToCommit(target, mode); + return await this.resetToCommit(target, mode, cwd); } } catch (error) { @@ -89,7 +87,7 @@ export class GitResetCommand implements GitSubcommand { return { mode, target, files, isFileReset }; } - private async resetFiles(files: string[]): Promise { + private async resetFiles(files: string[], cwd: string): Promise { try { const resetFiles: string[] = []; const errors: string[] = []; @@ -99,7 +97,7 @@ export class GitResetCommand implements GitSubcommand { try { // Get the status matrix to find all staged files const statusMatrix = await this.git.statusMatrix({ - dir: this.pwd, + dir: cwd, }); // Find files that are staged (differ from HEAD) @@ -117,7 +115,7 @@ export class GitResetCommand implements GitSubcommand { for (const file of stagedFiles) { try { await this.git.resetIndex({ - dir: this.pwd, + dir: cwd, filepath: file, }); resetFiles.push(file); @@ -134,7 +132,7 @@ export class GitResetCommand implements GitSubcommand { try { // Remove from staging area (reset to HEAD) await this.git.resetIndex({ - dir: this.pwd, + dir: cwd, filepath: file, }); resetFiles.push(file); @@ -159,14 +157,13 @@ export class GitResetCommand implements GitSubcommand { } } - private async resetToCommit(target: string, mode: 'soft' | 'mixed' | 'hard'): Promise { + private async resetToCommit(target: string, mode: 'soft' | 'mixed' | 'hard', cwd: string): Promise { try { // Resolve the target commit let targetOid: string; try { targetOid = await this.git.resolveRef({ - - dir: this.pwd, + dir: cwd, ref: target, }); } catch { @@ -177,8 +174,7 @@ export class GitResetCommand implements GitSubcommand { let currentOid: string; try { currentOid = await this.git.resolveRef({ - - dir: this.pwd, + dir: cwd, ref: 'HEAD', }); } catch { @@ -205,7 +201,7 @@ export class GitResetCommand implements GitSubcommand { let currentBranch: string | null = null; try { currentBranch = await this.git.currentBranch({ - dir: this.pwd, + dir: cwd, }) || null; } catch { // Detached HEAD state @@ -215,14 +211,14 @@ export class GitResetCommand implements GitSubcommand { if (currentOid !== targetOid) { if (currentBranch) { await this.git.writeRef({ - dir: this.pwd, + dir: cwd, ref: `refs/heads/${currentBranch}`, value: targetOid, force: true, }); } else { await this.git.writeRef({ - dir: this.pwd, + dir: cwd, ref: 'HEAD', value: targetOid, force: true, @@ -233,7 +229,7 @@ export class GitResetCommand implements GitSubcommand { // Reset the index only (not the working directory) // Using noCheckout: true to only update the index, not the working directory await this.git.checkout({ - dir: this.pwd, + dir: cwd, ref: targetOid, noCheckout: true, noUpdateHead: true, @@ -253,7 +249,7 @@ export class GitResetCommand implements GitSubcommand { // Get the commit object to ensure it exists await this.git.readCommit({ - dir: this.pwd, + dir: cwd, oid: targetOid, }); @@ -261,7 +257,7 @@ export class GitResetCommand implements GitSubcommand { let currentBranch: string | null = null; try { currentBranch = await this.git.currentBranch({ - dir: this.pwd, + dir: cwd, }) || null; } catch { // Detached HEAD state @@ -272,14 +268,14 @@ export class GitResetCommand implements GitSubcommand { if (currentOid !== targetOid) { if (currentBranch) { await this.git.writeRef({ - dir: this.pwd, + dir: cwd, ref: `refs/heads/${currentBranch}`, value: targetOid, force: true, }); } else { await this.git.writeRef({ - dir: this.pwd, + dir: cwd, ref: 'HEAD', value: targetOid, force: true, @@ -291,7 +287,7 @@ export class GitResetCommand implements GitSubcommand { // Using noUpdateHead: true because we already updated HEAD above // Using force: true to overwrite any local changes await this.git.checkout({ - dir: this.pwd, + dir: cwd, ref: targetOid, force: true, noUpdateHead: true, @@ -310,4 +306,4 @@ export class GitResetCommand implements GitSubcommand { return createErrorResult(`Failed to reset: ${error instanceof Error ? error.message : 'Unknown error'}`); } } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/show.test.ts b/src/lib/commands/git/show.test.ts index d89b1109..d9b7edfe 100644 --- a/src/lib/commands/git/show.test.ts +++ b/src/lib/commands/git/show.test.ts @@ -319,12 +319,11 @@ describe('GitShowCommand', () => { showCommand = new GitShowCommand({ git: mockGit as Git, fs: mockFS as JSRuntimeFS, - pwd: mockPwd, }); }); it('should show basic commit information', async () => { - const result = await showCommand.execute(['simple-commit']); + const result = await showCommand.execute(['simple-commit'], mockPwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('commit simple-commit'); @@ -333,7 +332,7 @@ describe('GitShowCommand', () => { }); it('should handle initial commits properly', async () => { - const result = await showCommand.execute(['initial-commit']); + const result = await showCommand.execute(['initial-commit'], mockPwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Initial commit'); @@ -344,7 +343,7 @@ describe('GitShowCommand', () => { it('should resolve HEAD~1 correctly', async () => { // First, check that the implementation correctly resolves HEAD~1 - const result = await showCommand.execute(['HEAD~1']); + const result = await showCommand.execute(['HEAD~1'], mockPwd); // Verify that resolveRef was called with HEAD expect(mockGit.resolveRef).toHaveBeenCalledWith({ @@ -363,7 +362,7 @@ describe('GitShowCommand', () => { }); it('should resolve HEAD^2 correctly', async () => { - const result = await showCommand.execute(['HEAD^2']); + const result = await showCommand.execute(['HEAD^2'], mockPwd); // Verify that resolveRef was called with HEAD expect(mockGit.resolveRef).toHaveBeenCalledWith({ @@ -411,7 +410,7 @@ describe('GitShowCommand', () => { }); // Execute the command - const result = await showCommand.execute(['simple-commit']); + const result = await showCommand.execute(['simple-commit'], mockPwd); // Check that the command output contains the commit message expect(result.stdout).toContain('Simple changes'); @@ -569,7 +568,7 @@ describe('GitShowCommand', () => { }); // Execute the command - const result = await showCommand.execute(['diff-test-commit']); + const result = await showCommand.execute(['diff-test-commit'], mockPwd); // Debug output console.log('Test output:', result.stdout); @@ -596,7 +595,7 @@ describe('GitShowCommand', () => { }); it('should return an error for invalid references', async () => { - const result = await showCommand.execute(['non-existent-ref']); + const result = await showCommand.execute(['non-existent-ref'], mockPwd); expect(result.exitCode).not.toBe(0); expect(result.stderr).toContain('bad revision'); @@ -605,7 +604,7 @@ describe('GitShowCommand', () => { it('should return an error when not in a git repository', async () => { mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory')); - const result = await showCommand.execute([]); + const result = await showCommand.execute([], mockPwd); expect(result.exitCode).not.toBe(0); expect(result.stderr).toContain('not a git repository'); diff --git a/src/lib/commands/git/show.ts b/src/lib/commands/git/show.ts index 5f1ec8b4..bf8579c7 100644 --- a/src/lib/commands/git/show.ts +++ b/src/lib/commands/git/show.ts @@ -11,19 +11,17 @@ export class GitShowCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -31,12 +29,12 @@ export class GitShowCommand implements GitSubcommand { const { commit } = this.parseArgs(args); // Resolve the commit reference (handling relative refs like HEAD~1) - const resolvedCommit = await this.resolveCommitRef(commit); + const resolvedCommit = await this.resolveCommitRef(commit, cwd); if (!resolvedCommit) { return createErrorResult(`fatal: bad revision '${commit}'`); } - return await this.showCommit(resolvedCommit); + return await this.showCommit(resolvedCommit, cwd); } catch (error) { return createErrorResult(`git show: ${error instanceof Error ? error.message : 'Unknown error'}`); @@ -59,7 +57,7 @@ export class GitShowCommand implements GitSubcommand { /** * Resolve a commit reference, handling special syntax like HEAD~N and HEAD^N */ - private async resolveCommitRef(ref: string): Promise { + private async resolveCommitRef(ref: string, cwd: string): Promise { try { // Handle HEAD~N syntax (ancestor) const tildeMatch = ref.match(/^(.+)~(\d+)$/); @@ -69,17 +67,17 @@ export class GitShowCommand implements GitSubcommand { if (numSteps === 0) { // ~0 is the commit itself - return this.resolveCommitRef(baseRef); + return this.resolveCommitRef(baseRef, cwd); } // First resolve the base reference - const baseCommit = await this.resolveCommitRef(baseRef); + const baseCommit = await this.resolveCommitRef(baseRef, cwd); if (!baseCommit) { throw new Error(`Could not resolve base reference: ${baseRef}`); } // Walk back N steps in history - return this.walkBackNCommits(baseCommit, numSteps); + return this.walkBackNCommits(baseCommit, numSteps, cwd); } // Handle HEAD^N syntax (Nth parent) @@ -89,19 +87,19 @@ export class GitShowCommand implements GitSubcommand { const parentIndex = parentNum ? parseInt(parentNum, 10) - 1 : 0; // Default to first parent // First resolve the base reference - const baseCommit = await this.resolveCommitRef(baseRef); + const baseCommit = await this.resolveCommitRef(baseRef, cwd); if (!baseCommit) { throw new Error(`Could not resolve base reference: ${baseRef}`); } // Get the specified parent - return this.getNthParent(baseCommit, parentIndex); + return this.getNthParent(baseCommit, parentIndex, cwd); } // Handle simple reference (direct resolution) try { return await this.git.resolveRef({ - dir: this.pwd, + dir: cwd, ref, }); } catch (error) { @@ -119,14 +117,14 @@ export class GitShowCommand implements GitSubcommand { /** * Walk back N commits from the given commit */ - private async walkBackNCommits(startCommit: string, steps: number): Promise { + private async walkBackNCommits(startCommit: string, steps: number, cwd: string): Promise { try { let currentCommit = startCommit; for (let i = 0; i < steps; i++) { // Get the commit object const commit = await this.git.readCommit({ - dir: this.pwd, + dir: cwd, oid: currentCommit, }); @@ -149,11 +147,11 @@ export class GitShowCommand implements GitSubcommand { /** * Get the Nth parent of the given commit */ - private async getNthParent(commit: string, parentIndex: number): Promise { + private async getNthParent(commit: string, parentIndex: number, cwd: string): Promise { try { // Get the commit object const commitObj = await this.git.readCommit({ - dir: this.pwd, + dir: cwd, oid: commit, }); @@ -175,11 +173,11 @@ export class GitShowCommand implements GitSubcommand { } } - private async showCommit(commitRef: string): Promise { + private async showCommit(commitRef: string, cwd: string): Promise { try { // Get the commit const commits = await this.git.log({ - dir: this.pwd, + dir: cwd, depth: 1, ref: commitRef, }); @@ -220,7 +218,7 @@ export class GitShowCommand implements GitSubcommand { // Get the tree for this commit const tree = await this.git.readTree({ - dir: this.pwd, + dir: cwd, oid: commit.oid, }); @@ -237,12 +235,12 @@ export class GitShowCommand implements GitSubcommand { // Get the trees for both commits const parentTree = await this.git.readTree({ - dir: this.pwd, + dir: cwd, oid: parentCommit, }); const commitTree = await this.git.readTree({ - dir: this.pwd, + dir: cwd, oid: commit.oid, }); @@ -285,7 +283,7 @@ export class GitShowCommand implements GitSubcommand { const result = new Map(); try { const tree = await this.git.readTree({ - dir: this.pwd, + dir: cwd, oid, }); @@ -435,7 +433,7 @@ export class GitShowCommand implements GitSubcommand { let parentContent = ''; try { const parentBlob = await this.git.readBlob({ - dir: this.pwd, + dir: cwd, oid: parentCommit, filepath: change.path, }); @@ -449,7 +447,7 @@ export class GitShowCommand implements GitSubcommand { let currentContent = ''; try { const currentBlob = await this.git.readBlob({ - dir: this.pwd, + dir: cwd, oid: commit.oid, filepath: change.path, }); @@ -689,4 +687,4 @@ export class GitShowCommand implements GitSubcommand { return createErrorResult(`Failed to show commit: ${error instanceof Error ? error.message : 'Unknown error'}`); } } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/stash.test.ts b/src/lib/commands/git/stash.test.ts index 946db978..6b8fb014 100644 --- a/src/lib/commands/git/stash.test.ts +++ b/src/lib/commands/git/stash.test.ts @@ -65,7 +65,6 @@ describe('GitStashCommand', () => { stashCommand = new GitStashCommand({ git: mockGit, fs: mockFS, - pwd: testCwd, }); }); @@ -78,14 +77,14 @@ describe('GitStashCommand', () => { it('should return error when not in a git repository', async () => { vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT')); - const result = await stashCommand.execute(['push']); + const result = await stashCommand.execute(['push'], testCwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('fatal: not a git repository'); }); it('should show help with --help flag', async () => { - const result = await stashCommand.execute(['--help']); + const result = await stashCommand.execute(['--help'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('git stash list'); @@ -99,7 +98,7 @@ describe('GitStashCommand', () => { ['unchanged.txt', 1, 1, 1], // No changes ]); - const result = await stashCommand.execute(['push']); + const result = await stashCommand.execute(['push'], testCwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('No local changes to save'); @@ -119,7 +118,7 @@ describe('GitStashCommand', () => { return Promise.resolve(''); }); - const result = await stashCommand.execute(['push']); + const result = await stashCommand.execute(['push'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Saved working directory and index state'); @@ -145,7 +144,7 @@ describe('GitStashCommand', () => { return Promise.resolve(''); }); - const result = await stashCommand.execute(['push', '-m', 'my custom message']); + const result = await stashCommand.execute(['push', '-m', 'my custom message'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('my custom message'); @@ -165,7 +164,7 @@ describe('GitStashCommand', () => { return Promise.resolve(''); }); - const result = await stashCommand.execute(['push', '-u']); + const result = await stashCommand.execute(['push', '-u'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Saved working directory'); @@ -183,7 +182,7 @@ describe('GitStashCommand', () => { return Promise.resolve(''); }); - const result = await stashCommand.execute(['push']); + const result = await stashCommand.execute(['push'], testCwd); expect(result.exitCode).toBe(0); expect(mockGit.checkout).toHaveBeenCalledWith({ @@ -207,7 +206,7 @@ describe('GitStashCommand', () => { return Promise.resolve(''); }); - const result = await stashCommand.execute(['push']); + const result = await stashCommand.execute(['push'], testCwd); expect(result.exitCode).toBe(0); expect(mockGit.resetIndex).toHaveBeenCalledWith({ @@ -221,7 +220,7 @@ describe('GitStashCommand', () => { it('should return empty when no stashes', async () => { vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT')); - const result = await stashCommand.execute(['list']); + const result = await stashCommand.execute(['list'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); @@ -234,7 +233,7 @@ describe('GitStashCommand', () => { ]; vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes)); - const result = await stashCommand.execute(['list']); + const result = await stashCommand.execute(['list'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('stash@{0}: first stash'); @@ -246,7 +245,7 @@ describe('GitStashCommand', () => { it('should return error when no stashes', async () => { vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT')); - const result = await stashCommand.execute(['show']); + const result = await stashCommand.execute(['show'], testCwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('No stash entries found'); @@ -267,7 +266,7 @@ describe('GitStashCommand', () => { ]; vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes)); - const result = await stashCommand.execute(['show']); + const result = await stashCommand.execute(['show'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('M\tmodified.txt'); @@ -293,7 +292,7 @@ describe('GitStashCommand', () => { ]; vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes)); - const result = await stashCommand.execute(['show', 'stash@{1}']); + const result = await stashCommand.execute(['show', 'stash@{1}'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('file1.txt'); @@ -305,7 +304,7 @@ describe('GitStashCommand', () => { it('should return error when no stashes', async () => { vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT')); - const result = await stashCommand.execute(['apply']); + const result = await stashCommand.execute(['apply'], testCwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('No stash entries found'); @@ -325,7 +324,7 @@ describe('GitStashCommand', () => { ]; vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes)); - const result = await stashCommand.execute(['apply']); + const result = await stashCommand.execute(['apply'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('test stash'); @@ -358,7 +357,7 @@ describe('GitStashCommand', () => { ]; vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes)); - const result = await stashCommand.execute(['apply', 'stash@{1}']); + const result = await stashCommand.execute(['apply', 'stash@{1}'], testCwd); expect(result.exitCode).toBe(0); expect(mockFS.writeFile).toHaveBeenCalledWith( @@ -379,7 +378,7 @@ describe('GitStashCommand', () => { ]; vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes)); - const result = await stashCommand.execute(['apply']); + const result = await stashCommand.execute(['apply'], testCwd); expect(result.exitCode).toBe(0); expect(mockFS.unlink).toHaveBeenCalledWith(expect.stringContaining('deleted.txt')); @@ -399,7 +398,7 @@ describe('GitStashCommand', () => { ]; vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes)); - const result = await stashCommand.execute(['pop']); + const result = await stashCommand.execute(['pop'], testCwd); expect(result.exitCode).toBe(0); expect(mockFS.writeFile).toHaveBeenCalledWith( @@ -418,7 +417,7 @@ describe('GitStashCommand', () => { it('should return error when no stashes', async () => { vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT')); - const result = await stashCommand.execute(['drop']); + const result = await stashCommand.execute(['drop'], testCwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('No stash entries found'); @@ -431,7 +430,7 @@ describe('GitStashCommand', () => { ]; vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes)); - const result = await stashCommand.execute(['drop']); + const result = await stashCommand.execute(['drop'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Dropped stash@{0}'); @@ -449,7 +448,7 @@ describe('GitStashCommand', () => { ]; vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes)); - const result = await stashCommand.execute(['drop', 'stash@{1}']); + const result = await stashCommand.execute(['drop', 'stash@{1}'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Dropped stash@{1}'); @@ -461,7 +460,7 @@ describe('GitStashCommand', () => { ]; vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes)); - const result = await stashCommand.execute(['drop', 'stash@{5}']); + const result = await stashCommand.execute(['drop', 'stash@{5}'], testCwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('is not a valid reference'); @@ -476,7 +475,7 @@ describe('GitStashCommand', () => { ]; vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes)); - const result = await stashCommand.execute(['clear']); + const result = await stashCommand.execute(['clear'], testCwd); expect(result.exitCode).toBe(0); expect(mockFS.writeFile).toHaveBeenCalledWith( @@ -501,7 +500,7 @@ describe('GitStashCommand', () => { return Promise.resolve(''); }); - const result = await stashCommand.execute(['save']); + const result = await stashCommand.execute(['save'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Saved working directory'); @@ -521,7 +520,7 @@ describe('GitStashCommand', () => { return Promise.resolve(''); }); - const result = await stashCommand.execute([]); + const result = await stashCommand.execute([], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('Saved working directory'); diff --git a/src/lib/commands/git/stash.ts b/src/lib/commands/git/stash.ts index 72e3333a..9ff4e79d 100644 --- a/src/lib/commands/git/stash.ts +++ b/src/lib/commands/git/stash.ts @@ -24,19 +24,17 @@ export class GitStashCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -47,26 +45,26 @@ export class GitStashCommand implements GitSubcommand { switch (subcommand) { case 'push': case 'save': - return await this.stashPush(subcommandArgs); + return await this.stashPush(subcommandArgs, cwd); case 'list': - return await this.stashList(); + return await this.stashList(cwd); case 'apply': - return await this.stashApply(subcommandArgs); + return await this.stashApply(subcommandArgs, cwd); case 'pop': - return await this.stashPop(subcommandArgs); + return await this.stashPop(subcommandArgs, cwd); case 'drop': - return await this.stashDrop(subcommandArgs); + return await this.stashDrop(subcommandArgs, cwd); case 'clear': - return await this.stashClear(); + return await this.stashClear(cwd); case 'show': - return await this.stashShow(subcommandArgs); + return await this.stashShow(subcommandArgs, cwd); case '--help': case '-h': - return this.showHelp(); + return this.showHelp(cwd); default: // If first arg doesn't look like a subcommand, treat it as 'push' if (subcommand.startsWith('-')) { - return await this.stashPush(args); + return await this.stashPush(args, cwd); } return createErrorResult(`git stash: '${subcommand}' is not a stash command. See 'git stash --help'.`); } @@ -76,7 +74,7 @@ export class GitStashCommand implements GitSubcommand { } } - private async stashPush(args: string[]): Promise { + private async stashPush(args: string[], cwd: string): Promise { try { // Parse arguments let message = 'WIP on'; @@ -96,13 +94,13 @@ export class GitStashCommand implements GitSubcommand { // Get current branch let currentBranch: string | null = null; try { - currentBranch = await this.git.currentBranch({ dir: this.pwd }) || null; + currentBranch = await this.git.currentBranch({ dir: cwd }) || null; } catch { currentBranch = 'HEAD'; } // Get status to find changed files - const statusMatrix = await this.git.statusMatrix({ dir: this.pwd }); + const statusMatrix = await this.git.statusMatrix({ dir: cwd }); const filesToStash: StashEntry['files'] = []; const stagedFiles: string[] = []; @@ -124,7 +122,7 @@ export class GitStashCommand implements GitSubcommand { // Untracked files (only with -u flag) if (includeUntracked && headStatus === 0 && stageStatus === 0 && workdirStatus === 2) { - const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8'); + const content = await this.fs.readFile(join(cwd, filepath), 'utf8'); filesToStash.push({ filepath, content, @@ -141,7 +139,7 @@ export class GitStashCommand implements GitSubcommand { } // Staged new files or modified files (staged changes) else if (hasStagedChanges && workdirStatus === 2) { - const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8'); + const content = await this.fs.readFile(join(cwd, filepath), 'utf8'); const status = headStatus === 0 ? 'added' : 'modified'; filesToStash.push({ filepath, @@ -151,7 +149,7 @@ export class GitStashCommand implements GitSubcommand { } // Unstaged modifications in working directory else if (hasWorkdirChanges && workdirStatus === 2) { - const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8'); + const content = await this.fs.readFile(join(cwd, filepath), 'utf8'); filesToStash.push({ filepath, content, @@ -177,7 +175,7 @@ export class GitStashCommand implements GitSubcommand { }; // Save stash - await this.saveStash(stashEntry); + await this.saveStash(stashEntry, cwd); // Revert changes in working directory for (const file of filesToStash) { @@ -185,21 +183,21 @@ export class GitStashCommand implements GitSubcommand { if (file.status === 'deleted') { // Restore deleted file from HEAD await this.git.checkout({ - dir: this.pwd, + dir: cwd, filepaths: [file.filepath], force: true, }); } else if (file.status === 'modified') { // Restore file from HEAD using checkout await this.git.checkout({ - dir: this.pwd, + dir: cwd, filepaths: [file.filepath], force: true, }); } else if (file.status === 'added') { // Delete new file (it doesn't exist in HEAD) try { - await this.fs.unlink(join(this.pwd, file.filepath)); + await this.fs.unlink(join(cwd, file.filepath)); } catch { // File might already be gone } @@ -213,7 +211,7 @@ export class GitStashCommand implements GitSubcommand { for (const file of stagedFiles) { try { await this.git.resetIndex({ - dir: this.pwd, + dir: cwd, filepath: file, }); } catch { @@ -228,9 +226,9 @@ export class GitStashCommand implements GitSubcommand { } } - private async stashList(): Promise { + private async stashList(cwd: string): Promise { try { - const stashes = await this.loadStashes(); + const stashes = await this.loadStashes(cwd); if (stashes.length === 0) { return createSuccessResult(''); @@ -247,9 +245,9 @@ export class GitStashCommand implements GitSubcommand { } } - private async stashApply(args: string[]): Promise { + private async stashApply(args: string[], cwd: string): Promise { try { - const stashes = await this.loadStashes(); + const stashes = await this.loadStashes(cwd); if (stashes.length === 0) { return createErrorResult('No stash entries found.'); @@ -257,7 +255,7 @@ export class GitStashCommand implements GitSubcommand { // Parse stash reference (e.g., stash@{0} or just 0) const stashRef = args[0] || 'stash@{0}'; - const index = this.parseStashRef(stashRef); + const index = this.parseStashRef(stashRef, cwd); if (index < 0 || index >= stashes.length) { return createErrorResult(`stash@{${index}} is not a valid reference`); @@ -271,19 +269,19 @@ export class GitStashCommand implements GitSubcommand { if (file.status === 'deleted') { // Delete the file try { - await this.fs.unlink(join(this.pwd, file.filepath)); + await this.fs.unlink(join(cwd, file.filepath)); } catch { // File might not exist } } else { // Create file with stashed content - const dir = join(this.pwd, file.filepath, '..'); + const dir = join(cwd, file.filepath, '..'); try { await this.fs.mkdir(dir, { recursive: true }); } catch { // Directory might exist } - await this.fs.writeFile(join(this.pwd, file.filepath), file.content); + await this.fs.writeFile(join(cwd, file.filepath), file.content); } } catch (error) { console.warn(`Failed to apply ${file.filepath}:`, error); @@ -294,7 +292,7 @@ export class GitStashCommand implements GitSubcommand { for (const filepath of stash.stagedFiles) { try { await this.git.add({ - dir: this.pwd, + dir: cwd, filepath, }); } catch { @@ -309,17 +307,17 @@ export class GitStashCommand implements GitSubcommand { } } - private async stashPop(args: string[]): Promise { + private async stashPop(args: string[], cwd: string): Promise { try { // Apply the stash first - const result = await this.stashApply(args); + const result = await this.stashApply(args, cwd); if (result.exitCode !== 0) { return result; } // If apply succeeded, drop the stash - const dropResult = await this.stashDrop(args); + const dropResult = await this.stashDrop(args, cwd); if (dropResult.exitCode !== 0) { return createErrorResult(`Applied stash successfully but failed to drop: ${dropResult.stderr}`); @@ -332,9 +330,9 @@ export class GitStashCommand implements GitSubcommand { } } - private async stashDrop(args: string[]): Promise { + private async stashDrop(args: string[], cwd: string): Promise { try { - const stashes = await this.loadStashes(); + const stashes = await this.loadStashes(cwd); if (stashes.length === 0) { return createErrorResult('No stash entries found.'); @@ -342,7 +340,7 @@ export class GitStashCommand implements GitSubcommand { // Parse stash reference const stashRef = args[0] || 'stash@{0}'; - const index = this.parseStashRef(stashRef); + const index = this.parseStashRef(stashRef, cwd); if (index < 0 || index >= stashes.length) { return createErrorResult(`stash@{${index}} is not a valid reference`); @@ -350,7 +348,7 @@ export class GitStashCommand implements GitSubcommand { // Remove the stash stashes.splice(index, 1); - await this.saveStashes(stashes); + await this.saveStashes(stashes, cwd); return createSuccessResult(`Dropped stash@{${index}}\n`); @@ -359,9 +357,9 @@ export class GitStashCommand implements GitSubcommand { } } - private async stashClear(): Promise { + private async stashClear(cwd: string): Promise { try { - await this.saveStashes([]); + await this.saveStashes([], cwd); return createSuccessResult(''); } catch (error) { @@ -369,9 +367,9 @@ export class GitStashCommand implements GitSubcommand { } } - private async stashShow(args: string[]): Promise { + private async stashShow(args: string[], cwd: string): Promise { try { - const stashes = await this.loadStashes(); + const stashes = await this.loadStashes(cwd); if (stashes.length === 0) { return createErrorResult('No stash entries found.'); @@ -379,7 +377,7 @@ export class GitStashCommand implements GitSubcommand { // Parse stash reference const stashRef = args[0] || 'stash@{0}'; - const index = this.parseStashRef(stashRef); + const index = this.parseStashRef(stashRef, cwd); if (index < 0 || index >= stashes.length) { return createErrorResult(`stash@{${index}} is not a valid reference`); @@ -405,7 +403,7 @@ export class GitStashCommand implements GitSubcommand { } } - private parseStashRef(ref: string): number { + private parseStashRef(ref: string, _cwd: string): number { // Parse stash@{N} or just N const match = ref.match(/^(?:stash@\{)?(\d+)\}?$/); if (match) { @@ -414,9 +412,9 @@ export class GitStashCommand implements GitSubcommand { return 0; // Default to stash@{0} } - private async loadStashes(): Promise { + private async loadStashes(cwd: string): Promise { try { - const stashPath = join(this.pwd, '.git', 'shakespeare_stash.json'); + const stashPath = join(cwd, '.git', 'shakespeare_stash.json'); const data = await this.fs.readFile(stashPath, 'utf8'); return JSON.parse(data) as StashEntry[]; } catch { @@ -424,18 +422,18 @@ export class GitStashCommand implements GitSubcommand { } } - private async saveStash(stash: StashEntry): Promise { - const stashes = await this.loadStashes(); + private async saveStash(stash: StashEntry, cwd: string): Promise { + const stashes = await this.loadStashes(cwd); stashes.unshift(stash); // Add to beginning of array - await this.saveStashes(stashes); + await this.saveStashes(stashes, cwd); } - private async saveStashes(stashes: StashEntry[]): Promise { - const stashPath = join(this.pwd, '.git', 'shakespeare_stash.json'); + private async saveStashes(stashes: StashEntry[], cwd: string): Promise { + const stashPath = join(cwd, '.git', 'shakespeare_stash.json'); await this.fs.writeFile(stashPath, JSON.stringify(stashes, null, 2)); } - private showHelp(): ShellCommandResult { + private showHelp(_cwd: string): ShellCommandResult { const helpText = `usage: git stash list [] or: git stash show [] or: git stash drop [] @@ -446,4 +444,4 @@ export class GitStashCommand implements GitSubcommand { return createSuccessResult(helpText); } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/status.test.ts b/src/lib/commands/git/status.test.ts index 4132e906..f2299db5 100644 --- a/src/lib/commands/git/status.test.ts +++ b/src/lib/commands/git/status.test.ts @@ -52,7 +52,6 @@ describe('GitStatusCommand', () => { statusCommand = new GitStatusCommand({ git: mockGit, fs: mockFS, - pwd: testCwd, }); }); @@ -66,7 +65,7 @@ describe('GitStatusCommand', () => { // Mock stat to throw error for .git directory vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT')); - const result = await statusCommand.execute([]); + const result = await statusCommand.execute([], testCwd); expect(result.exitCode).toBe(1); expect(result.stderr).toContain('fatal: not a git repository'); @@ -77,7 +76,7 @@ describe('GitStatusCommand', () => { vi.mocked(mockGit.statusMatrix).mockResolvedValue([]); vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); - const result = await statusCommand.execute([]); + const result = await statusCommand.execute([], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('On branch main'); @@ -93,7 +92,7 @@ describe('GitStatusCommand', () => { ]); vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); - const result = await statusCommand.execute([]); + const result = await statusCommand.execute([], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('On branch main'); @@ -109,7 +108,7 @@ describe('GitStatusCommand', () => { ]); vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); - const result = await statusCommand.execute([]); + const result = await statusCommand.execute([], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('On branch main'); @@ -125,7 +124,7 @@ describe('GitStatusCommand', () => { ]); vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); - const result = await statusCommand.execute([]); + const result = await statusCommand.execute([], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('On branch main'); @@ -141,7 +140,7 @@ describe('GitStatusCommand', () => { ]); vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); - const result = await statusCommand.execute([]); + const result = await statusCommand.execute([], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('On branch main'); @@ -159,7 +158,7 @@ describe('GitStatusCommand', () => { ]); vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); - const result = await statusCommand.execute(['--porcelain']); + const result = await statusCommand.execute(['--porcelain'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('?? untracked.txt'); @@ -175,7 +174,7 @@ describe('GitStatusCommand', () => { ]); vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); - const result = await statusCommand.execute(['--short']); + const result = await statusCommand.execute(['--short'], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('?? untracked.txt'); @@ -191,7 +190,7 @@ describe('GitStatusCommand', () => { ]); vi.mocked(mockGit.currentBranch).mockResolvedValue('feature-branch'); - const result = await statusCommand.execute([]); + const result = await statusCommand.execute([], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('On branch feature-branch'); @@ -209,7 +208,7 @@ describe('GitStatusCommand', () => { vi.mocked(mockGit.statusMatrix).mockResolvedValue([]); vi.mocked(mockGit.currentBranch).mockResolvedValue(undefined); - const result = await statusCommand.execute([]); + const result = await statusCommand.execute([], testCwd); expect(result.exitCode).toBe(0); expect(result.stdout).toContain('HEAD detached at unknown'); diff --git a/src/lib/commands/git/status.ts b/src/lib/commands/git/status.ts index 39bff1b3..71a91baa 100644 --- a/src/lib/commands/git/status.ts +++ b/src/lib/commands/git/status.ts @@ -11,19 +11,18 @@ export class GitStatusCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { + // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -32,23 +31,23 @@ export class GitStatusCommand implements GitSubcommand { // Get the status matrix const statusMatrix = await this.git.statusMatrix({ - dir: this.pwd, + dir: cwd, }); // Get current branch let currentBranch: string | null = null; try { currentBranch = await this.git.currentBranch({ - dir: this.pwd, + dir: cwd, }) || null; } catch { // Might be an empty repository } if (options.porcelain || options.short) { - return this.formatPorcelainStatus(statusMatrix); + return this.formatPorcelainStatus(statusMatrix, cwd); } else { - return this.formatHumanStatus(statusMatrix, currentBranch); + return this.formatHumanStatus(statusMatrix, currentBranch, cwd); } } catch (error) { @@ -70,7 +69,7 @@ export class GitStatusCommand implements GitSubcommand { return options; } - private formatPorcelainStatus(statusMatrix: Array<[string, number, number, number]>): ShellCommandResult { + private formatPorcelainStatus(statusMatrix: Array<[string, number, number, number]>, _cwd: string): ShellCommandResult { const lines: string[] = []; for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { @@ -108,7 +107,7 @@ export class GitStatusCommand implements GitSubcommand { return createSuccessResult(lines.join('\n') + (lines.length > 0 ? '\n' : '')); } - private formatHumanStatus(statusMatrix: Array<[string, number, number, number]>, currentBranch: string | null): ShellCommandResult { + private formatHumanStatus(statusMatrix: Array<[string, number, number, number]>, currentBranch: string | null, _cwd: string): ShellCommandResult { const lines: string[] = []; // Show current branch @@ -186,4 +185,4 @@ export class GitStatusCommand implements GitSubcommand { lines.push(''); return createSuccessResult(lines.join('\n')); } -} \ No newline at end of file +} diff --git a/src/lib/commands/git/tag.ts b/src/lib/commands/git/tag.ts index 158e4fed..e7c8ab06 100644 --- a/src/lib/commands/git/tag.ts +++ b/src/lib/commands/git/tag.ts @@ -12,19 +12,17 @@ export class GitTagCommand implements GitSubcommand { private git: Git; private fs: JSRuntimeFS; - private pwd: string; constructor(options: GitSubcommandOptions) { this.git = options.git; this.fs = options.fs; - this.pwd = options.pwd; } - async execute(args: string[]): Promise { + async execute(args: string[], cwd: string): Promise { try { // Check if we're in a git repository try { - await this.fs.stat(`${this.pwd}/.git`); + await this.fs.stat(`${cwd}/.git`); } catch { return createErrorResult('fatal: not a git repository (or any of the parent directories): .git'); } @@ -33,13 +31,13 @@ export class GitTagCommand implements GitSubcommand { switch (action) { case 'list': - return await this.listTags(); + return await this.listTags(cwd); case 'create': - return await this.createTag(tagName!, commit); + return await this.createTag(tagName!, cwd, commit); case 'delete': - return await this.deleteTag(tagName!); + return await this.deleteTag(tagName!, cwd); default: - return await this.listTags(); + return await this.listTags(cwd); } } catch (error) { @@ -84,10 +82,10 @@ export class GitTagCommand implements GitSubcommand { return { action, tagName, commit, options }; } - private async listTags(): Promise { + private async listTags(cwd: string): Promise { try { const tags = await this.git.listTags({ - dir: this.pwd, + dir: cwd, }); if (tags.length === 0) { @@ -104,7 +102,7 @@ export class GitTagCommand implements GitSubcommand { } } - private async createTag(tagName: string, commit?: string): Promise { + private async createTag(tagName: string, cwd: string, commit?: string): Promise { try { if (!tagName) { return createErrorResult('usage: git tag []'); @@ -113,8 +111,7 @@ export class GitTagCommand implements GitSubcommand { // Check if tag already exists try { const tags = await this.git.listTags({ - - dir: this.pwd, + dir: cwd, }); if (tags.includes(tagName)) { @@ -128,8 +125,7 @@ export class GitTagCommand implements GitSubcommand { let targetOid: string; try { targetOid = await this.git.resolveRef({ - - dir: this.pwd, + dir: cwd, ref: commit || 'HEAD', }); } catch { @@ -138,7 +134,7 @@ export class GitTagCommand implements GitSubcommand { // Create the tag await this.git.tag({ - dir: this.pwd, + dir: cwd, ref: tagName, object: targetOid, }); @@ -150,7 +146,7 @@ export class GitTagCommand implements GitSubcommand { } } - private async deleteTag(tagName: string): Promise { + private async deleteTag(tagName: string, cwd: string): Promise { try { if (!tagName) { return createErrorResult('usage: git tag -d '); @@ -159,8 +155,7 @@ export class GitTagCommand implements GitSubcommand { // Check if tag exists try { const tags = await this.git.listTags({ - - dir: this.pwd, + dir: cwd, }); if (!tags.includes(tagName)) { @@ -172,7 +167,7 @@ export class GitTagCommand implements GitSubcommand { // Delete the tag await this.git.deleteTag({ - dir: this.pwd, + dir: cwd, ref: tagName, }); @@ -182,4 +177,4 @@ export class GitTagCommand implements GitSubcommand { return createErrorResult(`Failed to delete tag: ${error instanceof Error ? error.message : 'Unknown error'}`); } } -} \ No newline at end of file +} diff --git a/src/lib/configUtils.test.ts b/src/lib/configUtils.test.ts index eb6529c1..9e3e5b9f 100644 --- a/src/lib/configUtils.test.ts +++ b/src/lib/configUtils.test.ts @@ -74,7 +74,10 @@ describe('configUtils', () => { const result = await readAISettings(mockFS); expect(mockFS.readFile).toHaveBeenCalledWith('/config/ai.json', 'utf8'); - expect(result).toEqual(sampleAISettings); + expect(result).toEqual({ + ...sampleAISettings, + mcpServers: {}, + }); }); it('should return default settings if file does not exist and no localStorage data', async () => { @@ -86,6 +89,7 @@ describe('configUtils', () => { expect(result).toEqual({ providers: [], recentlyUsedModels: [], + mcpServers: {}, }); }); @@ -98,6 +102,7 @@ describe('configUtils', () => { expect(result).toEqual({ providers: [], recentlyUsedModels: [], + mcpServers: {}, }); }); }); diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts index 12ce1b2c..ca9291a8 100644 --- a/src/lib/configUtils.ts +++ b/src/lib/configUtils.ts @@ -1,7 +1,7 @@ import z from 'zod'; import { filteredArray } from '@/lib/schema'; import type { JSRuntimeFS } from '@/lib/JSRuntime'; -import type { AIProvider, AISettings } from '@/contexts/AISettingsContext'; +import type { AIProvider, AISettings, MCPServer } from '@/contexts/AISettingsContext'; import type { GitSettings } from '@/contexts/GitSettingsContext'; import type { DeployProvider, DeploySettings } from '@/contexts/DeploySettingsContext'; @@ -42,9 +42,16 @@ const providerModelSchema = z.string().regex( 'Must be in format provider/model (e.g., "openai/gpt-4o")', ); +const mcpServerSchema: z.ZodType = z.object({ + type: z.literal('streamable-http'), + url: z.string().url(), + headers: z.record(z.string(), z.string()).optional(), +}); + const aiSettingsSchema = z.object({ providers: filteredArray(aiProviderSchema), recentlyUsedModels: filteredArray(providerModelSchema), + mcpServers: z.record(z.string(), mcpServerSchema).optional(), }); const gitCredentialSchema = z.object({ @@ -130,13 +137,19 @@ export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): P const defaultSettings: AISettings = { providers: [], recentlyUsedModels: [], + mcpServers: {}, }; try { const aiConfigPath = getAIConfigPath(configPath); const content = await fs.readFile(aiConfigPath, 'utf8'); const data = JSON.parse(content); - return aiSettingsSchema.parse(data); + const parsed = aiSettingsSchema.parse(data); + // Ensure mcpServers exists even if not in parsed data + return { + ...parsed, + mcpServers: parsed.mcpServers || {}, + }; } catch (error) { if (error instanceof z.ZodError) { console.error('AI settings parsing error:', error.errors); diff --git a/src/lib/git.ts b/src/lib/git.ts index 79a9d6af..842c3abd 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -1,4 +1,4 @@ -import git, { GitHttpRequest, GitHttpResponse, HttpClient } from 'isomorphic-git'; +import git, { FetchResult, GitHttpRequest, GitHttpResponse, HttpClient } from 'isomorphic-git'; import { NIP05 } from '@nostrify/nostrify'; import { nip19 } from 'nostr-tools'; import { proxyUrl } from './proxyUrl'; @@ -1615,7 +1615,7 @@ export class Git { return differences; } - private async nostrFetch(nostrUrl: string, options: Omit[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise<{ fetchHead?: string; fetchHeadDescription?: string }> { + private async nostrFetch(nostrUrl: string, options: Omit[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise { // Parse the Nostr URI const nostrURI = await this.parseNostrCloneURI(nostrUrl); if (!nostrURI) { @@ -1629,7 +1629,7 @@ export class Git { // If we have a state event, update our refs to match if (state) { - const foundAllData = async () => { + const foundAllData = async (): Promise => { // identify out-of-sync grasp servers are in sync const cloneURLsStates = await this.listFromCloneUrls(repo); const outOfSyncRefsPerCloneUrl = this.nostrIdentifyCloneUrlStateDifferences(state, cloneURLsStates); @@ -1657,8 +1657,9 @@ export class Git { ); return { - fetchHead: state.headCommit, + fetchHead: state.headCommit || null, fetchHeadDescription: `Fetched from Nostr repository state`, + defaultBranch: state.headBranch || null, }; }; @@ -2002,7 +2003,7 @@ export class Git { } /* just fetching the branches and tags so some refs (eg refs/nostr/) wont be fetched (unless the remote refspec specifies?) */ - private async nostrFetchDataFromGitRemote(httpsCloneUrl:string, dir: string): Promise<{ fetchHead?: string; fetchHeadDescription?: string }> { + private async nostrFetchDataFromGitRemote(httpsCloneUrl:string, dir: string): Promise { try { console.log(`Fetching from Git remote: ${httpsCloneUrl}`); @@ -2033,8 +2034,9 @@ export class Git { }); return { - fetchHead: fetchResult.fetchHead || undefined, + fetchHead: fetchResult.fetchHead || null, fetchHeadDescription: `Fetched from Git remote: ${httpsCloneUrl}`, + defaultBranch: fetchResult.defaultBranch || null, }; } catch (fetchError) { // Clean up the temporary remote diff --git a/src/lib/system.test.ts b/src/lib/system.test.ts index 9827a370..237b7fbc 100644 --- a/src/lib/system.test.ts +++ b/src/lib/system.test.ts @@ -40,6 +40,7 @@ const testConfig: AppConfig = { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', sentryDsn: '', sentryEnabled: false, }; diff --git a/src/lib/system.ts b/src/lib/system.ts index 08e64133..e7758e8c 100644 --- a/src/lib/system.ts +++ b/src/lib/system.ts @@ -200,11 +200,11 @@ This project has a repository URL configured, so you can create an "Edit with Sh Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use \`height: auto\` in CSS (or \`"h-auto"\` in Tailwind CSS) when applicable.{% else %} -**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}{% if readmeText %} +**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}{% if README %} -{{ readmeText }}{% endif %}{% if agentsText %} +{{ README }}{% endif %}{% if AGENTS %} -{{ agentsText }}{% endif %}`; +{{ AGENTS }}{% endif %}`; export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise { const { tools, mode, fs, cwd, config, defaultConfig, user, metadata, repositoryUrl, template } = opts; @@ -286,8 +286,8 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise> { + description: string; + private client: MCPClient; + private originalToolName: string; + + constructor( + description: string, + client: MCPClient, + originalToolName: string + ) { + this.description = description; + this.client = client; + this.originalToolName = originalToolName; + } + + async execute(args: Record): Promise { + return await this.client.callTool(this.originalToolName, args); + } +} + +/** + * Create MCPTool instances from discovered MCP tools. + */ +export function createMCPTools( + clients: Record +): Record> { + const tools: Record> = {}; + + for (const [prefixedName, client] of Object.entries(clients)) { + // Extract original tool name by removing server prefix + const parts = prefixedName.split('__'); + const originalToolName = parts.slice(1).join('__'); + + tools[prefixedName] = new MCPTool( + `MCP tool: ${prefixedName}`, + client, + originalToolName + ); + } + + return tools; +} diff --git a/src/lib/tools/ShellTool.test.ts b/src/lib/tools/ShellTool.test.ts index 3eca52e6..64f3dae1 100644 --- a/src/lib/tools/ShellTool.test.ts +++ b/src/lib/tools/ShellTool.test.ts @@ -41,7 +41,7 @@ describe('ShellTool', () => { mockFS = createMockFS(); mockNostr = createMockNostr(); mockGit = new Git({ fs: mockFS, nostr: mockNostr }); - shellTool = new ShellTool(mockFS, testCwd, mockGit, '/projects', testCorsProxy); + shellTool = new ShellTool(mockFS, testCwd, mockGit, testCorsProxy); }); it('should have correct tool properties', () => { diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index a312fb1b..8679bb36 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -51,7 +51,6 @@ export class ShellTool implements Tool { private cwd: string; private git: Git; private commands: Map; - private projectsPath: string; private signer?: NostrSigner; private corsProxy: string; @@ -63,11 +62,10 @@ export class ShellTool implements Tool { ), }); - constructor(fs: JSRuntimeFS, cwd: string, git: Git, projectsPath: string = '/projects', corsProxy: string, signer?: NostrSigner) { + constructor(fs: JSRuntimeFS, cwd: string, git: Git, corsProxy: string, signer?: NostrSigner) { this.fs = fs; this.cwd = cwd; this.git = git; - this.projectsPath = projectsPath; this.corsProxy = corsProxy; this.signer = signer; this.commands = new Map(); diff --git a/src/locales/en.json b/src/locales/en.json index 8f88ef58..d1846ce4 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -11,7 +11,7 @@ "themeDescription": "Choose between light, dark, or system theme preference.", "language": "Language", "languageDescription": "Select your preferred language for the interface.", - "systemSettings": "System Settings", + "systemSettings": "System", "systemSettingsDescription": "Configure system-level settings and advanced options.", "esmUrl": "Javascript CDN", "esmUrlDescription": "Javascript CDN URL for package imports.", @@ -95,14 +95,14 @@ "selectModelToDescribe": "Please select a model below, then describe what you'd like to build...", "examplePrompt": "e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies...", "settingsDescription": "Manage your application settings and preferences.", - "aiSettings": "AI Settings", + "aiSettings": "AI", "aiSettingsDescription": "Configure AI providers and API keys", - "gitSettings": "Git Settings", + "gitSettings": "Git", "gitSettingsDescription": "Configure Git credentials for HTTP authentication", "deploySettings": "Deployment", "deploySettingsDescription": "Configure deployment providers", "deploySettingsDescriptionLong": "Configure deployment providers to deploy your projects to various hosting platforms.", - "nostrSettings": "Nostr Settings", + "nostrSettings": "Nostr", "nostrSettingsDescription": "Configure relay connections and Nostr preferences", "storageSettings": "Storage", "storageSettingsDescription": "Export files and manage local data", @@ -478,6 +478,26 @@ "noPluginsConfigured": "No plugins configured. Add a plugin to get started.", "pluginsDirectory": "Plugins Directory", "pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.", + "mcpServers": "MCP Servers", + "mcpServersDescription": "Connect to Model Context Protocol servers to extend the AI's capabilities with external tools.", + "addMcpServer": "Add MCP Server", + "mcpServerName": "Server Name", + "mcpServerUrl": "Server URL", + "mcpServerType": "Server Type", + "mcpServerTypeStreamableHttp": "Streamable HTTP", + "mcpServerDescription": "MCP servers provide tools that can be discovered and used by the AI assistant.", + "noMcpServersConfigured": "No MCP servers configured. Add a server to get started.", + "mcpServerAdded": "MCP Server Added", + "mcpServerAddedDescription": "MCP server \"{{name}}\" has been added successfully.", + "mcpServerAddFailed": "Failed to Add MCP Server", + "mcpServerDeleted": "MCP Server Deleted", + "mcpServerDeletedDescription": "MCP server \"{{name}}\" has been deleted successfully.", + "mcpServerDeleteFailed": "Failed to Delete MCP Server", + "mcpServerHeaders": "Headers", + "mcpServerHeadersDescription": "Add custom HTTP headers to be sent with requests to this MCP server (e.g., Authorization headers).", + "discoveringTools": "Discovering tools...", + "toolsDiscovered": "{{count}} tool(s) discovered", + "toolDiscoveryFailed": "Failed to discover tools from this server", "filesystemPaths": "Filesystem Paths", "projectsDirectory": "Projects Directory", "projectsDirectoryDescription": "Directory where projects are stored in the virtual filesystem.", @@ -488,5 +508,10 @@ "deleting": "Deleting...", "modified": "Modified", "restoreToDefault": "Restore to default", - "restoredToDefault": "Restored to Default" + "restoredToDefault": "Restored to Default", + "templateUpdateFailed": "Template Update Failed", + "templateUpdateFailedDescription": "Failed to update the project template from the remote repository. Using the cached version instead.", + "templatesDirectory": "Templates Directory", + "templatesDirectoryDescription": "Directory where project templates are cached in the virtual filesystem.", + "terminal": "Terminal" } diff --git a/src/locales/ha.json b/src/locales/ha.json index 54be4ae1..e7417980 100644 --- a/src/locales/ha.json +++ b/src/locales/ha.json @@ -11,7 +11,7 @@ "themeDescription": "Zaɓi tsakanin haske, duhu, ko zaɓin jigogi na tsarin.", "language": "Harshe", "languageDescription": "Zaɓi harshen da kuke so don dubawa.", - "systemSettings": "Saitunan Tsarin", + "systemSettings": "Tsarin", "systemSettingsDescription": "Saita saitunan matakin tsari da zaɓuɓɓuka na ci gaba.", "esmUrl": "URL na CDN Javascript", "esmUrlDescription": "URL na CDN Javascript don shigo da fakitin.", @@ -91,11 +91,11 @@ "selectModelToDescribe": "Da fatan za a zaɓi samfuri a ƙasa, sannan a bayyana abin da kuke son ginawa...", "examplePrompt": "misali, Ƙirƙiri kasuwar kayan aikin noma don manoma na yankin su sayi da sayar da taraktoci, kayan aiki, da kayayyaki...", "settingsDescription": "Sarrafa saitunan aikace-aikacenku da zaɓuɓɓuka.", - "aiSettings": "Saitunan AI", + "aiSettings": "AI", "aiSettingsDescription": "Saita masu samar da AI da maɓallan API", - "gitSettings": "Saitunan Git", + "gitSettings": "Git", "gitSettingsDescription": "Saita bayanan shaidar Git don tabbatar da HTTP", - "nostrSettings": "Saitunan Nostr", + "nostrSettings": "Nostr", "nostrSettingsDescription": "Saita haɗin relay da zaɓuɓɓukan Nostr", "storageSettings": "Ajiya", "storageSettingsDescription": "Fitar da fayiloli da sarrafa bayanan gida", @@ -427,5 +427,6 @@ "giftCardAlreadyRedeemed": "An riga an fanshi wannan katin kyauta.", "modified": "An Canza", "restoreToDefault": "Mayar da asali", - "restoredToDefault": "An Mayar da Asali" + "restoredToDefault": "An Mayar da Asali", + "terminal": "Terminal" } diff --git a/src/locales/ig.json b/src/locales/ig.json index 922b34b9..1bab6623 100644 --- a/src/locales/ig.json +++ b/src/locales/ig.json @@ -11,7 +11,7 @@ "themeDescription": "Họrọ n'etiti ìhè, ọchịchịrị, ma ọ bụ nhọrọ isiokwu sistemu.", "language": "Asụsụ", "languageDescription": "Họrọ asụsụ ị chọrọ maka interface.", - "systemSettings": "Ntọala Sistemu", + "systemSettings": "Sistemu", "systemSettingsDescription": "Hazie ntọala ọkwa sistemu na nhọrọ ndị ọganihu.", "esmUrl": "URL CDN Javascript", "esmUrlDescription": "URL CDN Javascript maka mbubata ngwugwu.", @@ -91,11 +91,11 @@ "selectModelToDescribe": "Biko họrọ ụdịdị n'okpuru, wee kọwaa ihe ị chọrọ iwu...", "examplePrompt": "ọmụmaatụ, Mepụta ahịa ngwá ọrụ ugbo maka ndị ọrụ ugbo mpaghara ịzụta na ire traktọ, ngwá ọrụ, na ngwa...", "settingsDescription": "Jikwaa ntọala ngwa gị na nhọrọ.", - "aiSettings": "Ntọala AI", + "aiSettings": "AI", "aiSettingsDescription": "Hazie ndị na-enye AI na igodo API", - "gitSettings": "Ntọala Git", + "gitSettings": "Git", "gitSettingsDescription": "Hazie nzere Git maka nkwenye HTTP", - "nostrSettings": "Ntọala Nostr", + "nostrSettings": "Nostr", "nostrSettingsDescription": "Hazie njikọ relay na nhọrọ Nostr", "storageSettings": "Nchekwa", "storageSettingsDescription": "Bupụta faịlụ na jikwaa data mpaghara", @@ -424,5 +424,6 @@ "giftCardAlreadyRedeemed": "Egbapụtalarị kaadị onyinye a.", "modified": "Gbanwere", "restoreToDefault": "Weghachi na nke mbụ", - "restoredToDefault": "Weghachiri na Nke Mbụ" + "restoredToDefault": "Weghachiri na Nke Mbụ", + "terminal": "Terminal" } diff --git a/src/locales/pt.json b/src/locales/pt.json index 3b9bc08a..9001b49f 100644 --- a/src/locales/pt.json +++ b/src/locales/pt.json @@ -11,7 +11,7 @@ "themeDescription": "Escolha entre preferência de tema claro, escuro ou do sistema.", "language": "Idioma", "languageDescription": "Selecione seu idioma preferido para a interface.", - "systemSettings": "Configurações do Sistema", + "systemSettings": "Sistema", "systemSettingsDescription": "Configure configurações de nível de sistema e opções avançadas.", "esmUrl": "URL do CDN Javascript", "esmUrlDescription": "URL do CDN Javascript para importações de pacotes.", @@ -91,14 +91,14 @@ "selectModelToDescribe": "Por favor, selecione um modelo abaixo e depois descreva o que gostaria de construir...", "examplePrompt": "ex., Criar um marketplace de equipamentos agrícolas para fazendeiros locais comprarem e venderem tratores, ferramentas e suprimentos...", "settingsDescription": "Gerencie as configurações e preferências da aplicação.", - "aiSettings": "Configurações de IA", + "aiSettings": "IA", "aiSettingsDescription": "Configure provedores de IA e chaves de API", - "gitSettings": "Configurações do Git", + "gitSettings": "Git", "gitSettingsDescription": "Configure credenciais do Git para autenticação HTTP", "deploySettings": "Implantação", "deploySettingsDescription": "Configure provedores de implantação", "deploySettingsDescriptionLong": "Configure provedores de implantação para implantar seus projetos em várias plataformas de hospedagem.", - "nostrSettings": "Configurações do Nostr", + "nostrSettings": "Nostr", "nostrSettingsDescription": "Configure conexões de relay e preferências do Nostr", "storageSettings": "Armazenamento", "storageSettingsDescription": "Exporte arquivos e gerencie dados locais", @@ -437,5 +437,6 @@ "giftCardAlreadyRedeemed": "Este cartão presente já foi resgatado.", "modified": "Modificado", "restoreToDefault": "Restaurar para padrão", - "restoredToDefault": "Restaurado para Padrão" + "restoredToDefault": "Restaurado para Padrão", + "terminal": "Terminal" } diff --git a/src/locales/yo.json b/src/locales/yo.json index 916f7618..f0ee7f49 100644 --- a/src/locales/yo.json +++ b/src/locales/yo.json @@ -11,7 +11,7 @@ "themeDescription": "Yan laarin imọlẹ, okunkun, tabi ayanfẹ akori eto.", "language": "Ede", "languageDescription": "Yan ede ti o fẹran fun wiwo.", - "systemSettings": "Saitunan Eto", + "systemSettings": "Eto", "systemSettingsDescription": "Tunto awọn saitan eto ati awọn ayanfẹ ti o pọju.", "esmUrl": "URL CDN Javascript", "esmUrlDescription": "URL CDN Javascript fun gbigbe awọn package.", @@ -91,11 +91,11 @@ "selectModelToDescribe": "Jọwọ yan awoṣe ni isalẹ, lẹhinna ṣapejuwe ohun ti o fẹ kọ...", "examplePrompt": "apeere, Ṣẹda ọja ẹrọ ogbin fun awọn agbe agbegbe lati ra ati ta awọn traktọ, awọn irinṣẹ, ati awọn ipese...", "settingsDescription": "Ṣakoso awọn eto ohun elo rẹ ati awọn ayanfẹ.", - "aiSettings": "Awọn eto AI", + "aiSettings": "AI", "aiSettingsDescription": "Tunto awọn olupese AI ati awọn bọtini API", - "gitSettings": "Awọn eto Git", + "gitSettings": "Git", "gitSettingsDescription": "Tunto awọn ẹri Git fun ijẹrisi HTTP", - "nostrSettings": "Awọn eto Nostr", + "nostrSettings": "Nostr", "nostrSettingsDescription": "Tunto awọn asopọ relay ati awọn ayanfẹ Nostr", "storageSettings": "Ibi ipamọ", "storageSettingsDescription": "Gbe awọn faili jade ati ṣakoso data agbegbe", @@ -424,5 +424,6 @@ "giftCardAlreadyRedeemed": "A ti ra kaadi ẹbun yii tẹlẹ.", "modified": "Ti Yipada", "restoreToDefault": "Pada si atilẹwa", - "restoredToDefault": "Ti Pada si Atilẹwa" + "restoredToDefault": "Ti Pada si Atilẹwa", + "terminal": "Terminal" } diff --git a/src/locales/zh.json b/src/locales/zh.json index ef097093..12485f3c 100644 --- a/src/locales/zh.json +++ b/src/locales/zh.json @@ -11,7 +11,7 @@ "themeDescription": "选择浅色、深色或系统主题偏好。", "language": "语言", "languageDescription": "选择您的界面首选语言。", - "systemSettings": "系统设置", + "systemSettings": "系统", "systemSettingsDescription": "配置系统级设置和高级选项。", "esmUrl": "Javascript CDN URL", "esmUrlDescription": "包导入的 Javascript CDN URL。", @@ -91,14 +91,14 @@ "selectModelToDescribe": "请在下方选择一个模型,然后描述您想要构建的内容...", "examplePrompt": "例如:为当地农民创建一个农业设备市场,用于买卖拖拉机、工具和用品...", "settingsDescription": "管理您的应用程序设置和偏好。", - "aiSettings": "AI设置", + "aiSettings": "AI", "aiSettingsDescription": "配置AI提供商和API密钥", - "gitSettings": "Git设置", + "gitSettings": "Git", "gitSettingsDescription": "配置HTTP身份验证的Git凭据", "deploySettings": "部署", "deploySettingsDescription": "配置部署提供商", "deploySettingsDescriptionLong": "配置部署提供商以将您的项目部署到各种托管平台。", - "nostrSettings": "Nostr设置", + "nostrSettings": "Nostr", "nostrSettingsDescription": "配置中继连接和Nostr偏好", "storageSettings": "存储", "storageSettingsDescription": "导出文件和管理本地数据", @@ -437,5 +437,6 @@ "giftCardAlreadyRedeemed": "此礼品卡已被兑换。", "modified": "已修改", "restoreToDefault": "恢复默认值", - "restoredToDefault": "已恢复默认值" + "restoredToDefault": "已恢复默认值", + "terminal": "终端" } diff --git a/src/pages/AISettings.tsx b/src/pages/AISettings.tsx index c36ddaca..63635b3c 100644 --- a/src/pages/AISettings.tsx +++ b/src/pages/AISettings.tsx @@ -36,6 +36,7 @@ import { useNavigate, Link } from 'react-router-dom'; import type { AIProvider } from '@/contexts/AISettingsContext'; import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets'; import { ExternalFavicon } from '@/components/ExternalFavicon'; +import { MCPServersSection } from '@/components/MCPServersSection'; import { PluginsSection } from '@/components/PluginsSection'; interface SortableProviderItemProps { @@ -566,6 +567,9 @@ export function AISettings() {
+ {/* MCP Servers Section */} + + {/* Plugins Section */} diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 8a9fd97b..59216fca 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -24,9 +24,11 @@ import { ArrowUp } from 'lucide-react'; import { useSeoMeta } from '@unhead/react'; import { ShakespeareLogo } from '@/components/ShakespeareLogo'; import { AppShowcase } from '@/components/AppShowcase'; +import { useToast } from '@/hooks/useToast'; export default function Index() { const { t } = useTranslation(); + const { toast } = useToast(); const [prompt, setPrompt] = useState(''); const [isCreating, setIsCreating] = useState(false); const [storedPrompt, setStoredPrompt] = useLocalStorage('shakespeare-draft-prompt', ''); @@ -227,8 +229,20 @@ export default function Index() { // Add model to recently used when creating project with AI addRecentlyUsedModel(providerModel.trim()); - // Create project with AI-generated ID - const project = await projectsManager.createProject(prompt.trim(), config.projectTemplate, projectId); + // Create project with AI-generated ID and handle template update errors + const project = await projectsManager.createProject( + prompt.trim(), + config.projectTemplate, + projectId, + () => { + // Show a toast if template update fails (non-critical) + toast({ + title: t('templateUpdateFailed'), + description: t('templateUpdateFailedDescription'), + variant: 'default', + }); + } + ); // Build message content from input and attached files // Images are converted to base64-encoded data URLs diff --git a/src/pages/SystemSettings.tsx b/src/pages/SystemSettings.tsx index 381b1087..0c46aaa3 100644 --- a/src/pages/SystemSettings.tsx +++ b/src/pages/SystemSettings.tsx @@ -13,6 +13,7 @@ import { useAppContext } from "@/hooks/useAppContext"; import { useOffline } from "@/hooks/useOffline"; import { useToast } from "@/hooks/useToast"; import { defaultSystemPrompt } from "@/lib/system"; +import { Terminal } from "@/components/Terminal"; export function SystemSettings() { const { t } = useTranslation(); @@ -32,6 +33,7 @@ export function SystemSettings() { const [fsPathConfigInput, setFsPathConfigInput] = useState(config.fsPathConfig); const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp); const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins); + const [fsPathTemplatesInput, setFsPathTemplatesInput] = useState(config.fsPathTemplates); const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn); const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt); @@ -48,86 +50,134 @@ export function SystemSettings() { fsPathConfig: config.fsPathConfig !== defaultConfig.fsPathConfig, fsPathTmp: config.fsPathTmp !== defaultConfig.fsPathTmp, fsPathPlugins: config.fsPathPlugins !== defaultConfig.fsPathPlugins, + fsPathTemplates: config.fsPathTemplates !== defaultConfig.fsPathTemplates, sentryDsn: config.sentryDsn !== defaultConfig.sentryDsn, systemPrompt: (config.systemPrompt || defaultSystemPrompt) !== (defaultConfig.systemPrompt || defaultSystemPrompt), }), [config, defaultConfig]); - // Restore functions + // Restore functions - clear the value from config to use the default const restoreProjectTemplate = () => { const defaultValue = defaultConfig.projectTemplate; setProjectTemplateInput(defaultValue); - updateConfig((current) => ({ ...current, projectTemplate: defaultValue })); + updateConfig((current) => { + const { projectTemplate, ...rest } = current; + return rest; + }); }; const restoreEsmUrl = () => { const defaultValue = defaultConfig.esmUrl; setEsmUrlInput(defaultValue); - updateConfig((current) => ({ ...current, esmUrl: defaultValue })); + updateConfig((current) => { + const { esmUrl, ...rest } = current; + return rest; + }); }; const restoreCorsProxy = () => { const defaultValue = defaultConfig.corsProxy; setCorsProxyInput(defaultValue); - updateConfig((current) => ({ ...current, corsProxy: defaultValue })); + updateConfig((current) => { + const { corsProxy, ...rest } = current; + return rest; + }); }; const restoreFaviconUrl = () => { const defaultValue = defaultConfig.faviconUrl; setFaviconUrlInput(defaultValue); - updateConfig((current) => ({ ...current, faviconUrl: defaultValue })); + updateConfig((current) => { + const { faviconUrl, ...rest } = current; + return rest; + }); }; const restorePreviewDomain = () => { const defaultValue = defaultConfig.previewDomain; setPreviewDomainInput(defaultValue); - updateConfig((current) => ({ ...current, previewDomain: defaultValue })); + updateConfig((current) => { + const { previewDomain, ...rest } = current; + return rest; + }); }; const restoreShowcaseEnabled = () => { - const defaultValue = defaultConfig.showcaseEnabled; - updateConfig((current) => ({ ...current, showcaseEnabled: defaultValue })); + updateConfig((current) => { + const { showcaseEnabled, ...rest } = current; + return rest; + }); }; const restoreShowcaseModerator = () => { const defaultValue = defaultConfig.showcaseModerator; setShowcaseModeratorInput(defaultValue); - updateConfig((current) => ({ ...current, showcaseModerator: defaultValue })); + updateConfig((current) => { + const { showcaseModerator, ...rest } = current; + return rest; + }); }; const restoreFsPathProjects = () => { const defaultValue = defaultConfig.fsPathProjects; setFsPathProjectsInput(defaultValue); - updateConfig((current) => ({ ...current, fsPathProjects: defaultValue })); + updateConfig((current) => { + const { fsPathProjects, ...rest } = current; + return rest; + }); }; const restoreFsPathConfig = () => { const defaultValue = defaultConfig.fsPathConfig; setFsPathConfigInput(defaultValue); - updateConfig((current) => ({ ...current, fsPathConfig: defaultValue })); + updateConfig((current) => { + const { fsPathConfig, ...rest } = current; + return rest; + }); }; const restoreFsPathTmp = () => { const defaultValue = defaultConfig.fsPathTmp; setFsPathTmpInput(defaultValue); - updateConfig((current) => ({ ...current, fsPathTmp: defaultValue })); + updateConfig((current) => { + const { fsPathTmp, ...rest } = current; + return rest; + }); }; const restoreFsPathPlugins = () => { const defaultValue = defaultConfig.fsPathPlugins; setFsPathPluginsInput(defaultValue); - updateConfig((current) => ({ ...current, fsPathPlugins: defaultValue })); + updateConfig((current) => { + const { fsPathPlugins, ...rest } = current; + return rest; + }); + }; + + const restoreFsPathTemplates = () => { + const defaultValue = defaultConfig.fsPathTemplates; + setFsPathTemplatesInput(defaultValue); + updateConfig((current) => { + const { fsPathTemplates, ...rest } = current; + return rest; + }); }; const restoreSentryDsn = () => { const defaultValue = defaultConfig.sentryDsn; setSentryDsnInput(defaultValue); - updateConfig((current) => ({ ...current, sentryDsn: defaultValue })); + updateConfig((current) => { + const { sentryDsn, ...rest } = current; + return rest; + }); }; const restoreSystemPrompt = () => { const defaultValue = defaultSystemPrompt; setSystemPromptInput(defaultValue); - updateConfig((current) => ({ ...current, systemPrompt: defaultValue })); + updateConfig((current) => { + const { systemPrompt, ...rest } = current; + return rest; + }); }; // Service Worker state @@ -748,7 +798,7 @@ export function SystemSettings() {

{t('filesystemPaths')}

- {(isModified.fsPathProjects || isModified.fsPathConfig || isModified.fsPathTmp || isModified.fsPathPlugins) && ( + {(isModified.fsPathProjects || isModified.fsPathConfig || isModified.fsPathTmp || isModified.fsPathPlugins || isModified.fsPathTemplates) && (
)}
@@ -918,6 +968,47 @@ export function SystemSettings() { {t('pluginsDirectoryDescription')}

+ +
+
+ + {isModified.fsPathTemplates && ( +
+ )} +
+
+ { + const value = e.target.value; + setFsPathTemplatesInput(value); + updateConfig((current) => ({ + ...current, + fsPathTemplates: value, + })); + }} + className="flex-1" + /> + {isModified.fsPathTemplates && ( + + )} +
+

+ {t('templatesDirectoryDescription')} +

+
@@ -969,6 +1060,22 @@ export function SystemSettings() { + + {/* Terminal */} + + + +
+

{t('terminal')}

+
+
+ +
+ +
+
+
+
); diff --git a/src/test/TestApp.tsx b/src/test/TestApp.tsx index 3548f159..1eb4e141 100644 --- a/src/test/TestApp.tsx +++ b/src/test/TestApp.tsx @@ -48,6 +48,7 @@ export function TestApp({ children }: TestAppProps) { fsPathConfig: '/config', fsPathTmp: '/tmp', fsPathPlugins: '/plugins', + fsPathTemplates: '/templates', sentryDsn: '', sentryEnabled: false, };