mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-12-03 08:10:27 +00:00
Merge origin/main into feat/screenshot-targets
This commit is contained in:
Generated
+9
-9
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@windmill-labs/components",
|
||||
"version": "1.882.0",
|
||||
"version": "1.894.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@windmill-labs/components",
|
||||
"version": "1.882.0",
|
||||
"version": "1.894.1",
|
||||
"hasInstallScript": true,
|
||||
"license": "AGPL-3.0",
|
||||
"dependencies": {
|
||||
@@ -96,6 +96,7 @@
|
||||
"tailwind-merge": "^1.13.2",
|
||||
"unified": "^11.0.5",
|
||||
"unist-util-visit": "^5.0.0",
|
||||
"uqr": "^0.1.3",
|
||||
"vscode": "npm:@codingame/monaco-vscode-extension-api@=25.0.0",
|
||||
"vscode-languageclient": "~9.0.1",
|
||||
"vscode-uri": "~3.1.0",
|
||||
@@ -115,7 +116,6 @@
|
||||
"windmill-parser-wasm-wac": "1.830.0",
|
||||
"windmill-parser-wasm-yaml": "1.770.0",
|
||||
"windmill-sql-datatype-parser-wasm": "1.512.0",
|
||||
"windmill-utils-internal": "1.8.6",
|
||||
"xterm": "^5.3.0",
|
||||
"xterm-readline": "^1.1.2",
|
||||
"y-monaco": "^0.1.4",
|
||||
@@ -13446,6 +13446,12 @@
|
||||
"browserslist": ">= 4.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/uqr": {
|
||||
"version": "0.1.3",
|
||||
"resolved": "https://registry.npmjs.org/uqr/-/uqr-0.1.3.tgz",
|
||||
"integrity": "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/uri-js": {
|
||||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
|
||||
@@ -14140,12 +14146,6 @@
|
||||
"resolved": "https://registry.npmjs.org/windmill-sql-datatype-parser-wasm/-/windmill-sql-datatype-parser-wasm-1.512.0.tgz",
|
||||
"integrity": "sha512-uHNL8F72/Tf96xF3hOHnPDjkEyqXw7fNjcPJiUhth9sTQkcwUIoJMOdwm8/cs+j9kKVRJ4tgNYMHEBLylazp6g=="
|
||||
},
|
||||
"node_modules/windmill-utils-internal": {
|
||||
"version": "1.8.6",
|
||||
"resolved": "https://registry.npmjs.org/windmill-utils-internal/-/windmill-utils-internal-1.8.6.tgz",
|
||||
"integrity": "sha512-jzHhEZ3xSBf90zektXaAIhAu9wLo5RMtYshvjg5if8jjEJvWENd+WQzEbod8Sr+SzMUbmmF4ArefqN15f2XtHw==",
|
||||
"license": "Apache 2.0"
|
||||
},
|
||||
"node_modules/wordwrap": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@windmill-labs/components",
|
||||
"version": "1.882.0",
|
||||
"version": "1.894.1",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"dev:ui-builder": "mv static/ui_builder static/ui_builder.dev-disabled 2>/dev/null || true ; trap 'mv static/ui_builder.dev-disabled static/ui_builder 2>/dev/null || true' EXIT ; vite dev",
|
||||
@@ -15,8 +15,8 @@
|
||||
"format:check": "prettier --ignore-path .gitignore --check --plugin-search-dir=. .",
|
||||
"format": "prettier --ignore-path .gitignore --write --plugin-search-dir=. .",
|
||||
"package": "svelte-package -o package && node scripts/package-system-prompts.js && node scripts/fix-svelte-module-imports.js",
|
||||
"generate-backend-client": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --useOptions --enums javascript --format false",
|
||||
"generate-backend-client-mac": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --useOptions --enums javascript",
|
||||
"generate-backend-client": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --request ./scripts/openapi-ts-request.ts --useOptions --enums javascript --format false",
|
||||
"generate-backend-client-mac": "openapi-ts --input ../backend/windmill-api/openapi.yaml --output ./src/lib/gen --request ./scripts/openapi-ts-request.ts --useOptions --enums javascript",
|
||||
"gen:display-catalog": "WM_GEN_DISPLAY_CATALOG=1 vitest run --project server src/lib/components/display/displayCatalogGen.test.ts",
|
||||
"gen:mcp-session": "WM_GEN_MCP_SESSION=1 vitest run --project server src/lib/components/copilot/chat/global/mcpSessionGen.test.ts",
|
||||
"pretest": "tsc --incremental -p tests/tsconfig.json",
|
||||
@@ -161,6 +161,7 @@
|
||||
"tailwind-merge": "^1.13.2",
|
||||
"unified": "^11.0.5",
|
||||
"unist-util-visit": "^5.0.0",
|
||||
"uqr": "^0.1.3",
|
||||
"vscode": "npm:@codingame/monaco-vscode-extension-api@=25.0.0",
|
||||
"vscode-languageclient": "~9.0.1",
|
||||
"vscode-uri": "~3.1.0",
|
||||
@@ -180,7 +181,6 @@
|
||||
"windmill-parser-wasm-wac": "1.830.0",
|
||||
"windmill-parser-wasm-yaml": "1.770.0",
|
||||
"windmill-sql-datatype-parser-wasm": "1.512.0",
|
||||
"windmill-utils-internal": "1.8.6",
|
||||
"xterm": "^5.3.0",
|
||||
"xterm-readline": "^1.1.2",
|
||||
"y-monaco": "^0.1.4",
|
||||
|
||||
@@ -21,7 +21,10 @@
|
||||
// `chat-sdk/src/index.ts`, which escapes the package root the same way.
|
||||
// Compile that entry point into the package and rewrite those imports.
|
||||
//
|
||||
// 4. `$lib/utils` from inside `utils/`: svelte-package turns it into `./`,
|
||||
// 4. Utils: the `windmill-utils-internal` alias points at
|
||||
// `cli/windmill-utils-internal/src`, handled like the chat SDK.
|
||||
//
|
||||
// 5. `$lib/utils` from inside `utils/`: svelte-package turns it into `./`,
|
||||
// which is the `utils/` directory (no index) rather than `utils.js`.
|
||||
// Point a directory specifier with no index at its sibling module.
|
||||
//
|
||||
@@ -45,32 +48,46 @@ copyFileSync(oauthConnectSrc, oauthConnectDest)
|
||||
const chatSdkSrc = resolve(__dirname, '..', '..', 'chat-sdk', 'src', 'index.ts')
|
||||
const chatSdkDest = join(packageDir, 'chat-sdk')
|
||||
|
||||
const utilsSrc = resolve(__dirname, '..', '..', 'cli', 'windmill-utils-internal', 'src')
|
||||
const utilsDest = join(packageDir, 'utils-internal')
|
||||
const utilsModules = ['deploy', 'parse/parse-schema']
|
||||
|
||||
// File arguments make tsc ignore every tsconfig and emit only what the entry
|
||||
// point reaches, which leaves out the React and AI SDK adapters.
|
||||
execFileSync(
|
||||
'npx',
|
||||
[
|
||||
'tsc',
|
||||
chatSdkSrc,
|
||||
'--outDir',
|
||||
chatSdkDest,
|
||||
'--rootDir',
|
||||
dirname(chatSdkSrc),
|
||||
'--declaration',
|
||||
'--target',
|
||||
'ES2021',
|
||||
'--module',
|
||||
'ESNext',
|
||||
'--moduleResolution',
|
||||
'bundler',
|
||||
'--skipLibCheck'
|
||||
],
|
||||
{ stdio: 'inherit', cwd: resolve(__dirname, '..') }
|
||||
function compile(entries, outDir, rootDir) {
|
||||
execFileSync(
|
||||
'npx',
|
||||
[
|
||||
'tsc',
|
||||
...entries,
|
||||
'--outDir',
|
||||
outDir,
|
||||
'--rootDir',
|
||||
rootDir,
|
||||
'--declaration',
|
||||
'--target',
|
||||
'ES2021',
|
||||
'--module',
|
||||
'ESNext',
|
||||
'--moduleResolution',
|
||||
'bundler',
|
||||
'--skipLibCheck'
|
||||
],
|
||||
{ stdio: 'inherit', cwd: resolve(__dirname, '..') }
|
||||
)
|
||||
}
|
||||
|
||||
compile([chatSdkSrc], chatSdkDest, dirname(chatSdkSrc))
|
||||
compile(
|
||||
utilsModules.map((m) => join(utilsSrc, `${m}.ts`)),
|
||||
utilsDest,
|
||||
utilsSrc
|
||||
)
|
||||
|
||||
const IMPORT_SPECIFIER_RE = /(\bfrom\s*|\bimport\s*\(?\s*)(['"])(\.\.?(?:\/[^'"]*)?)\2/g
|
||||
const OAUTH_CONNECT_RE = /^(\.\.\/)+backend\/oauth_connect\.json$/
|
||||
const CHAT_SDK_RE = /^(\.\.\/)+chat-sdk\/src\/index\.ts$/
|
||||
const UTILS_RE = /^(?:\.\.\/)+cli\/windmill-utils-internal\/src\/(.+?)(?:\.ts)?$/
|
||||
const DIRECTORY_RE = /(^|\/)\.\.?$|\/$/
|
||||
const ALIASED_GLOB_RE = /import\.meta\.glob(?:<[^>]*>)?\(\s*\[?\s*['"]\$/
|
||||
|
||||
@@ -111,6 +128,12 @@ for (const file of walk(packageDir)) {
|
||||
rewrittenImports++
|
||||
return `${prefix}${quote}${relativeSpecifier(file, join(chatSdkDest, 'index.js'))}${quote}`
|
||||
}
|
||||
const utilsModule = specifier.match(UTILS_RE)?.[1]
|
||||
if (utilsModules.includes(utilsModule)) {
|
||||
changed = true
|
||||
rewrittenImports++
|
||||
return `${prefix}${quote}${relativeSpecifier(file, join(utilsDest, `${utilsModule}.js`))}${quote}`
|
||||
}
|
||||
const target = resolve(dirname(file), specifier)
|
||||
// Test files ride along in the output but no consumer imports them, so an escaping
|
||||
// import there (e.g. `../app.html?raw`) breaks nothing.
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
// Custom request module for `openapi-ts --request`: the generated core/request.ts, except that
|
||||
// getUrl encodes path parameters with encodePathParam (src/lib/apiPathParams.ts).
|
||||
import { ApiError } from './ApiError'
|
||||
import type { ApiRequestOptions } from './ApiRequestOptions'
|
||||
import type { ApiResult } from './ApiResult'
|
||||
import { CancelablePromise } from './CancelablePromise'
|
||||
import type { OnCancel } from './CancelablePromise'
|
||||
import type { OpenAPIConfig } from './OpenAPI'
|
||||
import { encodePathParam } from '../../apiPathParams'
|
||||
|
||||
export const isString = (value: unknown): value is string => {
|
||||
return typeof value === 'string'
|
||||
}
|
||||
|
||||
export const isStringWithValue = (value: unknown): value is string => {
|
||||
return isString(value) && value !== ''
|
||||
}
|
||||
|
||||
export const isBlob = (value: any): value is Blob => {
|
||||
return value instanceof Blob
|
||||
}
|
||||
|
||||
export const isFormData = (value: unknown): value is FormData => {
|
||||
return value instanceof FormData
|
||||
}
|
||||
|
||||
export const base64 = (str: string): string => {
|
||||
try {
|
||||
return btoa(str)
|
||||
} catch (err) {
|
||||
// @ts-ignore
|
||||
return Buffer.from(str).toString('base64')
|
||||
}
|
||||
}
|
||||
|
||||
export const getQueryString = (params: Record<string, unknown>): string => {
|
||||
const qs: string[] = []
|
||||
|
||||
const append = (key: string, value: unknown) => {
|
||||
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
|
||||
}
|
||||
|
||||
const encodePair = (key: string, value: unknown) => {
|
||||
if (value === undefined || value === null) {
|
||||
return
|
||||
}
|
||||
|
||||
if (value instanceof Date) {
|
||||
append(key, value.toISOString())
|
||||
} else if (Array.isArray(value)) {
|
||||
value.forEach((v) => encodePair(key, v))
|
||||
} else if (typeof value === 'object') {
|
||||
Object.entries(value).forEach(([k, v]) => encodePair(`${key}[${k}]`, v))
|
||||
} else {
|
||||
append(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
Object.entries(params).forEach(([key, value]) => encodePair(key, value))
|
||||
|
||||
return qs.length ? `?${qs.join('&')}` : ''
|
||||
}
|
||||
|
||||
const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => {
|
||||
const path = options.url
|
||||
.replace('{api-version}', config.VERSION)
|
||||
.replace(/{(.*?)}/g, (substring: string, group: string) => {
|
||||
if (options.path?.hasOwnProperty(group)) {
|
||||
const value = String(options.path[group])
|
||||
return config.ENCODE_PATH ? config.ENCODE_PATH(value) : encodePathParam(group, value)
|
||||
}
|
||||
return substring
|
||||
})
|
||||
|
||||
const url = config.BASE + path
|
||||
return options.query ? url + getQueryString(options.query) : url
|
||||
}
|
||||
|
||||
export const getFormData = (options: ApiRequestOptions): FormData | undefined => {
|
||||
if (options.formData) {
|
||||
const formData = new FormData()
|
||||
|
||||
const process = (key: string, value: unknown) => {
|
||||
if (isString(value) || isBlob(value)) {
|
||||
formData.append(key, value)
|
||||
} else {
|
||||
formData.append(key, JSON.stringify(value))
|
||||
}
|
||||
}
|
||||
|
||||
Object.entries(options.formData)
|
||||
.filter(([, value]) => value !== undefined && value !== null)
|
||||
.forEach(([key, value]) => {
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((v) => process(key, v))
|
||||
} else {
|
||||
process(key, value)
|
||||
}
|
||||
})
|
||||
|
||||
return formData
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>
|
||||
|
||||
export const resolve = async <T>(
|
||||
options: ApiRequestOptions,
|
||||
resolver?: T | Resolver<T>
|
||||
): Promise<T | undefined> => {
|
||||
if (typeof resolver === 'function') {
|
||||
return (resolver as Resolver<T>)(options)
|
||||
}
|
||||
return resolver
|
||||
}
|
||||
|
||||
export const getHeaders = async (
|
||||
config: OpenAPIConfig,
|
||||
options: ApiRequestOptions
|
||||
): Promise<Headers> => {
|
||||
const [token, username, password, additionalHeaders] = await Promise.all([
|
||||
resolve(options, config.TOKEN),
|
||||
resolve(options, config.USERNAME),
|
||||
resolve(options, config.PASSWORD),
|
||||
resolve(options, config.HEADERS)
|
||||
])
|
||||
|
||||
const headers = Object.entries({
|
||||
Accept: 'application/json',
|
||||
...additionalHeaders,
|
||||
...options.headers
|
||||
})
|
||||
.filter(([, value]) => value !== undefined && value !== null)
|
||||
.reduce(
|
||||
(headers, [key, value]) => ({
|
||||
...headers,
|
||||
[key]: String(value)
|
||||
}),
|
||||
{} as Record<string, string>
|
||||
)
|
||||
|
||||
if (isStringWithValue(token)) {
|
||||
headers['Authorization'] = `Bearer ${token}`
|
||||
}
|
||||
|
||||
if (isStringWithValue(username) && isStringWithValue(password)) {
|
||||
const credentials = base64(`${username}:${password}`)
|
||||
headers['Authorization'] = `Basic ${credentials}`
|
||||
}
|
||||
|
||||
if (options.body !== undefined) {
|
||||
if (options.mediaType) {
|
||||
headers['Content-Type'] = options.mediaType
|
||||
} else if (isBlob(options.body)) {
|
||||
headers['Content-Type'] = options.body.type || 'application/octet-stream'
|
||||
} else if (isString(options.body)) {
|
||||
headers['Content-Type'] = 'text/plain'
|
||||
} else if (!isFormData(options.body)) {
|
||||
headers['Content-Type'] = 'application/json'
|
||||
}
|
||||
}
|
||||
|
||||
return new Headers(headers)
|
||||
}
|
||||
|
||||
export const getRequestBody = (options: ApiRequestOptions): unknown => {
|
||||
if (options.body !== undefined) {
|
||||
if (options.mediaType?.includes('application/json') || options.mediaType?.includes('+json')) {
|
||||
return JSON.stringify(options.body)
|
||||
} else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) {
|
||||
return options.body
|
||||
} else {
|
||||
return JSON.stringify(options.body)
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export const sendRequest = async (
|
||||
config: OpenAPIConfig,
|
||||
options: ApiRequestOptions,
|
||||
url: string,
|
||||
body: any,
|
||||
formData: FormData | undefined,
|
||||
headers: Headers,
|
||||
onCancel: OnCancel
|
||||
): Promise<Response> => {
|
||||
const controller = new AbortController()
|
||||
|
||||
let request: RequestInit = {
|
||||
headers,
|
||||
body: body ?? formData,
|
||||
method: options.method,
|
||||
signal: controller.signal
|
||||
}
|
||||
|
||||
if (config.WITH_CREDENTIALS) {
|
||||
request.credentials = config.CREDENTIALS
|
||||
}
|
||||
|
||||
for (const fn of config.interceptors.request._fns) {
|
||||
request = await fn(request)
|
||||
}
|
||||
|
||||
onCancel(() => controller.abort())
|
||||
|
||||
return await fetch(url, request)
|
||||
}
|
||||
|
||||
export const getResponseHeader = (
|
||||
response: Response,
|
||||
responseHeader?: string
|
||||
): string | undefined => {
|
||||
if (responseHeader) {
|
||||
const content = response.headers.get(responseHeader)
|
||||
if (isString(content)) {
|
||||
return content
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export const getResponseBody = async (response: Response): Promise<unknown> => {
|
||||
if (response.status !== 204) {
|
||||
try {
|
||||
const contentType = response.headers.get('Content-Type')
|
||||
if (contentType) {
|
||||
const binaryTypes = [
|
||||
'application/octet-stream',
|
||||
'application/pdf',
|
||||
'application/zip',
|
||||
'audio/',
|
||||
'image/',
|
||||
'video/'
|
||||
]
|
||||
if (contentType.includes('application/json') || contentType.includes('+json')) {
|
||||
return await response.json()
|
||||
} else if (binaryTypes.some((type) => contentType.includes(type))) {
|
||||
return await response.blob()
|
||||
} else if (contentType.includes('multipart/form-data')) {
|
||||
return await response.formData()
|
||||
} else if (contentType.includes('text/')) {
|
||||
return await response.text()
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => {
|
||||
const errors: Record<number, string> = {
|
||||
400: 'Bad Request',
|
||||
401: 'Unauthorized',
|
||||
402: 'Payment Required',
|
||||
403: 'Forbidden',
|
||||
404: 'Not Found',
|
||||
405: 'Method Not Allowed',
|
||||
406: 'Not Acceptable',
|
||||
407: 'Proxy Authentication Required',
|
||||
408: 'Request Timeout',
|
||||
409: 'Conflict',
|
||||
410: 'Gone',
|
||||
411: 'Length Required',
|
||||
412: 'Precondition Failed',
|
||||
413: 'Payload Too Large',
|
||||
414: 'URI Too Long',
|
||||
415: 'Unsupported Media Type',
|
||||
416: 'Range Not Satisfiable',
|
||||
417: 'Expectation Failed',
|
||||
418: 'Im a teapot',
|
||||
421: 'Misdirected Request',
|
||||
422: 'Unprocessable Content',
|
||||
423: 'Locked',
|
||||
424: 'Failed Dependency',
|
||||
425: 'Too Early',
|
||||
426: 'Upgrade Required',
|
||||
428: 'Precondition Required',
|
||||
429: 'Too Many Requests',
|
||||
431: 'Request Header Fields Too Large',
|
||||
451: 'Unavailable For Legal Reasons',
|
||||
500: 'Internal Server Error',
|
||||
501: 'Not Implemented',
|
||||
502: 'Bad Gateway',
|
||||
503: 'Service Unavailable',
|
||||
504: 'Gateway Timeout',
|
||||
505: 'HTTP Version Not Supported',
|
||||
506: 'Variant Also Negotiates',
|
||||
507: 'Insufficient Storage',
|
||||
508: 'Loop Detected',
|
||||
510: 'Not Extended',
|
||||
511: 'Network Authentication Required',
|
||||
...options.errors
|
||||
}
|
||||
|
||||
const error = errors[result.status]
|
||||
if (error) {
|
||||
throw new ApiError(options, result, error)
|
||||
}
|
||||
|
||||
if (!result.ok) {
|
||||
const errorStatus = result.status ?? 'unknown'
|
||||
const errorStatusText = result.statusText ?? 'unknown'
|
||||
const errorBody = (() => {
|
||||
try {
|
||||
return JSON.stringify(result.body, null, 2)
|
||||
} catch (e) {
|
||||
return undefined
|
||||
}
|
||||
})()
|
||||
|
||||
throw new ApiError(
|
||||
options,
|
||||
result,
|
||||
`Generic Error: status: ${errorStatus}; status text: ${errorStatusText}; body: ${errorBody}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request method
|
||||
* @param config The OpenAPI configuration object
|
||||
* @param options The request options from the service
|
||||
* @returns CancelablePromise<T>
|
||||
* @throws ApiError
|
||||
*/
|
||||
export const request = <T>(
|
||||
config: OpenAPIConfig,
|
||||
options: ApiRequestOptions
|
||||
): CancelablePromise<T> => {
|
||||
return new CancelablePromise(async (resolve, reject, onCancel) => {
|
||||
try {
|
||||
const url = getUrl(config, options)
|
||||
const formData = getFormData(options)
|
||||
const body = getRequestBody(options)
|
||||
const headers = await getHeaders(config, options)
|
||||
|
||||
if (!onCancel.isCancelled) {
|
||||
let response = await sendRequest(config, options, url, body, formData, headers, onCancel)
|
||||
|
||||
for (const fn of config.interceptors.response._fns) {
|
||||
response = await fn(response)
|
||||
}
|
||||
|
||||
const responseBody = await getResponseBody(response)
|
||||
const responseHeader = getResponseHeader(response, options.responseHeader)
|
||||
|
||||
const result: ApiResult = {
|
||||
url,
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
body: responseHeader ?? responseBody
|
||||
}
|
||||
|
||||
catchErrorCodes(options, result)
|
||||
|
||||
resolve(result.body)
|
||||
}
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"baseUrl": "https://pub-06154ed168a24e73a86ab84db6bf15d8.r2.dev",
|
||||
"version": "5ae35e6",
|
||||
"sha256": "cdc948ce65b3ed0befbbfab7c816f2db63ae9207bbd85653d3484516c7ac3238"
|
||||
"version": "f9da2f8",
|
||||
"sha256": "fec1b1536fa0f97759314337d79b1f64bd0f5fb6d5e8aee3d5e2a2abb247ca8f"
|
||||
}
|
||||
|
||||
@@ -159,6 +159,12 @@
|
||||
var pub = /^\/public\/([^/]+)\/([^/]+)\/?$/.exec(path)
|
||||
var custom = /^\/a\/(.+?)\/?$/.exec(path)
|
||||
if (!pub && !custom && !/^\/public\//.test(path)) return
|
||||
// fetch() resolves encoded dot segments and separators, which would take these
|
||||
// URLs outside their route; such paths are left to the page, which refuses them.
|
||||
if (/%2e|%2f|%5c|\\/i.test(path)) {
|
||||
pub = null
|
||||
custom = null
|
||||
}
|
||||
// Dark as PublicApp decides it, painted before any stylesheet so that a dark app
|
||||
// does not load over a white page.
|
||||
var dark = false
|
||||
|
||||
@@ -166,6 +166,6 @@ it("keeps a model pick the tab's workspace does not offer, without sending it th
|
||||
setCopilotInfo(withModel('parent'))
|
||||
|
||||
expect(get(copilotSessionModel)).toEqual(pick)
|
||||
expect(tryResolveModelFor(get(copilotInfo))?.model).toBe('parent')
|
||||
expect(tryResolveModelFor(get(copilotInfo), pick)?.model).toBe('parent')
|
||||
copilotSessionModel.set(undefined)
|
||||
})
|
||||
|
||||
+84
-24
@@ -15,10 +15,16 @@ import {
|
||||
WorkspaceService
|
||||
} from './gen'
|
||||
import {
|
||||
AI_REVIEW_MODEL_SETTING_NAME,
|
||||
AI_REVIEW_PROVIDER_SETTING_NAME,
|
||||
AI_REVIEW_REASONING_SETTING_NAME,
|
||||
aiUserDisabled,
|
||||
COPILOT_SESSION_MODEL_SETTING_NAME,
|
||||
COPILOT_SESSION_PROVIDER_SETTING_NAME,
|
||||
COPILOT_SESSION_REASONING_SETTING_NAME
|
||||
COPILOT_SESSION_REASONING_SETTING_NAME,
|
||||
SCRIPT_GEN_MODEL_SETTING_NAME,
|
||||
SCRIPT_GEN_PROVIDER_SETTING_NAME,
|
||||
SCRIPT_GEN_REASONING_SETTING_NAME
|
||||
} from './stores'
|
||||
import { getLocalSetting, storeLocalSetting } from './utils'
|
||||
import {
|
||||
@@ -28,20 +34,51 @@ import {
|
||||
|
||||
const USER_CUSTOM_PROMPTS_KEY = 'userCustomAIPrompts'
|
||||
|
||||
const sessionModel = getLocalSetting(COPILOT_SESSION_MODEL_SETTING_NAME)
|
||||
const sessionProvider = getLocalSetting(COPILOT_SESSION_PROVIDER_SETTING_NAME)
|
||||
const sessionReasoning = getLocalSetting(COPILOT_SESSION_REASONING_SETTING_NAME)
|
||||
export const copilotSessionModel = writable<ReasoningProviderModel | undefined>(
|
||||
sessionModel && sessionProvider
|
||||
? {
|
||||
// Strip the deprecated /thinking suffix on read; the default effort
|
||||
// (resolved later) restores reasoning for migrated selections.
|
||||
model: stripLegacyThinkingSuffix(sessionModel),
|
||||
provider: sessionProvider as AIProvider,
|
||||
...(sessionReasoning ? { reasoning: sessionReasoning } : {})
|
||||
}
|
||||
: undefined
|
||||
)
|
||||
type PickSettings = { model: string; provider: string; reasoning: string }
|
||||
|
||||
const LAST_PICK_SETTINGS: PickSettings = {
|
||||
model: COPILOT_SESSION_MODEL_SETTING_NAME,
|
||||
provider: COPILOT_SESSION_PROVIDER_SETTING_NAME,
|
||||
reasoning: COPILOT_SESSION_REASONING_SETTING_NAME
|
||||
}
|
||||
const SCRIPT_GEN_PICK_SETTINGS: PickSettings = {
|
||||
model: SCRIPT_GEN_MODEL_SETTING_NAME,
|
||||
provider: SCRIPT_GEN_PROVIDER_SETTING_NAME,
|
||||
reasoning: SCRIPT_GEN_REASONING_SETTING_NAME
|
||||
}
|
||||
const AI_REVIEW_PICK_SETTINGS: PickSettings = {
|
||||
model: AI_REVIEW_MODEL_SETTING_NAME,
|
||||
provider: AI_REVIEW_PROVIDER_SETTING_NAME,
|
||||
reasoning: AI_REVIEW_REASONING_SETTING_NAME
|
||||
}
|
||||
|
||||
function readStoredPick(settings: PickSettings): ReasoningProviderModel | undefined {
|
||||
const model = getLocalSetting(settings.model)
|
||||
const provider = getLocalSetting(settings.provider)
|
||||
const reasoning = getLocalSetting(settings.reasoning)
|
||||
if (!model || !provider) return undefined
|
||||
return {
|
||||
// Strip the deprecated /thinking suffix on read; the default effort
|
||||
// (resolved later) restores reasoning for migrated selections.
|
||||
model: stripLegacyThinkingSuffix(model),
|
||||
provider: provider as AIProvider,
|
||||
...(reasoning ? { reasoning } : {})
|
||||
}
|
||||
}
|
||||
|
||||
function storePick(settings: PickSettings, pick: ReasoningProviderModel) {
|
||||
storeLocalSetting(settings.model, pick.model)
|
||||
storeLocalSetting(settings.provider, pick.provider)
|
||||
storeLocalSetting(settings.reasoning, pick.reasoning)
|
||||
}
|
||||
|
||||
export const copilotSessionModel = writable(readStoredPick(LAST_PICK_SETTINGS))
|
||||
|
||||
// Script generation's own pick, which neither follows nor sets the last pick.
|
||||
export const scriptGenModel = writable(readStoredPick(SCRIPT_GEN_PICK_SETTINGS))
|
||||
|
||||
// AI review's own pick outside a session; inside one, a review starts on the session's model.
|
||||
export const aiReviewModel = writable(readStoredPick(AI_REVIEW_PICK_SETTINGS))
|
||||
|
||||
export type CopilotInfo = {
|
||||
enabled: boolean
|
||||
@@ -198,11 +235,14 @@ export function isWebSearchEnabledForProvider(
|
||||
}
|
||||
|
||||
export function getCurrentModel(): ReasoningProviderModel {
|
||||
return resolveModelFor(get(copilotInfo))
|
||||
return resolveModelFor(get(copilotInfo), get(copilotSessionModel))
|
||||
}
|
||||
|
||||
export function resolveModelFor(info: CopilotInfo): ReasoningProviderModel {
|
||||
const model = tryResolveModelFor(info)
|
||||
export function resolveModelFor(
|
||||
info: CopilotInfo,
|
||||
pick: ReasoningProviderModel | undefined
|
||||
): ReasoningProviderModel {
|
||||
const model = tryResolveModelFor(info, pick)
|
||||
if (!model) {
|
||||
throw new Error('No model selected')
|
||||
}
|
||||
@@ -222,7 +262,7 @@ export function resolveMetadataModelFor(info: CopilotInfo): AIProviderModel {
|
||||
}
|
||||
|
||||
export function tryGetCurrentModel(): ReasoningProviderModel | undefined {
|
||||
return tryResolveModelFor(get(copilotInfo))
|
||||
return tryResolveModelFor(get(copilotInfo), get(copilotSessionModel))
|
||||
}
|
||||
|
||||
/** `workspace`'s AI config if loaded; otherwise starts loading it and returns undefined. */
|
||||
@@ -297,6 +337,23 @@ export function invalidateWorkspaceCopilotInfo(workspace?: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Sets the last pick, which everything without a pick of its own follows, a session included
|
||||
* until it has one. */
|
||||
export function setLastModelPick(model: ReasoningProviderModel) {
|
||||
copilotSessionModel.set(model)
|
||||
storePick(LAST_PICK_SETTINGS, model)
|
||||
}
|
||||
|
||||
export function setScriptGenModelPick(model: ReasoningProviderModel) {
|
||||
scriptGenModel.set(model)
|
||||
storePick(SCRIPT_GEN_PICK_SETTINGS, model)
|
||||
}
|
||||
|
||||
export function setAiReviewModelPick(model: ReasoningProviderModel) {
|
||||
aiReviewModel.set(model)
|
||||
storePick(AI_REVIEW_PICK_SETTINGS, model)
|
||||
}
|
||||
|
||||
// Leaves copilotSessionModel alone: the pick is shared with sessions in other workspaces, which may
|
||||
// offer a model this one does not.
|
||||
export function setCopilotInfo(aiConfig: AIConfig) {
|
||||
@@ -307,11 +364,14 @@ function isOffered(info: CopilotInfo, model: AIProviderModel): boolean {
|
||||
return info.aiModels.some((m) => m.model === model.model && m.provider === model.provider)
|
||||
}
|
||||
|
||||
/** The model a request for `info`'s workspace sends: the shared pick when that workspace offers
|
||||
* it, else its default, else its first model. Never one the workspace does not offer. */
|
||||
export function tryResolveModelFor(info: CopilotInfo): ReasoningProviderModel | undefined {
|
||||
const picked = get(copilotSessionModel)
|
||||
if (picked && isOffered(info, picked)) return picked
|
||||
/** The model a request for `info`'s workspace sends: `pick` when that workspace offers it, else
|
||||
* its default, else its first model. Never a pick the workspace does not offer. `pick` is required
|
||||
* so that a session passes its own rather than silently following the shared one. */
|
||||
export function tryResolveModelFor(
|
||||
info: CopilotInfo,
|
||||
pick: ReasoningProviderModel | undefined
|
||||
): ReasoningProviderModel | undefined {
|
||||
if (pick && isOffered(info, pick)) return pick
|
||||
return info.defaultModel ?? info.aiModels[0]
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { encodePathParam } from './apiPathParams'
|
||||
|
||||
describe('encodePathParam', () => {
|
||||
it('keeps slashes in path-like values', () => {
|
||||
expect(encodePathParam('path', 'u/admin/my script')).toBe('u/admin/my%20script')
|
||||
expect(encodePathParam('path', 'f/folder/a.b_c-d')).toBe('f/folder/a.b_c-d')
|
||||
})
|
||||
|
||||
it('keeps query and fragment characters inside the segment', () => {
|
||||
expect(encodePathParam('path', 'u/a/b?x=1#y')).toBe('u/a/b%3Fx=1%23y')
|
||||
})
|
||||
|
||||
it('refuses dot segments, plain or percent-encoded', () => {
|
||||
for (const v of ['u/../../jobs', '..', 'a/./b', 'a/%2e%2e/b', 'a/.%2E/b']) {
|
||||
expect(() => encodePathParam('path', v)).toThrow()
|
||||
}
|
||||
expect(encodePathParam('path', 'a/...')).toBe('a/...')
|
||||
})
|
||||
|
||||
it('encodes a workspace as one segment', () => {
|
||||
expect(encodePathParam('workspace', 'acme-1_x')).toBe('acme-1_x')
|
||||
expect(encodePathParam('workspace', 'acme/jobs/run?x=1')).toBe('acme%2Fjobs%2Frun%3Fx%3D1')
|
||||
expect(() => encodePathParam('workspace', '..')).toThrow()
|
||||
})
|
||||
|
||||
it('encodes percent signs so they are not decoded twice', () => {
|
||||
expect(encodePathParam('path', 'a/%2e%2e%2fb')).toBe('a/%252e%252e%252fb')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
// Path parameters are filled into the API route template by the generated client
|
||||
// (`scripts/openapi-ts-request.ts`). Each value must stay inside its own slot: the browser resolves
|
||||
// `.`/`..` segments (also as `%2e`) and starts the query at `?` or the fragment at `#`, so an
|
||||
// unchecked value would address a different route than the one the caller asked for.
|
||||
|
||||
/** Parameters whose values are single identifiers and never legitimately contain `/`. */
|
||||
const SINGLE_SEGMENT_PARAMS = new Set([
|
||||
'workspace',
|
||||
'workspace_id',
|
||||
'target_workspace_id',
|
||||
'fork_workspace_id',
|
||||
'client_name',
|
||||
'client'
|
||||
])
|
||||
|
||||
export class InvalidPathParamError extends Error {
|
||||
constructor(name: string) {
|
||||
super(`Invalid value for path parameter "${name}"`)
|
||||
this.name = 'InvalidPathParamError'
|
||||
}
|
||||
}
|
||||
|
||||
function isDotSegment(segment: string): boolean {
|
||||
return /^(\.|%2e){1,2}$/i.test(segment)
|
||||
}
|
||||
|
||||
function encodeSegment(segment: string): string {
|
||||
return encodeURI(segment).replace(/[?#]/g, (c) => encodeURIComponent(c))
|
||||
}
|
||||
|
||||
/** Encodes one path parameter value. Slashes are kept for path-like values (`u/user/script`),
|
||||
* but every segment is encoded and `.`/`..` segments are refused. */
|
||||
export function encodePathParam(name: string, value: string): string {
|
||||
if (SINGLE_SEGMENT_PARAMS.has(name)) {
|
||||
if (isDotSegment(value)) throw new InvalidPathParamError(name)
|
||||
return encodeURIComponent(value)
|
||||
}
|
||||
const segments = value.split('/')
|
||||
if (segments.some(isDotSegment)) throw new InvalidPathParamError(name)
|
||||
return segments.map(encodeSegment).join('/')
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
import pLimit from 'p-limit'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { get } from 'svelte/store'
|
||||
import { encodePathParam } from '$lib/apiPathParams'
|
||||
import { confinedSubpath } from './confinedPath'
|
||||
|
||||
// Backend proxy fallback functions
|
||||
const getBackendProxyUrl = () => {
|
||||
@@ -10,7 +12,7 @@ const getBackendProxyUrl = () => {
|
||||
if (!workspace) {
|
||||
throw new Error('No workspace available')
|
||||
}
|
||||
return `/api/w/${workspace}/npm_proxy`
|
||||
return `/api/w/${encodePathParam('workspace', workspace)}/npm_proxy`
|
||||
}
|
||||
|
||||
const backendProxyApi = async <T>(endpoint: string, resLimit: ResLimit): Promise<T | Error> => {
|
||||
@@ -153,11 +155,15 @@ export const getDTSFileForModuleWithVersion = (
|
||||
version: string,
|
||||
// file comes with a prefix /
|
||||
file: string
|
||||
) =>
|
||||
fromPreferredSource<string>(
|
||||
() => text(`https://cdn.jsdelivr.net/npm/${moduleName}@${version}${file}`),
|
||||
) => {
|
||||
const confinedFile = confinedSubpath(file)
|
||||
if (confinedFile === undefined) {
|
||||
return Promise.resolve(new Error(`File ${file} is outside of package ${moduleName}`))
|
||||
}
|
||||
return fromPreferredSource<string>(
|
||||
() => text(`https://cdn.jsdelivr.net/npm/${moduleName}@${version}${confinedFile}`),
|
||||
async () => {
|
||||
const proxyUrl = `${getBackendProxyUrl()}/file/${encodeURIComponent(moduleName)}/${encodeURIComponent(version)}${file}`
|
||||
const proxyUrl = `${getBackendProxyUrl()}/file/${encodeURIComponent(moduleName)}/${encodeURIComponent(version)}${confinedFile}`
|
||||
const proxied = await text(proxyUrl, { credentials: 'include' })
|
||||
// The callers in ata/index.ts log a fixed message and drop the value, so a cause
|
||||
// left inside the returned `Error` is a cause nothing ever prints.
|
||||
@@ -165,6 +171,7 @@ export const getDTSFileForModuleWithVersion = (
|
||||
return proxied
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reading the body can fail as readily as connecting, and both have to surface as a value
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { confinedSubpath, localImportUrl } from './confinedPath'
|
||||
|
||||
const ROOT = 'http://localhost/api/scripts_u/tokened_raw/ws/tok'
|
||||
|
||||
describe('localImportUrl', () => {
|
||||
it('resolves relative imports next to the script', () => {
|
||||
expect(localImportUrl(ROOT, 'u/admin/main', './helper')).toBe(ROOT + '/u/admin/helper')
|
||||
expect(localImportUrl(ROOT, 'u/admin/main', '../other/lib')).toBe(ROOT + '/u/other/lib')
|
||||
expect(localImportUrl(ROOT, 'f/folder/main', '/f/shared/util')).toBe(ROOT + '/f/shared/util')
|
||||
})
|
||||
|
||||
it('refuses imports that climb above the root', () => {
|
||||
expect(localImportUrl(ROOT, 'u/admin/main', '/../../../w/x/jobs')).toBeUndefined()
|
||||
expect(localImportUrl(ROOT, 'u/admin/main', '../../../../w/x')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps query and fragment characters in the file name', () => {
|
||||
expect(localImportUrl(ROOT, 'u/admin/main', '/u/a/b?x=1#')).toBe(ROOT + '/u/a/b%3Fx=1%23')
|
||||
expect(localImportUrl(ROOT, 'u/admin/main', '/u/%2e%2e/%2e%2e')).toBe(
|
||||
ROOT + '/u/%252e%252e/%252e%252e'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('confinedSubpath', () => {
|
||||
it('normalizes package file paths', () => {
|
||||
expect(confinedSubpath('/dist/index.d.ts')).toBe('/dist/index.d.ts')
|
||||
expect(confinedSubpath('/dist/./a/../b.d.ts')).toBe('/dist/b.d.ts')
|
||||
expect(confinedSubpath('/../../../file')).toBeUndefined()
|
||||
expect(confinedSubpath('/a\\..\\b')).toBe('/a%5C..%5Cb')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Normalizes a `/`-rooted file path and encodes each segment, so the result appended to a URL
|
||||
* prefix always names a file below that prefix: `.`/`..` are resolved here rather than by the
|
||||
* browser's URL parser, and `?`, `#`, `\` and `%` (so no `%2e%2e`) cannot reach the URL
|
||||
* unencoded. Returns `undefined` when the path climbs above its root.
|
||||
*/
|
||||
export function confinedSubpath(path: string): string | undefined {
|
||||
const out: string[] = []
|
||||
const segments = path.split('/')
|
||||
// A leading `/` gives an empty first segment, which is the root itself.
|
||||
if (segments[0] === '') segments.shift()
|
||||
for (const segment of segments) {
|
||||
if (segment === '.') continue
|
||||
if (segment === '..') {
|
||||
if (out.length === 0) return undefined
|
||||
out.pop()
|
||||
continue
|
||||
}
|
||||
out.push(encodeURI(segment).replace(/[?#]/g, (c) => encodeURIComponent(c)))
|
||||
}
|
||||
return '/' + out.join('/')
|
||||
}
|
||||
|
||||
/** URL of a script's relative or absolute local import, below the tokened raw-script `root`. */
|
||||
export function localImportUrl(
|
||||
root: string,
|
||||
scriptPath: string,
|
||||
specifier: string
|
||||
): string | undefined {
|
||||
const path = specifier.startsWith('/')
|
||||
? specifier
|
||||
: '/' + scriptPath + (specifier.startsWith('../') ? '/../' : '/.') + specifier
|
||||
const confined = confinedSubpath(path)
|
||||
return confined === undefined ? undefined : root + confined
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { isTypescriptRelativePath } from '$lib/relative_imports'
|
||||
import { localImportUrl } from './confinedPath'
|
||||
import {
|
||||
getDTSFileForModuleWithVersion,
|
||||
getFiletreeForModuleWithVersion,
|
||||
@@ -131,10 +132,8 @@ export const setupTypeAcquisition = (config: ATABootstrapConfig) => {
|
||||
if (depth == 0) {
|
||||
const relativeDeps = depsToGet.filter((f) => isTypescriptRelativePath(f.raw))
|
||||
relativeDeps.forEach(async (f) => {
|
||||
let path = f.raw.startsWith('/')
|
||||
? f.raw
|
||||
: '/' + config.scriptPath + (f.raw.startsWith('../') ? '/../' : '/.') + f.raw
|
||||
let url = config.root + path
|
||||
let url = localImportUrl(config.root, config.scriptPath ?? '', f.raw)
|
||||
if (url === undefined) return
|
||||
let localPath = f.raw
|
||||
if ((f.raw.startsWith('.') || f.raw.startsWith('/')) && !f.raw.endsWith('.ts')) {
|
||||
url += '.ts'
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { appendTrustedProxy, clientIpHeaderError, trustedProxiesErrors } from './clientIpTrust'
|
||||
|
||||
// The same inputs as `stored_trusted_proxies_refuse_what_is_not_a_proxy` in `client_ip.rs`:
|
||||
// the form must refuse exactly what the server refuses.
|
||||
describe('trustedProxiesErrors', () => {
|
||||
it('accepts proxies', () => {
|
||||
for (const ok of ['private, 10.1.2.3, 172.20.0.0/16, caddy, fd00::/8', 'none', '', '::ffff:10.0.0.1']) {
|
||||
expect(trustedProxiesErrors(ok), ok).toEqual([])
|
||||
}
|
||||
})
|
||||
it('refuses what is not a proxy', () => {
|
||||
for (const bad of [
|
||||
'0.0.0.0/0',
|
||||
'::/0',
|
||||
'10.0.0.0/8, 104.16.0.0/12',
|
||||
'162.158.1.1',
|
||||
'2606:4700::/48',
|
||||
'10.0.0.0/33',
|
||||
'10.0.0.256',
|
||||
'none, 10.0.0.1',
|
||||
'not a host!'
|
||||
]) {
|
||||
expect(trustedProxiesErrors(bad).length, bad).toBeGreaterThan(0)
|
||||
}
|
||||
})
|
||||
it('refuses X-Forwarded-For as the client IP header', () => {
|
||||
expect(clientIpHeaderError('X-Forwarded-For')).toBeDefined()
|
||||
expect(clientIpHeaderError('CF-Connecting-IP')).toBeUndefined()
|
||||
// YAML mode can put any JSON type here.
|
||||
expect(clientIpHeaderError(42)).toBeDefined()
|
||||
expect(trustedProxiesErrors(['10.0.0.1']).length).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('appendTrustedProxy', () => {
|
||||
it('adds to the default private trust or narrows it, as asked', () => {
|
||||
expect(appendTrustedProxy(undefined, '1.2.3.4', true)).toBe('private, 1.2.3.4')
|
||||
expect(appendTrustedProxy('', '10.0.0.5', false)).toBe('10.0.0.5')
|
||||
expect(appendTrustedProxy('none', '1.2.3.4', true)).toBe('1.2.3.4')
|
||||
expect(appendTrustedProxy('10.0.0.0/8, caddy', 'caddy', true)).toBe('10.0.0.0/8, caddy')
|
||||
// Narrowing drops whatever still trusts a whole private range.
|
||||
expect(appendTrustedProxy('private, 1.2.3.4', '10.0.0.5', false)).toBe('1.2.3.4, 10.0.0.5')
|
||||
expect(appendTrustedProxy('10.0.0.0/8, caddy', '10.0.0.5', false)).toBe('caddy, 10.0.0.5')
|
||||
// A subnet inside a private range is a list of proxies, kept.
|
||||
expect(appendTrustedProxy('192.168.0.0/24, 0.0.0.0/1', '10.0.0.5', false)).toBe(
|
||||
'192.168.0.0/24, 10.0.0.5'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,189 @@
|
||||
// Mirrors the checks `windmill_common::client_ip::validate_setting` applies on save, so the
|
||||
// Client IP settings refuse the same values before the server does.
|
||||
|
||||
/** https://www.cloudflare.com/ips-v4 and /ips-v6, as embedded in `client_ip.rs`. */
|
||||
const CLOUDFLARE = [
|
||||
'173.245.48.0/20',
|
||||
'103.21.244.0/22',
|
||||
'103.22.200.0/22',
|
||||
'103.31.4.0/22',
|
||||
'141.101.64.0/18',
|
||||
'108.162.192.0/18',
|
||||
'190.93.240.0/20',
|
||||
'188.114.96.0/20',
|
||||
'197.234.240.0/22',
|
||||
'198.41.128.0/17',
|
||||
'162.158.0.0/15',
|
||||
'104.16.0.0/13',
|
||||
'104.24.0.0/14',
|
||||
'172.64.0.0/13',
|
||||
'131.0.72.0/22',
|
||||
'2400:cb00::/32',
|
||||
'2606:4700::/32',
|
||||
'2803:f800::/32',
|
||||
'2405:b500::/32',
|
||||
'2405:8100::/32',
|
||||
'2a06:98c0::/29',
|
||||
'2c0f:f248::/32'
|
||||
]
|
||||
|
||||
type Net = { v6: boolean; addr: bigint; prefix: number }
|
||||
|
||||
function parseV4(s: string): bigint | undefined {
|
||||
const parts = s.split('.')
|
||||
if (parts.length !== 4) return undefined
|
||||
let n = 0n
|
||||
for (const p of parts) {
|
||||
if (!/^\d{1,3}$/.test(p) || Number(p) > 255) return undefined
|
||||
n = (n << 8n) | BigInt(p)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
function parseV6(s: string): bigint | undefined {
|
||||
if (!/^[0-9a-fA-F:.]+$/.test(s) || s.split('::').length > 2) return undefined
|
||||
const [head, tail] = s.includes('::') ? s.split('::') : [s, undefined]
|
||||
const groups = (g: string) => (g === '' ? [] : g.split(':'))
|
||||
const h = groups(head)
|
||||
const t = tail === undefined ? [] : groups(tail)
|
||||
const words: number[] = []
|
||||
const push = (list: string[], isLast: boolean) => {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const g = list[i]
|
||||
if (isLast && i === list.length - 1 && g.includes('.')) {
|
||||
const v4 = parseV4(g)
|
||||
if (v4 === undefined) return false
|
||||
words.push(Number(v4 >> 16n), Number(v4 & 0xffffn))
|
||||
} else if (/^[0-9a-fA-F]{1,4}$/.test(g)) {
|
||||
words.push(parseInt(g, 16))
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (!push(h, tail === undefined)) return undefined
|
||||
const headLen = words.length
|
||||
if (!push(t, true)) return undefined
|
||||
if (tail === undefined ? words.length !== 8 : words.length > 7) return undefined
|
||||
const full = [
|
||||
...words.slice(0, headLen),
|
||||
...Array(8 - words.length).fill(0),
|
||||
...words.slice(headLen)
|
||||
]
|
||||
return full.reduce((n, w) => (n << 16n) | BigInt(w), 0n)
|
||||
}
|
||||
|
||||
function parseNet(s: string): Net | undefined {
|
||||
const [addr, prefix, ...rest] = s.split('/')
|
||||
if (rest.length) return undefined
|
||||
const v4 = parseV4(addr)
|
||||
const v6 = v4 === undefined ? parseV6(addr) : undefined
|
||||
if (v4 === undefined && v6 === undefined) return undefined
|
||||
const isV6 = v4 === undefined
|
||||
const max = isV6 ? 128 : 32
|
||||
if (prefix !== undefined && !/^\d{1,3}$/.test(prefix)) return undefined
|
||||
const p = prefix === undefined ? max : Number(prefix)
|
||||
if (p > max) return undefined
|
||||
return { v6: isV6, addr: (v4 ?? v6)!, prefix: p }
|
||||
}
|
||||
|
||||
function network(n: Net): bigint {
|
||||
const bits = BigInt(n.v6 ? 128 : 32)
|
||||
const host = bits - BigInt(n.prefix)
|
||||
return (n.addr >> host) << host
|
||||
}
|
||||
|
||||
/** Whether `n` contains `other`'s network address: either containing the other is an overlap. */
|
||||
function containsAddr(n: Net, other: Net): boolean {
|
||||
if (n.v6 !== other.v6) return false
|
||||
const host = BigInt((n.v6 ? 128 : 32) - n.prefix)
|
||||
return network(n) >> host === network(other) >> host
|
||||
}
|
||||
|
||||
const CLOUDFLARE_NETS = CLOUDFLARE.map((c) => [c, parseNet(c)!] as const)
|
||||
|
||||
function isHostname(s: string): boolean {
|
||||
return (
|
||||
s.length <= 253 &&
|
||||
s
|
||||
.split('.')
|
||||
.every(
|
||||
(l) => l.length > 0 && l.length <= 63 && !l.startsWith('-') && /^[A-Za-z0-9_-]+$/.test(l)
|
||||
) &&
|
||||
!/^\d+$/.test(s.split('.').pop() ?? '')
|
||||
)
|
||||
}
|
||||
|
||||
/** Why each entry of a `trusted_proxies` value is refused, empty when it can be saved. */
|
||||
export function trustedProxiesErrors(value: unknown): string[] {
|
||||
if (value === undefined || value === null) return []
|
||||
if (typeof value !== 'string') return ['must be text: a comma-separated list']
|
||||
if (!value || value.trim().toLowerCase() === 'none') return []
|
||||
const errors: string[] = []
|
||||
for (const s of value
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)) {
|
||||
if (s.toLowerCase() === 'private') continue
|
||||
const net = parseNet(s)
|
||||
if (net) {
|
||||
if (net.prefix === 0) {
|
||||
errors.push(`${s} trusts every address, so any client could name its own`)
|
||||
continue
|
||||
}
|
||||
const cf = CLOUDFLARE_NETS.find(([, c]) => containsAddr(c, net) || containsAddr(net, c))
|
||||
if (cf) {
|
||||
errors.push(`${s} overlaps Cloudflare's range ${cf[0]}: turn on Trust Cloudflare instead`)
|
||||
}
|
||||
} else if (s.toLowerCase() === 'none') {
|
||||
errors.push('none trusts no proxy only on its own, not among other entries')
|
||||
} else if (!isHostname(s)) {
|
||||
errors.push(`${s} is not an IP address, a CIDR, a hostname or private`)
|
||||
}
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
/** Why a `client_ip_header` value is refused, if it is. */
|
||||
export function clientIpHeaderError(value: unknown): string | undefined {
|
||||
if (value === undefined || value === null) return undefined
|
||||
if (typeof value !== 'string') return 'must be text: a header name'
|
||||
const v = value.trim()
|
||||
if (!v) return undefined
|
||||
if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(v)) return `${v} is not a header name`
|
||||
if (v.toLowerCase() === 'x-forwarded-for') {
|
||||
return 'X-Forwarded-For is read by default, from the right: leave this empty'
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const PRIVATE_NETS = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'].map(
|
||||
(n) => parseNet(n)!
|
||||
)
|
||||
|
||||
/** Whether a trusted proxies entry trusts a whole private range, as the server's
|
||||
* `private_ranges_trusted` counts it. */
|
||||
function coversPrivateRange(entry: string): boolean {
|
||||
if (entry.toLowerCase() === 'private') return true
|
||||
const net = parseNet(entry)
|
||||
return net !== undefined && PRIVATE_NETS.some((p) => net.prefix <= p.prefix && containsAddr(net, p))
|
||||
}
|
||||
|
||||
/** `list` with `entry` appended, unless it already names it. An empty list stands for the
|
||||
* default, `private`. `keepDefault` keeps that trust; otherwise the result is narrowed to the
|
||||
* listed proxies, dropping every entry that trusts a whole private range. */
|
||||
export function appendTrustedProxy(
|
||||
list: string | undefined,
|
||||
entry: string,
|
||||
keepDefault: boolean
|
||||
): string {
|
||||
const base = list?.trim() ? list : keepDefault ? 'private' : ''
|
||||
const entries = base
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s && s.toLowerCase() !== 'none')
|
||||
.filter((s) => keepDefault || !coversPrivateRange(s))
|
||||
if (!entries.includes(entry)) entries.push(entry)
|
||||
return entries.join(', ')
|
||||
}
|
||||
@@ -9,19 +9,19 @@
|
||||
import GoogleSigninButton from './GoogleSigninButton.svelte'
|
||||
import IconedResourceType from './IconedResourceType.svelte'
|
||||
import { addResourceTitle } from './resourceTypeDisplay'
|
||||
import type { NativeConnect } from './triggers/native/utils'
|
||||
|
||||
interface Props {
|
||||
expressOAuthSetup?: boolean
|
||||
workspace?: string
|
||||
native?: NativeConnect
|
||||
}
|
||||
|
||||
let { expressOAuthSetup = false, workspace = undefined, native = undefined }: Props = $props()
|
||||
let { expressOAuthSetup = false, workspace = undefined }: Props = $props()
|
||||
|
||||
/** Set by `open(rt, fillPath)`, not by the parent: which resource this run fills is a
|
||||
* property of the click, and a prop would go stale between two different rows. */
|
||||
/** Set by `open(rt, fillPath, requiredScopes)`, not by the parent: which resource this run
|
||||
* fills is a property of the click, and a prop would go stale between two different rows. */
|
||||
let fillPath: string | undefined = $state(undefined)
|
||||
let requiredScopes: string[] = $state([])
|
||||
let viaWorkspaceApp = $state(false)
|
||||
|
||||
let drawer: Drawer | undefined = $state()
|
||||
let resourceType = $state('')
|
||||
@@ -29,13 +29,24 @@
|
||||
let disabled = $state(false)
|
||||
let isGoogleSignin = $state(false)
|
||||
let manual = $state(true)
|
||||
let actionLabel: string | undefined = $state(undefined)
|
||||
let canGoBack: boolean | undefined = $state(undefined)
|
||||
|
||||
let appConnectInner: AppConnectInner | undefined = $state(undefined)
|
||||
|
||||
let rtToLoad: string | undefined = $state('')
|
||||
/** `fill` connects into a resource that already exists, instead of creating one. */
|
||||
export async function open(rt?: string, fill?: string) {
|
||||
/** `fill` connects into a resource that already exists, instead of creating one; filling an
|
||||
* OAuth resource reconnects it in place. `scopes` replace the provider's defaults.
|
||||
* `workspaceApp` connects through the workspace's OAuth app when it has one, as triggers do. */
|
||||
export async function open(
|
||||
rt?: string,
|
||||
fill?: string,
|
||||
scopes: string[] = [],
|
||||
workspaceApp = false
|
||||
) {
|
||||
fillPath = fill
|
||||
requiredScopes = scopes
|
||||
viaWorkspaceApp = workspaceApp
|
||||
handedOff = false
|
||||
rtToLoad = rt
|
||||
drawer?.openDrawer?.()
|
||||
@@ -78,7 +89,7 @@
|
||||
size="700px"
|
||||
>
|
||||
<DrawerContent
|
||||
title={native?.title ?? addResourceTitle(step > 1 ? resourceType : undefined)}
|
||||
title={addResourceTitle(step > 1 ? resourceType : undefined)}
|
||||
id="add-resource-drawer"
|
||||
on:close={drawer?.closeDrawer}
|
||||
tooltip="Resources represent connections to third party systems. Learn more on how to integrate external APIs."
|
||||
@@ -96,18 +107,19 @@
|
||||
bind:isGoogleSignin
|
||||
bind:disabled
|
||||
bind:manual
|
||||
bind:actionLabel
|
||||
bind:canGoBack
|
||||
on:close={drawer?.closeDrawer}
|
||||
on:refresh
|
||||
express={expressOAuthSetup}
|
||||
{workspace}
|
||||
{fillPath}
|
||||
{native}
|
||||
{requiredScopes}
|
||||
{viaWorkspaceApp}
|
||||
/>
|
||||
{#snippet actions()}
|
||||
<div class="flex gap-1">
|
||||
<!-- Only when the user came through the type picker: opening the drawer for one
|
||||
resource type skips step 1, so Back would land on a list they never chose from. -->
|
||||
{#if step > 1 && !rtToLoad}
|
||||
{#if canGoBack}
|
||||
<Button variant="default" unifiedSize="md" onClick={() => appConnectInner?.back()}>
|
||||
Back
|
||||
</Button>
|
||||
@@ -121,13 +133,7 @@
|
||||
{disabled}
|
||||
onClick={() => appConnectInner?.next()}
|
||||
>
|
||||
{#if (step == 2 && !manual) || native}
|
||||
Connect
|
||||
{:else if step == 1}
|
||||
Next
|
||||
{:else}
|
||||
Save
|
||||
{/if}
|
||||
{actionLabel ?? 'Next'}
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -18,6 +18,8 @@
|
||||
let disabled = $state(false)
|
||||
let manual = $state(true)
|
||||
let isGoogleSignin = $state(false)
|
||||
let actionLabel: string | undefined = $state(undefined)
|
||||
let canGoBack: boolean | undefined = $state(undefined)
|
||||
|
||||
let appConnect: AppConnectInner | undefined = $state(undefined)
|
||||
|
||||
@@ -42,7 +44,7 @@
|
||||
{#if !express}
|
||||
<div class="flex flex-row-reverse w-full pb-2 shrink-0">
|
||||
<div class="flex gap-2">
|
||||
{#if step > 2}
|
||||
{#if canGoBack}
|
||||
<Button variant="default" unifiedSize="md" onClick={() => appConnect?.back()}>
|
||||
Back
|
||||
</Button>
|
||||
@@ -52,13 +54,7 @@
|
||||
<GoogleSigninButton {disabled} onClick={() => appConnect?.next()} />
|
||||
{:else}
|
||||
<Button variant="accent" unifiedSize="md" {disabled} onClick={() => appConnect?.next()}>
|
||||
{#if step == 2 && !manual}
|
||||
Connect
|
||||
{:else if step == 1}
|
||||
Next
|
||||
{:else}
|
||||
Save
|
||||
{/if}
|
||||
{actionLabel ?? 'Next'}
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -73,6 +69,8 @@
|
||||
bind:disabled
|
||||
bind:manual
|
||||
bind:isGoogleSignin
|
||||
bind:actionLabel
|
||||
bind:canGoBack
|
||||
on:error
|
||||
on:refresh
|
||||
/>
|
||||
|
||||
@@ -761,29 +761,6 @@
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{#if k === 'gworkspace'}
|
||||
<div>
|
||||
<Toggle
|
||||
options={{
|
||||
right:
|
||||
'Allow workspace admins to set up Google integration triggers using these credentials'
|
||||
}}
|
||||
checked={oauths[k]?.share_with_workspaces ?? false}
|
||||
on:change={(e) => {
|
||||
if (oauths && oauths[k]) {
|
||||
oauths[k] = { ...oauths[k], share_with_workspaces: e.detail }
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{#if oauths[k]?.share_with_workspaces}
|
||||
<p class="text-xs text-tertiary mt-1">
|
||||
Workspace admins will be able to connect Google integration triggers without
|
||||
configuring their own OAuth client. The credentials are not exposed to them.
|
||||
Connections use the redirect URI above.
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
/** Set on the pages that render inside the app shell, under the page header: there the
|
||||
* window is not the card's box, and taking the whole of it pushes 44px past the bottom. */
|
||||
inPage?: boolean
|
||||
/** Off for content that is a card of its own, which the box would frame a second time. */
|
||||
box?: boolean
|
||||
children?: import('svelte').Snippet
|
||||
}
|
||||
|
||||
@@ -32,6 +34,7 @@
|
||||
containOverflow = false,
|
||||
showVersion = true,
|
||||
inPage = false,
|
||||
box = true,
|
||||
children
|
||||
}: Props = $props()
|
||||
|
||||
@@ -46,13 +49,15 @@
|
||||
: 'h-screen'} p-4 relative bg-surface-secondary {containOverflow
|
||||
? 'overflow-hidden'
|
||||
: 'overflow-auto'}"
|
||||
class:items-center={centerVertically}
|
||||
style="scrollbar-gutter: stable both-edges;"
|
||||
bind:clientHeight={height}
|
||||
>
|
||||
<!-- Centred with auto margins, not `items-center` on the scroller: a card taller than the
|
||||
window would overflow both ways, and its top would be out of scroll reach. -->
|
||||
<div
|
||||
class={twMerge(
|
||||
'flex flex-col gap-2 items-center w-full pb-8',
|
||||
centerVertically && 'my-auto',
|
||||
containOverflow ? 'min-h-0' : 'h-fit',
|
||||
containOverflow ? '' : height > 1080 ? 'pt-28' : 'pt-12'
|
||||
)}
|
||||
@@ -80,11 +85,9 @@
|
||||
|
||||
{#if children}
|
||||
<div
|
||||
class="rounded-md bg-surface w-full {large
|
||||
? 'max-w-5xl'
|
||||
: 'max-w-[640px]'} p-4 sm:py-8 sm:px-10 z-10 {containOverflow
|
||||
? 'flex-1 min-h-0 flex flex-col'
|
||||
: ''}"
|
||||
class="w-full {large ? 'max-w-5xl' : 'max-w-[640px]'} z-10 {box
|
||||
? 'rounded-md bg-surface p-4 sm:py-8 sm:px-10'
|
||||
: ''} {containOverflow ? 'flex-1 min-h-0 flex flex-col' : ''}"
|
||||
>
|
||||
{@render children()}
|
||||
</div>
|
||||
|
||||
@@ -56,7 +56,7 @@
|
||||
type DeployResult
|
||||
} from '$lib/utils_workspace_deploy'
|
||||
import { asSyncDeploy } from '$lib/deployOrigin'
|
||||
import { isTriggerOrScheduleKind } from 'windmill-utils-internal'
|
||||
import { isTriggerOrScheduleKind } from 'windmill-utils-internal/deploy'
|
||||
import Tooltip from './Tooltip.svelte'
|
||||
import OnBehalfOfSelector, {
|
||||
needsOnBehalfOfSelection,
|
||||
|
||||
@@ -15,8 +15,16 @@
|
||||
const MIN_COL_WIDTH = 60
|
||||
const DEFAULT_COL_WIDTH = 150
|
||||
const MAX_AUTO_COL_WIDTH = 400
|
||||
// Header padding plus its sort and key icons.
|
||||
const HEADER_CHROME = 48
|
||||
// Header padding, the sort arrow with its gap (kept free so sorting never truncates the
|
||||
// label), and the border.
|
||||
const HEADER_CHROME = 34
|
||||
// A key, link or join icon with its gap.
|
||||
const HEADER_ICON_WIDTH = 16
|
||||
// A pinned header's pin icon with its gap, and the thicker border at the pinned block's edge.
|
||||
const PIN_CHROME = 17
|
||||
// The filter button in a filterable column's header, with its margin.
|
||||
const HEADER_FILTER_WIDTH = 24
|
||||
const HEADER_FILTER_DEBOUNCE = 300
|
||||
const CELL_PADDING = 18
|
||||
// A double click starts with a click: following a foreign key waits this long
|
||||
// so the double click can edit the cell instead.
|
||||
@@ -43,6 +51,7 @@
|
||||
Columns3,
|
||||
EyeOff,
|
||||
Download,
|
||||
Filter,
|
||||
KeyRound,
|
||||
Link,
|
||||
Merge,
|
||||
@@ -105,6 +114,8 @@
|
||||
joinTargets?: DbJoinTarget[]
|
||||
/** Offered from the add-column button: adding a column to the table itself. */
|
||||
onNewColumn?: () => void
|
||||
/** Hides the button that downloads the loaded rows, for a file whose owner disabled downloads. */
|
||||
disableDownload?: boolean
|
||||
}
|
||||
let {
|
||||
dbTableOps,
|
||||
@@ -114,7 +125,8 @@
|
||||
onRowFilterApplied,
|
||||
layoutStorageKey,
|
||||
joinTargets,
|
||||
onNewColumn
|
||||
onNewColumn,
|
||||
disableDownload = false
|
||||
}: Props = $props()
|
||||
|
||||
const storedLayout = untrack(() =>
|
||||
@@ -162,6 +174,65 @@
|
||||
)
|
||||
let columnFilters = $derived(columnFiltersOf(filters, filterSchema))
|
||||
let hasFilters = $derived(!!quicksearch || !!filterWhere)
|
||||
/** The column whose header filter is open, and the value typed there. A header filter
|
||||
* writes the same entry the search bar does, so each shows the other's filter. */
|
||||
let headerFilter: { column: string; key: string; draft: string } | undefined = $state(undefined)
|
||||
/** The typed value not yet written to `filters`. Written when typing pauses, and at once
|
||||
* when the popover closes or another column is typed in, so no keystroke is lost. */
|
||||
let pendingHeaderFilter: { key: string; draft: string } | undefined
|
||||
let headerFilterTimer: ReturnType<typeof setTimeout> | undefined
|
||||
function setHeaderFilter(key: string, boolean: boolean, draft: string) {
|
||||
const { [key]: current, ...rest } = filters
|
||||
const trimmed = draft.trim()
|
||||
const value = trimmed ? (boolean ? trimmed === 'true' : trimmed) : undefined
|
||||
if (value === current) return
|
||||
filters = value === undefined ? rest : { ...rest, [key]: value }
|
||||
}
|
||||
function flushHeaderFilter() {
|
||||
clearTimeout(headerFilterTimer)
|
||||
const pending = pendingHeaderFilter
|
||||
pendingHeaderFilter = undefined
|
||||
if (pending) setHeaderFilter(pending.key, false, pending.draft)
|
||||
}
|
||||
/** Filters as the reader types; a half-typed comparison such as `>` matches no row. */
|
||||
function typeHeaderFilter(key: string, draft: string) {
|
||||
if (pendingHeaderFilter && pendingHeaderFilter.key !== key) flushHeaderFilter()
|
||||
if (headerFilter?.key === key) headerFilter.draft = draft
|
||||
pendingHeaderFilter = { key, draft }
|
||||
clearTimeout(headerFilterTimer)
|
||||
headerFilterTimer = setTimeout(flushHeaderFilter, HEADER_FILTER_DEBOUNCE)
|
||||
}
|
||||
/** For a popover's content: Escape closes that popover only. Left to the window, it
|
||||
* would also close a drawer the table sits in. */
|
||||
function escapeClosesOnly(close: () => void) {
|
||||
return (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Escape') return
|
||||
e.stopPropagation()
|
||||
close()
|
||||
}
|
||||
}
|
||||
/** Where focus goes when a header filter closes: back to its button, unless the click
|
||||
* that closed it put focus somewhere else (the search bar). */
|
||||
function headerFilterCloseFocus(column: string): HTMLElement | null {
|
||||
const active = document.activeElement
|
||||
if (active && active !== document.body) return null
|
||||
return (
|
||||
scrollEl?.querySelector<HTMLElement>(
|
||||
`[data-header-column="${CSS.escape(column)}"] [data-popover]`
|
||||
) ?? null
|
||||
)
|
||||
}
|
||||
function closeHeaderFilter() {
|
||||
flushHeaderFilter()
|
||||
headerFilter = undefined
|
||||
}
|
||||
/** The open popover's text: what was typed, unless the filter was changed from elsewhere
|
||||
* (the search bar, a chip removed) since. */
|
||||
function headerFilterDraft(key: string): string {
|
||||
const applied = filters[key] === undefined ? '' : String(filters[key])
|
||||
const draft = headerFilter?.key === key ? headerFilter.draft : applied
|
||||
return pendingHeaderFilter?.key === key || draft.trim() === applied ? draft : applied
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
const f = rowFilter
|
||||
@@ -233,6 +304,9 @@
|
||||
colDefs: dbTableOps.colDefs,
|
||||
quicksearch,
|
||||
filterWhere,
|
||||
// Sources that filter rows themselves read the values: `>` and `abc` on a number
|
||||
// column render the same SQL but are different requests.
|
||||
columnFilters,
|
||||
sort,
|
||||
joins,
|
||||
workspace: $operatingWorkspace,
|
||||
@@ -243,18 +317,22 @@
|
||||
// A refresh keeps the scroll position; a new query starts from the top.
|
||||
const onlyRefreshed =
|
||||
prevQuery && deepEqual({ ...query, refreshCount: 0 }, { ...prevQuery, refreshCount: 0 })
|
||||
const onlySorted =
|
||||
prevQuery && deepEqual({ ...query, sort: undefined }, { ...prevQuery, sort: undefined })
|
||||
prevQuery = query
|
||||
if (!onlyRefreshed && scrollEl) scrollEl.scrollTop = 0
|
||||
reload()
|
||||
reload(onlySorted)
|
||||
})
|
||||
})
|
||||
|
||||
function reload() {
|
||||
/** `keepCount`: the rows are the same, only their order changed. */
|
||||
function reload(keepCount = false) {
|
||||
generation += 1
|
||||
blocks = {}
|
||||
endRow = undefined
|
||||
rowCount = undefined
|
||||
editing = undefined
|
||||
if (keepCount && rowCount !== undefined) return
|
||||
rowCount = undefined
|
||||
if (!$operatingWorkspace) return
|
||||
const gen = generation
|
||||
dbTableOps
|
||||
@@ -370,7 +448,10 @@
|
||||
const sizedWidths = Object.fromEntries(
|
||||
[...sizedColumns].filter((f) => widths[f] !== undefined).map((f) => [f, widths[f]])
|
||||
)
|
||||
if (Object.keys(sizedWidths).length) layout.widths = sizedWidths
|
||||
if (Object.keys(sizedWidths).length) {
|
||||
layout.widths = sizedWidths
|
||||
layout.widthsFitFilterButton = true
|
||||
}
|
||||
if (Object.keys(pinned).length) layout.pinned = $state.snapshot(pinned)
|
||||
if (joins.length) layout.joins = $state.snapshot(joins)
|
||||
if (hidden.length) layout.hidden = $state.snapshot(hidden)
|
||||
@@ -381,6 +462,8 @@
|
||||
// ── Column widths ────────────────────────────────────────────────────────
|
||||
let widths: Record<string, number> = $state({ ...storedLayout.widths })
|
||||
let sizedColumns = new Set<string>(Object.keys(storedLayout.widths ?? {}))
|
||||
// Widths saved before headers had a filter button can be too narrow for their label.
|
||||
let widenStoredWidths = !storedLayout.widthsFitFilterButton
|
||||
let autoSizedFor: ColumnDef[] | undefined
|
||||
|
||||
let measureCtx: CanvasRenderingContext2D | null | undefined
|
||||
@@ -396,16 +479,32 @@
|
||||
const family = getComputedStyle(scrollEl).fontFamily
|
||||
const rows = loadedRows().slice(0, 300)
|
||||
const next = { ...widths }
|
||||
const headerWidth = (col: ColumnDef) =>
|
||||
textWidth(col.field, `600 12px ${family}`) +
|
||||
HEADER_CHROME +
|
||||
(col.isprimarykey || fkByColumn[col.field] || joinedAliases.has(col.field)
|
||||
? HEADER_ICON_WIDTH
|
||||
: 0) +
|
||||
(pinned[col.field] ? PIN_CHROME : 0) +
|
||||
(filterSchema.keyOfColumn[col.field] ? HEADER_FILTER_WIDTH : 0)
|
||||
for (const col of columns) {
|
||||
if (only ? !only.includes(col.field) : sizedColumns.has(col.field)) continue
|
||||
let w = textWidth(col.field, `600 12px ${family}`) + HEADER_CHROME
|
||||
if (only ? !only.includes(col.field) : sizedColumns.has(col.field)) {
|
||||
if (!only && widenStoredWidths && next[col.field] !== undefined)
|
||||
next[col.field] = Math.ceil(
|
||||
Math.max(next[col.field], Math.min(MAX_AUTO_COL_WIDTH, headerWidth(col)))
|
||||
)
|
||||
continue
|
||||
}
|
||||
let w = headerWidth(col)
|
||||
for (const row of rows) {
|
||||
const text = formatCell(row[col.field]).slice(0, 200) || 'NULL'
|
||||
w = Math.max(w, textWidth(text, `400 12px ${family}`) + CELL_PADDING)
|
||||
}
|
||||
next[col.field] = Math.round(Math.min(MAX_AUTO_COL_WIDTH, Math.max(MIN_COL_WIDTH, w)))
|
||||
// Rounded up: a label a fraction of a pixel wider than its cell is cut.
|
||||
next[col.field] = Math.ceil(Math.min(MAX_AUTO_COL_WIDTH, Math.max(MIN_COL_WIDTH, w)))
|
||||
sizedColumns.add(col.field)
|
||||
}
|
||||
if (!only) widenStoredWidths = false
|
||||
widths = next
|
||||
saveLayout()
|
||||
}
|
||||
@@ -922,6 +1021,96 @@
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#snippet headerFilterButton(col: ColumnDef, key: string)}
|
||||
{@const boolean = dbColumnKind(col.datatype) === 'boolean'}
|
||||
{@const number = dbColumnKind(col.datatype) === 'number'}
|
||||
{@const active = filters[key] !== undefined && filters[key] !== ''}
|
||||
{@const open = headerFilter?.column === col.field}
|
||||
<Popover
|
||||
floatingConfig={{ strategy: 'fixed', placement: 'bottom-start' }}
|
||||
closeFocus={() => headerFilterCloseFocus(col.field)}
|
||||
bind:isOpen={
|
||||
() => open,
|
||||
(isOpen) => {
|
||||
if (isOpen) {
|
||||
flushHeaderFilter()
|
||||
headerFilter = { column: col.field, key, draft: active ? String(filters[key]) : '' }
|
||||
} else if (open) closeHeaderFilter()
|
||||
}
|
||||
}
|
||||
class={twMerge(
|
||||
'mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded hover:bg-surface-hover',
|
||||
active || open
|
||||
? 'text-accent'
|
||||
: 'text-secondary opacity-0 group-hover/header:opacity-100 focus-visible:opacity-100'
|
||||
)}
|
||||
triggerAttrs={{
|
||||
'aria-label': `Filter ${col.field}`,
|
||||
title: active ? `Filtered: ${filters[key]}` : `Filter ${col.field}`
|
||||
}}
|
||||
>
|
||||
{#snippet trigger()}
|
||||
<Filter size={12} />
|
||||
{/snippet}
|
||||
{#snippet content()}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div class="flex w-64 flex-col gap-2 p-3" onkeydown={escapeClosesOnly(closeHeaderFilter)}>
|
||||
<span class="truncate text-xs font-semibold text-emphasis">Filter {col.field}</span>
|
||||
{#if boolean}
|
||||
<Select
|
||||
items={[
|
||||
{ label: 'true', value: 'true' },
|
||||
{ label: 'false', value: 'false' }
|
||||
]}
|
||||
bind:value={
|
||||
() => headerFilterDraft(key) || undefined,
|
||||
(v) => {
|
||||
if (headerFilter) headerFilter.draft = v ?? ''
|
||||
setHeaderFilter(key, true, v ?? '')
|
||||
}
|
||||
}
|
||||
placeholder="Value"
|
||||
size="sm"
|
||||
/>
|
||||
{:else}
|
||||
<TextInput
|
||||
bind:value={() => headerFilterDraft(key), (v) => typeHeaderFilter(key, String(v ?? ''))}
|
||||
size="sm"
|
||||
inputProps={{
|
||||
placeholder: number ? '10, >10, <=5' : 'Contains',
|
||||
'aria-label': `Filter ${col.field}`,
|
||||
onkeydown: (e: KeyboardEvent) => {
|
||||
if (e.key === 'Enter') closeHeaderFilter()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<span class="text-2xs text-secondary">
|
||||
{number
|
||||
? 'A number, or a comparison: =, >, >=, <, <=, !='
|
||||
: 'Rows whose value contains this text. Start with = for an exact match.'}
|
||||
</span>
|
||||
{/if}
|
||||
{#if active}
|
||||
<div class="flex justify-end">
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
onClick={() => {
|
||||
pendingHeaderFilter = undefined
|
||||
clearTimeout(headerFilterTimer)
|
||||
setHeaderFilter(key, boolean, '')
|
||||
headerFilter = undefined
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/snippet}
|
||||
</Popover>
|
||||
{/snippet}
|
||||
|
||||
{#snippet addColumnHeader()}
|
||||
{#if canAddColumn}
|
||||
<div
|
||||
@@ -1035,18 +1224,23 @@
|
||||
/>
|
||||
|
||||
<div class="h-full relative flex flex-col">
|
||||
<div class="flex justify-between items-center bg-surface-input pr-2">
|
||||
<FilterSearchbar
|
||||
class="grow rounded-none !border-0"
|
||||
size="lg"
|
||||
searchIconPosition="left"
|
||||
dropdownMaxWidth={480}
|
||||
dropdownOffsetY={1}
|
||||
schema={filterSchema.schema}
|
||||
bind:value={filters}
|
||||
placeholder="Search, or filter by column..."
|
||||
/>
|
||||
<div class="flex shrink-0 items-center gap-2 text-xs text-secondary">
|
||||
<div class="flex flex-wrap justify-between items-center bg-surface-input pr-2">
|
||||
<!-- The search bar stops its mousedown, which an open header filter would take as an
|
||||
outside click; close that popover first so the bar gets the focus. -->
|
||||
<div class="contents" onmousedowncapture={() => headerFilter && closeHeaderFilter()}>
|
||||
<FilterSearchbar
|
||||
class="grow min-w-48 rounded-none !border-0"
|
||||
size="lg"
|
||||
searchIconPosition="left"
|
||||
dropdownMaxWidth={480}
|
||||
dropdownOffsetY={1}
|
||||
schema={filterSchema.schema}
|
||||
bind:value={filters}
|
||||
placeholder="Search, or filter by column..."
|
||||
/>
|
||||
</div>
|
||||
<!-- Wraps under the search bar in a narrow panel rather than being cut off. -->
|
||||
<div class="ml-auto flex shrink-0 items-center gap-2 pl-2 text-xs text-secondary">
|
||||
{#if totalRows > 0 && endRow !== 0}
|
||||
<span class="whitespace-nowrap">
|
||||
{Math.min(firstVisible + 1, totalRows)}–{Math.min(lastVisible, totalRows)}
|
||||
@@ -1055,14 +1249,16 @@
|
||||
{/if}
|
||||
</span>
|
||||
{/if}
|
||||
<Button
|
||||
startIcon={{ icon: Download }}
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
iconOnly
|
||||
title="Download loaded rows as CSV"
|
||||
onClick={downloadCsv}
|
||||
/>
|
||||
{#if !disableDownload}
|
||||
<Button
|
||||
startIcon={{ icon: Download }}
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
iconOnly
|
||||
title="Download loaded rows as CSV"
|
||||
onClick={downloadCsv}
|
||||
/>
|
||||
{/if}
|
||||
<div class="flex" bind:this={columnsAnchor}>
|
||||
<Popover
|
||||
floatingConfig={{ strategy: 'fixed', placement: 'bottom-end' }}
|
||||
@@ -1082,7 +1278,12 @@
|
||||
</Button>
|
||||
{/snippet}
|
||||
{#snippet content()}
|
||||
<div class="flex w-60 flex-col py-1" data-testid="db-columns-picker">
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="flex w-60 flex-col py-1"
|
||||
data-testid="db-columns-picker"
|
||||
onkeydown={escapeClosesOnly(() => (columnsPickerOpen = false))}
|
||||
>
|
||||
<label
|
||||
class="flex cursor-pointer items-center gap-2 border-b px-3 py-1.5 text-xs font-medium text-emphasis hover:bg-surface-hover"
|
||||
>
|
||||
@@ -1214,7 +1415,7 @@
|
||||
{/if}
|
||||
<div
|
||||
class={twMerge(
|
||||
'relative shrink-0 flex items-center border-r',
|
||||
'group/header relative shrink-0 flex items-center border-r',
|
||||
// Above the other header cells, whose resize handles sit at z-10.
|
||||
pin ? 'sticky z-20 bg-surface-tertiary dark:bg-surface-input' : '',
|
||||
// The pinned block's edge against the scrolling columns is a pixel thicker.
|
||||
@@ -1251,6 +1452,9 @@
|
||||
<Icon size={12} class="shrink-0 text-secondary" />
|
||||
{/if}
|
||||
</button>
|
||||
{#if filterSchema.keyOfColumn[col.field]}
|
||||
{@render headerFilterButton(col, filterSchema.keyOfColumn[col.field])}
|
||||
{/if}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="absolute -right-1 top-0 bottom-0 w-2 z-10 cursor-col-resize hover:bg-border-selected/50"
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
import { onDestroy, onMount, setContext, untrack } from 'svelte'
|
||||
import DarkModeToggle from '$lib/components/sidebar/DarkModeToggle.svelte'
|
||||
import { page } from '$app/state'
|
||||
import { isFromWindowEmbedder } from '$lib/utils/embedderMessage'
|
||||
import { getUserExt } from '$lib/user'
|
||||
import FlowPreviewButtons from './flows/header/FlowPreviewButtons.svelte'
|
||||
import FlowModuleSchemaMap from './flows/map/FlowModuleSchemaMap.svelte'
|
||||
@@ -271,8 +272,8 @@
|
||||
modeInitialized = true
|
||||
}
|
||||
|
||||
const el = (event) => {
|
||||
// sendUserToast(`Received message from parent ${event.data.type}`, true)
|
||||
const el = (event: MessageEvent) => {
|
||||
if (!isFromWindowEmbedder(event)) return
|
||||
if (event.data.type == 'runTest') {
|
||||
runTest()
|
||||
event.preventDefault()
|
||||
|
||||
@@ -402,6 +402,7 @@
|
||||
scope={aiReviewScope}
|
||||
source="draft_diff"
|
||||
info={aiChat.loadedSessionAiTarget?.info}
|
||||
defaultModel={aiChat.isSessionChat ? aiChat.currentModel : undefined}
|
||||
/>
|
||||
{/key}
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,6 +16,7 @@
|
||||
nodeId?: string | undefined
|
||||
result: any
|
||||
disableTooltips?: boolean
|
||||
disableExpand?: boolean
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -25,7 +26,8 @@
|
||||
jobId = undefined,
|
||||
nodeId = undefined,
|
||||
result,
|
||||
disableTooltips = false
|
||||
disableTooltips = false,
|
||||
disableExpand = false
|
||||
}: Props = $props()
|
||||
|
||||
const dispatch = createEventDispatcher()
|
||||
@@ -86,7 +88,9 @@
|
||||
<button onclick={() => copyToClipboard(toJsonStr(result))}>
|
||||
<ClipboardCopy size={14} />
|
||||
</button>
|
||||
<button onclick={() => dispatch('open-drawer')}>
|
||||
<Expand size={14} />
|
||||
</button>
|
||||
{#if !disableExpand}
|
||||
<button onclick={() => dispatch('open-drawer')}>
|
||||
<Expand size={14} />
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -112,6 +112,15 @@
|
||||
|
||||
let neverLoaded = $state(true)
|
||||
|
||||
// Inline helper code comes from the editor, whose content can be seeded from a link: running it
|
||||
// as soon as the form mounts would execute code the viewer never chose to run. Wait for the
|
||||
// dropdown to be opened before loading; deployed helpers keep loading eagerly.
|
||||
let openedOnce = $state(false)
|
||||
$effect(() => {
|
||||
if (open) openedOnce = true
|
||||
})
|
||||
let canLoad = $derived(helperScript?.source !== 'inline' || open || openedOnce)
|
||||
|
||||
$effect(() => {
|
||||
if (_items.value && value !== undefined && isSelect) {
|
||||
if (isMultiple && Array.isArray(value) && Array.isArray(_items.value)) {
|
||||
@@ -175,6 +184,7 @@
|
||||
;[filterText, entrypoint, helperScript]
|
||||
if (
|
||||
resultJobLoader &&
|
||||
canLoad &&
|
||||
(open || neverLoaded || !deepEqual(filterArgs(lastArgs), filterArgs(nargs)))
|
||||
) {
|
||||
neverLoaded = false
|
||||
@@ -193,6 +203,7 @@
|
||||
bind:value
|
||||
items={safeSelectItems(items || [])}
|
||||
placeholder="Select items"
|
||||
onOpen={() => (openedOnce = true)}
|
||||
noItemsMsg={_items.status === 'loading' ? 'Loading...' : 'No items found'}
|
||||
disabled={disabled || _items.status === 'loading'}
|
||||
/>
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
type DBSchema,
|
||||
codeCompletionSessionEnabled,
|
||||
lspTokenStore,
|
||||
needsSuperAdminFor,
|
||||
formatOnSave,
|
||||
vimMode,
|
||||
relativeLineNumbers
|
||||
@@ -112,10 +113,12 @@
|
||||
import { editorPositionMap } from '$lib/utils'
|
||||
import { extToLang, langToExt } from '$lib/editorLangUtils'
|
||||
import { aiChatManager, type AIChatManager } from './copilot/chat/AIChatManager.svelte'
|
||||
import type { Selection } from 'monaco-editor'
|
||||
import { canHavePreprocessor, getPreprocessorModuleCode } from '$lib/script_helpers'
|
||||
import { setMonacoTypescriptOptions } from './monacoLanguagesOptions'
|
||||
import { copilotInfo } from '$lib/aiStore'
|
||||
import { createCodeSelection, type CodeSelection, type CodeSource } from './copilot/chat/context'
|
||||
import { getOpenInSessionHandoff, withEditorFlush } from './sessions/openInSessionContext'
|
||||
import { openSourceInSession } from './sessions/sessionSwitch.svelte'
|
||||
import { getDbSchemas } from './apps/components/display/dbtable/metadata'
|
||||
import { rawAppLintStore, type MonacoLintError } from './raw_apps/lintStore'
|
||||
import { MarkerSeverity } from 'monaco-editor'
|
||||
@@ -168,7 +171,10 @@
|
||||
loadAsync?: boolean
|
||||
key?: string | undefined
|
||||
class?: string | undefined
|
||||
moduleId?: string
|
||||
/** The item an AI session is told the selected code belongs to. Unset for code of no item. */
|
||||
codeSource?: CodeSource
|
||||
/** The language an AI session is told the code is in, when `scriptLang` only colours it. */
|
||||
codeSourceLang?: CodeSelection['lang']
|
||||
enablePreprocessorSnippet?: boolean
|
||||
/** When set, enables raw app lint collection mode and reports Monaco markers to the lint store under this key */
|
||||
rawAppRunnableKey?: string | undefined
|
||||
@@ -210,7 +216,8 @@
|
||||
loadAsync = false,
|
||||
key = undefined,
|
||||
class: clazz = undefined,
|
||||
moduleId = undefined,
|
||||
codeSource = undefined,
|
||||
codeSourceLang = undefined,
|
||||
enablePreprocessorSnippet = false,
|
||||
rawAppRunnableKey = undefined,
|
||||
preparedAssetsSqlQueries,
|
||||
@@ -282,6 +289,22 @@
|
||||
const completionInfo = $derived(
|
||||
sessionScopedChatManager ? sessionScopedChatManager.aiInfo : $copilotInfo
|
||||
)
|
||||
const sessionHandoff = getOpenInSessionHandoff()
|
||||
const inIframe = BROWSER && window.self !== window.top
|
||||
// The item's own hand-off: one of another kind is an outer editor's.
|
||||
const handoffSource = $derived.by(() => {
|
||||
if (!codeSource) return undefined
|
||||
const source = sessionHandoff?.source(
|
||||
codeSource.kind === 'flow' ? { moduleId: codeSource.part } : undefined
|
||||
)
|
||||
return source?.target?.kind === codeSource.kind ? source : undefined
|
||||
})
|
||||
// The path the item's draft is stored under, which the session's tools read it by.
|
||||
const codePath = $derived(handoffSource?.target?.path || codeSource?.path)
|
||||
// In a session, ⌘K goes to its chat instead.
|
||||
const newSessionSource = $derived(
|
||||
sessionScopedChatManager || inIframe || !$copilotInfo.enabled ? undefined : handoffSource
|
||||
)
|
||||
// let graphqlService: MonacoGraphQLAPI | undefined = undefined
|
||||
|
||||
let fetchedDbSchema: DBSchema | undefined = $state(undefined)
|
||||
@@ -398,18 +421,56 @@
|
||||
}
|
||||
}
|
||||
|
||||
export function getSelectedLines(): string | undefined {
|
||||
if (editor) {
|
||||
const selection = editor.getSelection()
|
||||
if (selection) {
|
||||
const range: IRange = {
|
||||
startLineNumber: selection.startLineNumber,
|
||||
/** The selected lines, whole, or the cursor's line. */
|
||||
function getCodeSelection(): CodeSelection | undefined {
|
||||
const selection = editor?.getSelection()
|
||||
const model = editor?.getModel()
|
||||
if (!selection || !model || !codeSource || !codePath || !scriptLang) return undefined
|
||||
const { startLineNumber: startLine, endLineNumber, endColumn } = selection
|
||||
// A selection dragged to the start of a line holds none of it.
|
||||
const endLine =
|
||||
endColumn === 1 && endLineNumber > startLine ? endLineNumber - 1 : endLineNumber
|
||||
return createCodeSelection(
|
||||
{ ...codeSource, path: codePath },
|
||||
{
|
||||
startLine,
|
||||
endLine,
|
||||
content: model.getValueInRange({
|
||||
startLineNumber: startLine,
|
||||
startColumn: 1,
|
||||
endLineNumber: selection.endLineNumber + 1,
|
||||
endColumn: 1
|
||||
}
|
||||
return editor.getModel()?.getValueInRange(range)
|
||||
endLineNumber: endLine,
|
||||
endColumn: model.getLineMaxColumn(endLine)
|
||||
}),
|
||||
lang: codeSourceLang ?? (scriptLang as CodeSelection['lang'])
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
async function sendInlinePrompt(prompt: string): Promise<boolean> {
|
||||
const selection = getCodeSelection()
|
||||
if (!selection || !newSessionSource) return false
|
||||
try {
|
||||
await openSourceInSession(withEditorFlush(newSessionSource, flushPendingChanges), {
|
||||
seedPrompt: prompt,
|
||||
autoSend: true,
|
||||
seedPick: selection
|
||||
})
|
||||
} catch (e) {
|
||||
sendUserToast(e instanceof Error ? e.message : String(e), true)
|
||||
return false
|
||||
}
|
||||
closeAIInlineWidget()
|
||||
return true
|
||||
}
|
||||
|
||||
/** Go to the session's chat, with the selected lines. Outside a session no chat is on screen. */
|
||||
function attachSelectionToChat() {
|
||||
if (!sessionScopedChatManager) return
|
||||
const selection = editor?.getSelection()?.isEmpty() ? undefined : getCodeSelection()
|
||||
if (selection) {
|
||||
sessionScopedChatManager.attachCodeSelection(selection)
|
||||
} else {
|
||||
sessionScopedChatManager.focusInput()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -982,8 +1043,6 @@
|
||||
|
||||
// Inline ai chat widget
|
||||
let showInlineAIChat = $state(false)
|
||||
let inlineAIChatSelection: Selection | null = $state(null)
|
||||
let selectedCode = $state('')
|
||||
|
||||
export async function reviewAndApplyCode(code: string, opts?: ReviewChangesOpts) {
|
||||
await aiChatEditorHandler?.reviewChanges(code, opts)
|
||||
@@ -1618,9 +1677,6 @@
|
||||
editor?.addCommand(KeyMod.CtrlCmd | KeyCode.DownArrow, function () {
|
||||
if (aiChatManager.pendingNewCode) {
|
||||
aiChatManager.scriptEditorApplyCode?.(aiChatManager.pendingNewCode)
|
||||
if (showInlineAIChat) {
|
||||
closeAIInlineWidget()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1649,35 +1705,16 @@
|
||||
})
|
||||
|
||||
editor?.addCommand(KeyMod.CtrlCmd | KeyCode.KeyL, function () {
|
||||
const selectedLines = getSelectedLines()
|
||||
const selection = editor?.getSelection()
|
||||
const hasSelection =
|
||||
selection &&
|
||||
(selection.startLineNumber !== selection.endLineNumber ||
|
||||
selection.startColumn !== selection.endColumn)
|
||||
// Only a session pane has a chat on screen to send the lines to.
|
||||
const chat = sessionScopedChatManager
|
||||
if (!chat) return
|
||||
if (hasSelection && selectedLines) {
|
||||
chat.addSelectedLinesToContext(
|
||||
selectedLines,
|
||||
selection.startLineNumber,
|
||||
selection.endLineNumber,
|
||||
moduleId
|
||||
)
|
||||
} else {
|
||||
chat.focusInput()
|
||||
}
|
||||
// Monaco runs a command for whichever editor has focus, this one or not.
|
||||
if (editor?.hasWidgetFocus()) attachSelectionToChat()
|
||||
})
|
||||
|
||||
editor?.addCommand(KeyMod.CtrlCmd | KeyCode.KeyK, function () {
|
||||
if ($copilotInfo.enabled) {
|
||||
aiChatEditorHandler?.rejectAll()
|
||||
if (showInlineAIChat) {
|
||||
closeAIInlineWidget()
|
||||
} else {
|
||||
showAIInlineWidget()
|
||||
}
|
||||
if (!editor?.hasWidgetFocus()) return
|
||||
if (newSessionSource) {
|
||||
showInlineAIChat = !showInlineAIChat
|
||||
} else {
|
||||
attachSelectionToChat()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1896,30 +1933,10 @@
|
||||
})
|
||||
}
|
||||
|
||||
function showAIInlineWidget() {
|
||||
if (!editor) return
|
||||
|
||||
inlineAIChatSelection = editor.getSelection()
|
||||
if (!inlineAIChatSelection) {
|
||||
return
|
||||
}
|
||||
const model = editor.getModel()
|
||||
selectedCode = ''
|
||||
if (model) {
|
||||
selectedCode = model.getValueInRange(inlineAIChatSelection)
|
||||
}
|
||||
showInlineAIChat = true
|
||||
aiChatInlineWidget?.focusInput()
|
||||
}
|
||||
|
||||
function closeAIInlineWidget() {
|
||||
showInlineAIChat = false
|
||||
inlineAIChatSelection = null
|
||||
selectedCode = ''
|
||||
}
|
||||
|
||||
let aiChatInlineWidget: AIChatInlineWidget | null = $state(null)
|
||||
|
||||
$effect(() => {
|
||||
const fontSize = small ? editorFontSize.small : editorFontSize.regular
|
||||
if (editor) {
|
||||
@@ -1968,14 +1985,23 @@
|
||||
})
|
||||
|
||||
async function genRoot(hostname: string) {
|
||||
let token = $lspTokenStore
|
||||
const workspace = $operatingWorkspace ?? ''
|
||||
const cached = $lspTokenStore
|
||||
let token = cached?.workspace === workspace ? cached.token : undefined
|
||||
if (!token) {
|
||||
let expiration = new Date()
|
||||
expiration.setHours(expiration.getHours() + 72)
|
||||
const newToken = await UserService.createToken({
|
||||
requestBody: { label: 'Ephemeral lsp token', expiration: expiration.toISOString() }
|
||||
requestBody: {
|
||||
label: 'Ephemeral lsp token',
|
||||
expiration: expiration.toISOString(),
|
||||
workspace_id: workspace || undefined,
|
||||
// It reads the scripts an import names as the editing user would, admin included.
|
||||
admin: true,
|
||||
super_admin: needsSuperAdminFor(workspace)
|
||||
}
|
||||
})
|
||||
$lspTokenStore = newToken
|
||||
$lspTokenStore = { workspace, token: newToken }
|
||||
token = newToken
|
||||
}
|
||||
let root = hostname + '/api/scripts_u/tokened_raw/' + $operatingWorkspace + '/' + token
|
||||
@@ -2008,9 +2034,6 @@
|
||||
rejectCodeChanges()
|
||||
} else if ((e.ctrlKey || e.metaKey) && e.key === 'ArrowDown' && aiChatManager.pendingNewCode) {
|
||||
acceptCodeChanges()
|
||||
if (showInlineAIChat) {
|
||||
closeAIInlineWidget()
|
||||
}
|
||||
}
|
||||
}
|
||||
$effect(() => {
|
||||
@@ -2250,14 +2273,15 @@
|
||||
<GlobalReviewButtons onAcceptAll={acceptCodeChanges} onRejectAll={rejectCodeChanges} />
|
||||
{/if}
|
||||
|
||||
{#if editor && $copilotInfo.enabled && aiChatEditorHandler}
|
||||
{#if editor && showInlineAIChat && newSessionSource}
|
||||
<AIChatInlineWidget
|
||||
bind:this={aiChatInlineWidget}
|
||||
bind:show={showInlineAIChat}
|
||||
{editor}
|
||||
editorHandler={aiChatEditorHandler}
|
||||
selection={inlineAIChatSelection}
|
||||
{selectedCode}
|
||||
line={editor.getSelection()?.startLineNumber ?? 1}
|
||||
onSend={sendInlinePrompt}
|
||||
onClose={(refocus) => {
|
||||
closeAIInlineWidget()
|
||||
if (refocus) editor?.focus()
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -417,11 +417,14 @@
|
||||
let highlightedIndex = $state(0)
|
||||
let taggedTextInput: TaggedTextInput | undefined = $state()
|
||||
|
||||
// A key is letters, digits and `_` in any script; `\b` and `\w` only know ASCII ones.
|
||||
const KEY_START = '(?<![\\p{L}\\p{N}_])'
|
||||
|
||||
let tags = $derived(
|
||||
Object.entries(schema)
|
||||
.filter(([_, s]) => !s.hidden)
|
||||
.map(([key, filterSchema]) => ({
|
||||
regex: new RegExp(`\\b${key}:(?:\\\\.|[^\\s])*`, 'g'),
|
||||
regex: new RegExp(`${KEY_START}${key}:(?:\\\\.|[^\\s])*`, 'gu'),
|
||||
id: key,
|
||||
onClear: () => (delete value[key], asText.reparse())
|
||||
}))
|
||||
@@ -429,18 +432,18 @@
|
||||
|
||||
let keyHighlightRegex = $derived(
|
||||
new RegExp(
|
||||
`\\b(${Object.entries(schema)
|
||||
`${KEY_START}(${Object.entries(schema)
|
||||
.filter(([_, s]) => !s.hidden)
|
||||
.map(([k]) => k)
|
||||
.join('|')}):`,
|
||||
'g'
|
||||
'gu'
|
||||
)
|
||||
)
|
||||
|
||||
let errorKeys = $derived(new Set(errors.flatMap((e) => e.fields)))
|
||||
let errorHighlights = $derived(
|
||||
[...errorKeys].map((key) => ({
|
||||
regex: new RegExp(`(?<=\\b${key}:)(?:\\\\.|[^\\s])+`),
|
||||
regex: new RegExp(`(?<=${KEY_START}${key}:)(?:\\\\.|[^\\s])+`, 'u'),
|
||||
classes: 'text-red-500 dark:text-red-400'
|
||||
}))
|
||||
)
|
||||
@@ -498,7 +501,8 @@
|
||||
.filter((o) => {
|
||||
if (selectedValues.includes(o.value)) return false
|
||||
if (!searchSuffix) return true
|
||||
return o.value.includes(searchSuffix)
|
||||
const q = searchSuffix.toLowerCase()
|
||||
return [o.value, o.label].some((t) => t?.toLowerCase().includes(q))
|
||||
})
|
||||
.map((option) => ({
|
||||
type: 'option' as const,
|
||||
@@ -567,7 +571,7 @@
|
||||
highlightedIndex = 0
|
||||
})
|
||||
|
||||
const kvRegex = /\b(\w+):((?:[^\s\\]|\\.)*)/g
|
||||
const kvRegex = new RegExp(`${KEY_START}([\\p{L}\\p{N}_]+):((?:[^\\s\\\\]|\\\\.)*)`, 'gu')
|
||||
|
||||
function parseFromText(text: string): Partial<FilterInstanceRec<SchemaT>> {
|
||||
const parsed: Record<string, string> = {}
|
||||
@@ -811,7 +815,16 @@
|
||||
{autofocus}
|
||||
/>
|
||||
{#if asText.val}
|
||||
<CloseButton small class="mr-1.5" onClick={() => (_value.current = {})} />
|
||||
<CloseButton
|
||||
small
|
||||
class="mr-1.5"
|
||||
onClick={() => {
|
||||
_value.current = {}
|
||||
// On a closed bar this click's mousedown just wrote the text, and the text skips the
|
||||
// filter change that follows its own write: left to that sync, the old text stays.
|
||||
asText.reparse()
|
||||
}}
|
||||
/>
|
||||
{:else if searchIconPosition === 'right'}
|
||||
<div class="mr-3">
|
||||
<SearchIcon size={16} class="text-hint" />
|
||||
|
||||
@@ -138,6 +138,7 @@
|
||||
import { editInForkAllowed, editInForkLabel, openEditInFork } from '$lib/utils/editInFork'
|
||||
import { isCloudHosted } from '$lib/cloud'
|
||||
import { UserDraft } from '$lib/userDraft.svelte'
|
||||
import { assertDraftSaved } from './sessions/pageDrawerSession'
|
||||
import { setOpenInSessionHandoff } from './sessions/openInSessionContext'
|
||||
import { getEditorStoragePath, setEditorStoragePath } from './editorStoragePathContext'
|
||||
import { useEditRights, useRoleCapabilities, useTriggerLock } from '$lib/operatorWriteRights'
|
||||
@@ -494,9 +495,15 @@
|
||||
// discardIf baseline, safe only when there is none.
|
||||
async function persistDraftForSession(): Promise<void> {
|
||||
await saveDraft()
|
||||
if (opWorkspace && liveEditorDraftStoragePath && newFlow) {
|
||||
if (!opWorkspace || !liveEditorDraftStoragePath) return
|
||||
if (newFlow) {
|
||||
await UserDraft.forcePersist('flow', liveEditorDraftStoragePath, { workspace: opWorkspace })
|
||||
}
|
||||
assertDraftSaved({
|
||||
workspace: opWorkspace,
|
||||
itemKind: 'flow',
|
||||
path: liveEditorDraftStoragePath
|
||||
})
|
||||
}
|
||||
|
||||
export function computeUnlockedSteps(flow: Flow) {
|
||||
@@ -1034,18 +1041,16 @@
|
||||
const outerStoragePath = getEditorStoragePath()
|
||||
setEditorStoragePath(() => liveEditorDraftStoragePath ?? outerStoragePath?.())
|
||||
|
||||
// "Open in AI session" target: the URL draft path the editor loads/saves by
|
||||
// (which for a new flow differs from the live-edited friendly `$pathStore`),
|
||||
// falling back to `$pathStore` in drawer mounts that carry no storage path.
|
||||
const sessionTargetPath = $derived(liveEditorDraftStoragePath || $pathStore)
|
||||
|
||||
const aiBuilderShown = $derived(!disableAi && customUi?.topBar?.aiBuilder != false)
|
||||
const showFlowAiButton = $derived(aiBuilderShown && $roleCaps.flows !== 'compose')
|
||||
|
||||
// Targets the draft path the editor loads/saves by, which for a new flow differs from
|
||||
// the live-edited friendly `$pathStore`. A drawer mount has none: its edits are in no
|
||||
// draft, so leaving for a session would lose them.
|
||||
const sessionOpen = $derived(
|
||||
sessionTargetPath
|
||||
indicatorPath
|
||||
? {
|
||||
target: { kind: 'flow' as const, path: sessionTargetPath },
|
||||
target: { kind: 'flow' as const, path: indicatorPath },
|
||||
workspaceId: opWorkspace ?? undefined,
|
||||
beforeOpen: persistDraftForSession
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@
|
||||
initial?: boolean
|
||||
selectedJobStep?: string | undefined
|
||||
selectedJobStepIsTopLevel?: boolean | undefined
|
||||
selectedJobStepType?: 'single' | 'forloop' | 'branchall'
|
||||
selectedJobStepType?: 'single' | 'forloop' | 'branchall' | 'parallel'
|
||||
rightColumnSelect?: 'timeline' | 'node_status' | 'node_definition' | 'user_states'
|
||||
branchOrIterationN?: number
|
||||
scrollTop?: number
|
||||
@@ -419,16 +419,20 @@
|
||||
-->
|
||||
<FlowRestartButton
|
||||
{jobId}
|
||||
{selectedJobStep}
|
||||
selectedJobStep={restart.restartStepId ?? selectedJobStep}
|
||||
selectedJobStepType={restart.selectedJobStepType}
|
||||
parallelFailedCount={restart.parallelFailedCount}
|
||||
parallelUnit={restart.parallelUnit}
|
||||
restartBranchNames={restart.restartBranchNames}
|
||||
presetIterationN={restart.topLevelLoopIteration}
|
||||
iterationCounts={restart.iterationCounts}
|
||||
onRestart={(stepId, branchOrIterationN) => {
|
||||
onRestart={(stepId, branchOrIterationN, _flowVersion, failedOnly, fromFailedStep) => {
|
||||
runPreview(previewArgs.val, {
|
||||
flow_job_id: jobId,
|
||||
step_id: stepId,
|
||||
branch_or_iteration_n: branchOrIterationN
|
||||
branch_or_iteration_n: branchOrIterationN,
|
||||
failed_only: failedOnly || undefined,
|
||||
from_failed_step: fromFailedStep || undefined
|
||||
})
|
||||
}}
|
||||
/>
|
||||
@@ -628,7 +632,15 @@
|
||||
</div>
|
||||
|
||||
{#if jobId}
|
||||
<FlowProgressBar {job} bind:this={flowProgressBar} slim textPosition="bottom" showStepId />
|
||||
<FlowProgressBar
|
||||
{job}
|
||||
bind:this={flowProgressBar}
|
||||
slim
|
||||
textPosition="bottom"
|
||||
showStepId
|
||||
stepStates={localModuleStates}
|
||||
waitingNested={Object.keys(suspendStatus?.val ?? {}).length > 0}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if job}
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
import { Badge, Button } from './common'
|
||||
import Popover from './meltComponents/Popover.svelte'
|
||||
import { ChevronDown, Play, RefreshCw } from 'lucide-svelte'
|
||||
import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte'
|
||||
import Toggle from './Toggle.svelte'
|
||||
import { FlowService, JobService, type FlowVersion } from '$lib/gen'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
|
||||
@@ -11,7 +14,14 @@
|
||||
interface Props {
|
||||
jobId: string
|
||||
selectedJobStep: string
|
||||
selectedJobStepType: 'single' | 'forloop' | 'branchall'
|
||||
selectedJobStepType: 'single' | 'forloop' | 'branchall' | 'parallel'
|
||||
/**
|
||||
* For a parallel step: how many of its iterations (branches) failed in the
|
||||
* run, when known. Rerunning only those is offered unless it is zero.
|
||||
*/
|
||||
parallelFailedCount?: number
|
||||
/** What a parallel step reruns: its loop's iterations or its branches. */
|
||||
parallelUnit?: 'iterations' | 'branches'
|
||||
restartBranchNames?: [number, string][]
|
||||
flowPath?: string
|
||||
/** The flow version ID used in this run (from job.script_hash) */
|
||||
@@ -57,7 +67,13 @@
|
||||
*/
|
||||
nestedPathIterationCounts?: Record<string, number>
|
||||
/** Called when flow is restarted. If not provided, will navigate to the new run using goto (requires SvelteKit) */
|
||||
onRestart?: (stepId: string, branchOrIterationN: number, flowVersion?: number) => void
|
||||
onRestart?: (
|
||||
stepId: string,
|
||||
branchOrIterationN: number,
|
||||
flowVersion?: number,
|
||||
failedOnly?: boolean,
|
||||
fromFailedStep?: boolean
|
||||
) => void
|
||||
/** Called when flow restart completes with the new job ID. Used for navigation in non-SvelteKit contexts */
|
||||
onRestartComplete?: (newJobId: string) => void
|
||||
}
|
||||
@@ -66,6 +82,8 @@
|
||||
jobId,
|
||||
selectedJobStep,
|
||||
selectedJobStepType,
|
||||
parallelFailedCount = undefined,
|
||||
parallelUnit = 'iterations',
|
||||
restartBranchNames = [],
|
||||
flowPath = undefined,
|
||||
flowVersionId = undefined,
|
||||
@@ -100,6 +118,8 @@
|
||||
const RUN_VERSION_SENTINEL = -1
|
||||
|
||||
let branchOrIterationN = $state(0)
|
||||
let rerun: 'failed' | 'all' = $state('failed')
|
||||
let fromFailedStep = $state(false)
|
||||
|
||||
// Iteration inputs for nested-step restart inside one or more ForLoop ancestors.
|
||||
// Each editable position keeps a local copy that the popup can mutate; on
|
||||
@@ -110,6 +130,21 @@
|
||||
type IterField = { key: 'top' | `inner-${number}`; label: string; value: number }
|
||||
let iterationEdits: Record<string, number> = $state({})
|
||||
|
||||
// The count describes the outer iterations the graph shows, so it is unknown once the
|
||||
// popup restarts another one.
|
||||
const failedCount = $derived(
|
||||
Object.entries(iterationEdits).some(([key, value]) =>
|
||||
key === 'top'
|
||||
? value !== nestedTopBranchOrIterationN
|
||||
: value !== nestedPath?.[Number(key.slice('inner-'.length))]?.branch_or_iteration_n
|
||||
)
|
||||
? undefined
|
||||
: parallelFailedCount
|
||||
)
|
||||
const failedOnly = $derived(
|
||||
selectedJobStepType === 'parallel' && rerun === 'failed' && failedCount !== 0
|
||||
)
|
||||
|
||||
function resetEditsFromProps() {
|
||||
const next: Record<string, number> = {}
|
||||
if (isNested && nestedTopBranchOrIterationN !== undefined) {
|
||||
@@ -123,9 +158,11 @@
|
||||
})
|
||||
}
|
||||
iterationEdits = next
|
||||
if (selectedJobStepType === 'forloop' && presetIterationN !== undefined) {
|
||||
branchOrIterationN = presetIterationN
|
||||
}
|
||||
rerun = parallelFailedCount === 0 ? 'all' : 'failed'
|
||||
fromFailedStep = false
|
||||
// The button outlives the selection, so a previous step's iteration must not carry over.
|
||||
branchOrIterationN =
|
||||
selectedJobStepType === 'forloop' && presetIterationN !== undefined ? presetIterationN : 0
|
||||
}
|
||||
const iterationFields = $derived.by((): IterField[] => {
|
||||
if (!isNested) return []
|
||||
@@ -172,12 +209,16 @@
|
||||
nested_path: nestedPath?.map((entry, i) => ({
|
||||
step_id: entry.step_id,
|
||||
branch_or_iteration_n: iterationEdits[`inner-${i}`] ?? entry.branch_or_iteration_n
|
||||
}))
|
||||
})),
|
||||
failed_only: failedOnly || undefined,
|
||||
from_failed_step: (failedOnly && fromFailedStep) || undefined
|
||||
}
|
||||
: {
|
||||
step_id: stepId,
|
||||
branch_or_iteration_n: branchOrIterationN,
|
||||
flow_version: flowVersion
|
||||
flow_version: flowVersion,
|
||||
failed_only: failedOnly || undefined,
|
||||
from_failed_step: (failedOnly && fromFailedStep) || undefined
|
||||
}
|
||||
let run = await JobService.restartFlowAtStep({
|
||||
workspace: $operatingWorkspace!,
|
||||
@@ -220,7 +261,13 @@
|
||||
|
||||
function handleRestart() {
|
||||
if (onRestart) {
|
||||
onRestart(selectedJobStep, branchOrIterationN, getFlowVersionForRestart())
|
||||
onRestart(
|
||||
selectedJobStep,
|
||||
branchOrIterationN,
|
||||
getFlowVersionForRestart(),
|
||||
failedOnly,
|
||||
failedOnly && fromFailedStep
|
||||
)
|
||||
} else {
|
||||
const flowVersion = getFlowVersionForRestart()
|
||||
restartFlow(selectedJobStep, branchOrIterationN, flowVersion)
|
||||
@@ -328,6 +375,39 @@
|
||||
{/if}
|
||||
</div>
|
||||
</label>
|
||||
{:else if selectedJobStepType === 'parallel'}
|
||||
<div>
|
||||
<div class="pb-1 text-xs font-semibold text-emphasis">
|
||||
Rerun {parallelUnit} of <code class="text-xs">{displayStepId}</code>
|
||||
</div>
|
||||
<ToggleButtonGroup bind:selected={rerun}>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton
|
||||
value="failed"
|
||||
label="Failed only{failedCount ? ` (${failedCount})` : ''}"
|
||||
tooltip="Keep the results that succeeded and rerun the failed ones {fromFailedStep
|
||||
? 'from the step where each failed'
|
||||
: 'from their first step'}, each in its original position"
|
||||
showTooltipIcon
|
||||
disabled={failedCount === 0}
|
||||
{item}
|
||||
/>
|
||||
<ToggleButton value="all" label="All" {item} />
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
{#if failedOnly}
|
||||
<Toggle
|
||||
bind:checked={fromFailedStep}
|
||||
size="xs"
|
||||
class="pt-2"
|
||||
options={{
|
||||
right: 'From the failed step',
|
||||
rightTooltip:
|
||||
'Resume each failed one at the step where it failed, keeping the results of the steps before it'
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if selectedJobStepType === 'branchall'}
|
||||
<label>
|
||||
<div class="pb-1 text-xs font-semibold text-emphasis">From branch</div>
|
||||
|
||||
@@ -97,13 +97,11 @@
|
||||
|
||||
let lastJobId: string = untrack(() => jobId)
|
||||
|
||||
let retryStatus = $state({ val: {} })
|
||||
let globalRefreshes: Record<string, ((clear, root) => Promise<void>)[]> = $state({})
|
||||
|
||||
setContext<FlowStatusViewerContext>('FlowStatusViewer', {
|
||||
flowState,
|
||||
suspendStatus,
|
||||
retryStatus,
|
||||
hideDownloadInGraph: untrack(() => hideDownloadInGraph),
|
||||
hideNodeDefinition: untrack(() => hideNodeDefinition),
|
||||
hideTimeline: untrack(() => hideTimeline),
|
||||
@@ -119,7 +117,6 @@
|
||||
if (jobId !== lastJobId) {
|
||||
console.log('updateJobId 3', jobId)
|
||||
lastJobId = jobId
|
||||
retryStatus.val = {}
|
||||
suspendStatus.val = {}
|
||||
globalRefreshes = {}
|
||||
for (let key in localModuleStates) delete flowState[key]
|
||||
@@ -152,10 +149,17 @@
|
||||
|
||||
let storedToolCallJobs: Record<string, Job> = $state({})
|
||||
let toolCallIndicesToLoad: string[] = $state([])
|
||||
|
||||
let inner: FlowStatusViewerInner | undefined = $state(undefined)
|
||||
/** Selects a step in the graph, as a click on its node does. */
|
||||
export function selectStep(id: string) {
|
||||
inner?.selectStep(id)
|
||||
}
|
||||
</script>
|
||||
|
||||
{#key jobId}
|
||||
<FlowStatusViewerInner
|
||||
bind:this={inner}
|
||||
onJobsLoaded={({ job, force }) => {
|
||||
if (job.script_path != lastScriptPath && job.script_path) {
|
||||
lastScriptPath = job.script_path
|
||||
|
||||
@@ -13,8 +13,10 @@
|
||||
type CompletedJob,
|
||||
type WorkflowStatus,
|
||||
type FlowNote,
|
||||
type FlowValue
|
||||
type FlowValue,
|
||||
ConcurrencyGroupsService
|
||||
} from '$lib/gen'
|
||||
import { getDbClockNow } from '$lib/forLater'
|
||||
import FlowJobResult from './FlowJobResult.svelte'
|
||||
import WorkflowTimeline from './WorkflowTimeline.svelte'
|
||||
import DisplayResult from './DisplayResult.svelte'
|
||||
@@ -84,7 +86,6 @@
|
||||
|
||||
let {
|
||||
flowState: flowStateStore,
|
||||
retryStatus,
|
||||
suspendStatus,
|
||||
hideDownloadInGraph,
|
||||
hideTimeline,
|
||||
@@ -348,6 +349,49 @@
|
||||
|
||||
let selectionManager = new SelectionManager()
|
||||
|
||||
function onGraphSelect(e: string | FlowModule) {
|
||||
subflowPathChain = undefined
|
||||
if (rightColumnSelect != 'node_definition' && rightColumnSelect != 'tracing') {
|
||||
rightColumnSelect = 'node_status'
|
||||
}
|
||||
if (typeof e == 'string') {
|
||||
if (e == 'Input') {
|
||||
selectedNode = 'start'
|
||||
stepDetail = undefined
|
||||
} else if (e == 'Result') {
|
||||
selectedNode = 'end'
|
||||
stepDetail = 'end'
|
||||
} else {
|
||||
const id = e.startsWith(AI_TOOL_CALL_PREFIX) ? e.split('-').pop() : e
|
||||
const resolved = resolveLoadedExpandedSubflowStep(
|
||||
e,
|
||||
job?.raw_flow?.modules ?? [],
|
||||
expandedSubflows ?? {}
|
||||
)
|
||||
stepDetail =
|
||||
resolved?.module ?? dfs(job?.raw_flow?.modules ?? [], (m) => m).find((m) => m?.id === id)
|
||||
subflowPathChain = resolved?.pathChain
|
||||
selectedNode = e
|
||||
if (e.startsWith(AI_TOOL_CALL_PREFIX)) {
|
||||
const [_prefix, agentModuleId, j, _toolModuleId] = e.split('-')
|
||||
const parentLoopsPrefix = getParentLoopsPrefix(agentModuleId)
|
||||
const jIdx = Number(j)
|
||||
const storeKey = parentLoopsPrefix + agentModuleId + '-' + jIdx
|
||||
toolCallStore?.addToolCallToLoad(storeKey)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
stepDetail = e
|
||||
selectedNode = e.id
|
||||
}
|
||||
}
|
||||
|
||||
/** Selects a step from outside the graph, as a click on its node does. */
|
||||
export function selectStep(id: string) {
|
||||
selectionManager.selectId(id)
|
||||
onGraphSelect(id)
|
||||
}
|
||||
|
||||
function onFlowModuleId() {
|
||||
let modId = flowJobIds?.moduleId
|
||||
if (modId) {
|
||||
@@ -588,21 +632,10 @@
|
||||
}
|
||||
updateInnerModules(status)
|
||||
|
||||
// The preprocessor (step -1) and the error handler (past the steps) retry outside `modules`.
|
||||
const outsideSteps = status.step < 0 || status.step >= status.modules.length
|
||||
let count =
|
||||
job?.type === 'CompletedJob' || (retryingStepId == undefined && !outsideSteps)
|
||||
? undefined
|
||||
: status.retry?.fail_count
|
||||
if (count) {
|
||||
retryStatus.val[jobId ?? ''] = count
|
||||
} else if (retryStatus.val[jobId ?? ''] != undefined) {
|
||||
delete retryStatus.val[jobId ?? '']
|
||||
}
|
||||
let jobStatus = job?.flow_status?.modules?.[job?.flow_status.step]
|
||||
|
||||
if (jobStatus && jobStatus.count != undefined) {
|
||||
suspendStatus.val[jobId ?? ''] = { nb: jobStatus.count, job: job! }
|
||||
suspendStatus.val[jobId ?? ''] = { nb: jobStatus.count, job: job!, prefix }
|
||||
} else if (suspendStatus.val[jobId ?? ''] != undefined) {
|
||||
delete suspendStatus.val[jobId ?? '']
|
||||
}
|
||||
@@ -682,6 +715,94 @@
|
||||
|
||||
/** The step waiting for or running its next attempt, if any. */
|
||||
let retryingStepId: string | undefined = undefined
|
||||
|
||||
// A concurrency limit moves a waiting step's due time each time it holds it back, often by
|
||||
// only a few seconds, so a step still waiting once that time has passed is read again, at
|
||||
// most every 5s. The parent flow does not change meanwhile, hence the timer below.
|
||||
const waitingStepChecks = new Map<string, number>()
|
||||
// A step's concurrency key is written as it is queued: one without can never be held, so
|
||||
// past the end of its sleep only a change of the parent flow can change what it waits for.
|
||||
const unlimitedSteps = new Set<string>()
|
||||
function waitingStepDue(mod: FlowStatusModule): boolean {
|
||||
const last = waitingStepChecks.get(mod.job ?? '')
|
||||
if (last != undefined && Date.now() - last < 5000) return false
|
||||
const scheduledFor = localModuleStates[mod.id ?? '']?.scheduled_for
|
||||
return scheduledFor == undefined || new Date(scheduledFor) <= getDbClockNow()
|
||||
}
|
||||
|
||||
function loadWaitingStep(mod: FlowStatusModule, retrying: boolean) {
|
||||
waitingStepChecks.set(mod.job ?? '', Date.now())
|
||||
const workspace = workspaceId ?? $operatingWorkspace ?? ''
|
||||
Promise.all([
|
||||
JobService.getJob({ workspace, id: mod.job ?? '', noLogs: true, noCode: true }),
|
||||
ConcurrencyGroupsService.getConcurrencyKeyStatus({ id: mod.job ?? '' }).catch(() => undefined)
|
||||
])
|
||||
.then(([job, held]) => {
|
||||
// The step may have started or ended while this was in flight.
|
||||
const now = innerModules?.find((m) => m.id === mod.id)
|
||||
if (now?.type !== 'WaitingForExecutor' || now.job !== mod.job) return
|
||||
if (held === null) unlimitedSteps.add(mod.job ?? '')
|
||||
const scheduledFor: string | undefined = job?.['scheduled_for']
|
||||
// Once let in, a held job only waits for a worker.
|
||||
const waiting_reason: GraphModuleState['waiting_reason'] =
|
||||
held?.deferred_from && !held.released_at
|
||||
? 'concurrency'
|
||||
: scheduledFor &&
|
||||
new Date(scheduledFor) > getDbClockNow() &&
|
||||
!retrying &&
|
||||
sleepsBefore(mod.id)
|
||||
? 'sleep'
|
||||
: undefined
|
||||
setModuleState(mod.id ?? '', {
|
||||
type: mod.type,
|
||||
scheduled_for: job?.['scheduled_for'],
|
||||
waiting_reason,
|
||||
concurrency_key: waiting_reason === 'concurrency' ? held?.key : undefined,
|
||||
held_since:
|
||||
waiting_reason === 'concurrency' ? (held?.deferred_from ?? undefined) : undefined,
|
||||
job_id: job?.id,
|
||||
parent_module: failedStepOf(mod),
|
||||
args: job?.args,
|
||||
tag: job?.tag,
|
||||
script_hash: job?.script_hash
|
||||
})
|
||||
// So the timeline draws the wait while it lasts.
|
||||
if (waiting_reason && job?.created_at)
|
||||
setDurationStatusByJob(
|
||||
mod.id ?? '',
|
||||
job.id,
|
||||
{ created_at: new Date(job.created_at).getTime() },
|
||||
true
|
||||
)
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(`Could not load inner module for job ${mod.job}`, e)
|
||||
})
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (job?.type !== 'QueuedJob' || isReplay) return
|
||||
const id = setInterval(() => {
|
||||
innerModules?.forEach((mod) => {
|
||||
if (
|
||||
mod.type === 'WaitingForExecutor' &&
|
||||
(!unlimitedSteps.has(mod.job ?? '') ||
|
||||
localModuleStates[mod.id ?? '']?.waiting_reason === 'sleep') &&
|
||||
waitingStepDue(mod)
|
||||
) {
|
||||
loadWaitingStep(mod, mod.id === retryingStepId)
|
||||
}
|
||||
})
|
||||
}, 5000)
|
||||
return () => clearInterval(id)
|
||||
})
|
||||
|
||||
/** Whether the step before `id` sleeps once done, which pushes `id` back by that long. */
|
||||
function sleepsBefore(id: string | undefined): boolean {
|
||||
const raw = job?.raw_flow?.modules ?? []
|
||||
const i = raw.findIndex((m) => m.id === id)
|
||||
return i > 0 && !!raw[i - 1].sleep
|
||||
}
|
||||
function updateInnerModules(status: FlowStatus) {
|
||||
const found = findDeniedApproval(status)
|
||||
const denied = found?.approval
|
||||
@@ -707,6 +828,24 @@
|
||||
if (mod.type === 'Failure' && localModuleStates[mod.id ?? '']?.type === 'Success') {
|
||||
setModuleState(mod.id ?? '', { type: 'Failure' })
|
||||
}
|
||||
// The step after an approval step is the one that waits for it.
|
||||
const approvalStep = innerModules?.[i - 1]
|
||||
const approvalWait =
|
||||
mod.id &&
|
||||
job?.id &&
|
||||
approvalStep?.id &&
|
||||
approvalStep.type === 'Success' &&
|
||||
mod.type === 'WaitingForEvents'
|
||||
? {
|
||||
job: job.id,
|
||||
workspace: job.workspace_id,
|
||||
step: approvalStep.id,
|
||||
required: mod.count ?? 1
|
||||
}
|
||||
: undefined
|
||||
if (mod.id && !deepEqual(approvalWait, localModuleStates[mod.id]?.approval_wait)) {
|
||||
setModuleState(mod.id, { approval_wait: approvalWait })
|
||||
}
|
||||
if (mod.type === 'WaitingForEvents' && innerModules?.[i - 1]?.type === 'Success') {
|
||||
setModuleState(mod.id ?? '', {
|
||||
type: mod.type,
|
||||
@@ -714,33 +853,9 @@
|
||||
tag: job?.tag,
|
||||
script_hash: job?.script_hash
|
||||
})
|
||||
} else if (
|
||||
mod.type === 'WaitingForExecutor' &&
|
||||
localModuleStates[mod.id ?? '']?.scheduled_for == undefined
|
||||
) {
|
||||
} else if (mod.type === 'WaitingForExecutor' && waitingStepDue(mod)) {
|
||||
if (!isReplay) {
|
||||
JobService.getJob({
|
||||
workspace: workspaceId ?? $operatingWorkspace ?? '',
|
||||
id: mod.job ?? '',
|
||||
noLogs: true,
|
||||
noCode: true
|
||||
})
|
||||
.then((job) => {
|
||||
const newState = {
|
||||
type: mod.type,
|
||||
scheduled_for: job?.['scheduled_for'],
|
||||
job_id: job?.id,
|
||||
parent_module: failedStepOf(mod),
|
||||
args: job?.args,
|
||||
tag: job?.tag,
|
||||
script_hash: job?.script_hash
|
||||
}
|
||||
|
||||
setModuleState(mod.id ?? '', newState)
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(`Could not load inner module for job ${mod.job}`, e)
|
||||
})
|
||||
loadWaitingStep(mod, mod.id === retryingId)
|
||||
}
|
||||
} else if (
|
||||
(mod.flow_jobs || mod.branch_chosen) &&
|
||||
@@ -1372,8 +1487,6 @@
|
||||
|
||||
let wrapperHeight: number = $state(0)
|
||||
|
||||
let retryStatusHeight: number = $state(0)
|
||||
|
||||
function removeFailureNode(id: string, parent_module: any) {
|
||||
if (id?.startsWith('failure-') && parent_module) {
|
||||
;[...globalModuleStates, localModuleStates].forEach((stateMap) => {
|
||||
@@ -1394,12 +1507,33 @@
|
||||
suspend?: boolean
|
||||
/** Shown in place of the id. */
|
||||
label?: string
|
||||
/** The fixed sleep of the step before it, in seconds. */
|
||||
sleepBefore?: number
|
||||
/** An inline script with a concurrency limit, which can be held back. */
|
||||
limited?: boolean
|
||||
}
|
||||
|
||||
// Sleeps in branches and loop bodies are not looked at.
|
||||
function timelineExtras(
|
||||
modules: FlowModule[]
|
||||
): Map<string, { sleepBefore?: number; limited?: boolean }> {
|
||||
const extras = new Map<string, { sleepBefore?: number; limited?: boolean }>()
|
||||
modules.forEach((m, i) => {
|
||||
const sleep = modules[i - 1]?.sleep
|
||||
const v = m.value
|
||||
extras.set(m.id, {
|
||||
sleepBefore: sleep?.type === 'static' ? Number(sleep.value) || undefined : undefined,
|
||||
limited: v.type === 'rawscript' && (v.concurrent_limit ?? 0) > 0
|
||||
})
|
||||
})
|
||||
return extras
|
||||
}
|
||||
|
||||
function allModulesForTimeline(
|
||||
modules: FlowModule[],
|
||||
expandedSubflows: Record<string, { modules: FlowModule[]; groups?: any[] }>
|
||||
): FlowModuleForTimeline[] {
|
||||
const topExtras = timelineExtras(modules)
|
||||
const ids = dfs(
|
||||
modules,
|
||||
(x) =>
|
||||
@@ -1407,7 +1541,8 @@
|
||||
id: x.id,
|
||||
type: x.value.type,
|
||||
suspend: x.suspend != undefined,
|
||||
label: x.id === AGENT_STEP_ID ? agentStepLabel(job?.script_path) : undefined
|
||||
label: x.id === AGENT_STEP_ID ? agentStepLabel(job?.script_path) : undefined,
|
||||
...topExtras.get(x.id)
|
||||
}) as FlowModuleForTimeline,
|
||||
{
|
||||
skipToolNodes: true
|
||||
@@ -1426,6 +1561,7 @@
|
||||
return []
|
||||
}
|
||||
let nprefix = buildPrefix(prefix, oid)
|
||||
const extras = fms ? timelineExtras(fms) : undefined
|
||||
return fms
|
||||
? rec(
|
||||
dfs(
|
||||
@@ -1433,7 +1569,8 @@
|
||||
(x) => ({
|
||||
id: x.id.startsWith('subflow:') ? x.id : buildSubflowKey(x.id, nprefix),
|
||||
type: x.value.type,
|
||||
suspend: x.suspend != undefined
|
||||
suspend: x.suspend != undefined,
|
||||
...extras?.get(x.id)
|
||||
}),
|
||||
{ skipToolNodes: true }
|
||||
),
|
||||
@@ -1612,10 +1749,6 @@
|
||||
)
|
||||
)
|
||||
|
||||
let totalEventsWaiting = $derived(
|
||||
Object.values(suspendStatus?.val ?? {}).reduce((a, b) => a + (b?.nb ?? 0), 0)
|
||||
)
|
||||
|
||||
let continuedOnError = $derived(job?.flow_status?.continued_on_error ?? [])
|
||||
</script>
|
||||
|
||||
@@ -2094,6 +2227,10 @@
|
||||
<ModuleStatus
|
||||
type={mod.type}
|
||||
scheduled_for={localModuleStates?.[mod.id ?? '']?.scheduled_for}
|
||||
waiting_reason={localModuleStates?.[mod.id ?? '']?.waiting_reason}
|
||||
concurrency_key={localModuleStates?.[mod.id ?? '']?.concurrency_key}
|
||||
held_since={localModuleStates?.[mod.id ?? '']?.held_since}
|
||||
approval_wait={localModuleStates?.[mod.id ?? '']?.approval_wait}
|
||||
/>
|
||||
{/if}
|
||||
</li>
|
||||
@@ -2167,69 +2304,19 @@
|
||||
<Splitpanes>
|
||||
<Pane bind:size={graphPaneSize} minSize={30}>
|
||||
<div class="bg-surface-secondary h-full {fillHeight ? '' : 'max-h-[1200px]'}">
|
||||
<div class="flex flex-col" bind:clientHeight={retryStatusHeight}>
|
||||
{#each Object.values(retryStatus?.val ?? {}) as count}
|
||||
{#if count}
|
||||
<span class="text-sm">
|
||||
Retry in progress, # of failed attempts: {count}
|
||||
</span>
|
||||
{/if}
|
||||
{/each}
|
||||
{#if totalEventsWaiting}
|
||||
<span class="text-sm">
|
||||
Flow suspended, waiting for {totalEventsWaiting} events
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<FlowGraphV2
|
||||
{selectionManager}
|
||||
triggerNode={true}
|
||||
download={!hideDownloadInGraph}
|
||||
minHeight={wrapperHeight - retryStatusHeight}
|
||||
maxHeight={fillHeight ? wrapperHeight - retryStatusHeight : undefined}
|
||||
minHeight={wrapperHeight}
|
||||
maxHeight={fillHeight ? wrapperHeight : undefined}
|
||||
fitOnLoad={fillHeight}
|
||||
outerDivClass={fillHeight ? '' : 'max-h-[1200px]'}
|
||||
success={jobId != undefined && isSuccess(job?.['success'])}
|
||||
flowModuleStates={localModuleStates}
|
||||
runDone={job?.type === 'CompletedJob'}
|
||||
bind:expandedSubflows
|
||||
onSelect={(e) => {
|
||||
subflowPathChain = undefined
|
||||
if (rightColumnSelect != 'node_definition' && rightColumnSelect != 'tracing') {
|
||||
rightColumnSelect = 'node_status'
|
||||
}
|
||||
if (typeof e == 'string') {
|
||||
if (e == 'Input') {
|
||||
selectedNode = 'start'
|
||||
stepDetail = undefined
|
||||
} else if (e == 'Result') {
|
||||
selectedNode = 'end'
|
||||
stepDetail = 'end'
|
||||
} else {
|
||||
const id = e.startsWith(AI_TOOL_CALL_PREFIX) ? e.split('-').pop() : e
|
||||
const resolved = resolveLoadedExpandedSubflowStep(
|
||||
e,
|
||||
job?.raw_flow?.modules ?? [],
|
||||
expandedSubflows ?? {}
|
||||
)
|
||||
stepDetail =
|
||||
resolved?.module ??
|
||||
dfs(job?.raw_flow?.modules ?? [], (m) => m).find((m) => m?.id === id)
|
||||
subflowPathChain = resolved?.pathChain
|
||||
selectedNode = e
|
||||
if (e.startsWith(AI_TOOL_CALL_PREFIX)) {
|
||||
const [_prefix, agentModuleId, j, _toolModuleId] = e.split('-')
|
||||
const parentLoopsPrefix = getParentLoopsPrefix(agentModuleId)
|
||||
const jIdx = Number(j)
|
||||
const storeKey = parentLoopsPrefix + agentModuleId + '-' + jIdx
|
||||
toolCallStore?.addToolCallToLoad(storeKey)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
stepDetail = e
|
||||
selectedNode = e.id
|
||||
}
|
||||
}}
|
||||
onSelect={onGraphSelect}
|
||||
{onSelectedIteration}
|
||||
earlyStop={job.raw_flow?.skip_expr !== undefined}
|
||||
cache={job.raw_flow?.cache_ttl !== undefined}
|
||||
@@ -2443,6 +2530,10 @@
|
||||
<ModuleStatus
|
||||
type={node.type}
|
||||
scheduled_for={node.scheduled_for}
|
||||
waiting_reason={node.waiting_reason}
|
||||
concurrency_key={node.concurrency_key}
|
||||
held_since={node.held_since}
|
||||
approval_wait={node.approval_wait}
|
||||
skipped={node.skipped}
|
||||
/>
|
||||
{#if node.duration_ms}
|
||||
|
||||
@@ -96,6 +96,23 @@
|
||||
<DisplayResult {workspaceId} noControls result={description} language={job?.language} />
|
||||
<div class="mt-2"></div>
|
||||
{/if}
|
||||
<!-- The form first, then its buttons below it, as any form is submitted. -->
|
||||
{#if job?.raw_flow?.modules?.[approvalStep]?.suspend?.resume_form?.schema}
|
||||
<div class="flex items-start gap-1 mb-2">
|
||||
<div
|
||||
class={twMerge(
|
||||
'w-full border rounded-lg p-2',
|
||||
light ? 'min-w-96 max-h-svh overflow-y-auto' : ''
|
||||
)}
|
||||
>
|
||||
<SchemaForm onlyMaskPassword bind:args={default_payload} {defaultValues} {schema} />
|
||||
</div>
|
||||
<Tooltip>
|
||||
The payload is optional, it is passed to the following step through the `resume`
|
||||
variable
|
||||
</Tooltip>
|
||||
</div>
|
||||
{/if}
|
||||
<!-- A new approval step gets usable buttons again. -->
|
||||
{#key job?.flow_status?.modules?.[approvalStep]?.job}
|
||||
<ApprovalActions
|
||||
@@ -118,20 +135,6 @@
|
||||
</a>
|
||||
{/if}
|
||||
|
||||
{#if job?.raw_flow?.modules?.[approvalStep]?.suspend?.resume_form?.schema}
|
||||
<div
|
||||
class={twMerge(
|
||||
'w-full border rounded-lg p-2',
|
||||
light ? 'min-w-96 max-h-svh overflow-y-auto' : ''
|
||||
)}
|
||||
>
|
||||
<SchemaForm onlyMaskPassword bind:args={default_payload} {defaultValues} {schema} />
|
||||
</div>
|
||||
<Tooltip>
|
||||
The payload is optional, it is passed to the following step through the `resume`
|
||||
variable
|
||||
</Tooltip>
|
||||
{/if}
|
||||
</ApprovalActions>
|
||||
{/key}
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { displayDate, msToCompactDuration } from '$lib/utils'
|
||||
import { ConcurrencyGroupsService } from '$lib/gen'
|
||||
import { Loader2 } from 'lucide-svelte'
|
||||
import TimelineBar from './TimelineBar.svelte'
|
||||
import WaitTimeWarning from './common/waitTimeWarning/WaitTimeWarning.svelte'
|
||||
@@ -135,6 +136,81 @@
|
||||
})
|
||||
|
||||
const hasApprovalWait = $derived(Object.keys(approvalWaitByModule).length > 0)
|
||||
|
||||
// The hold of a limited step's job once it started; a live hold comes from the step's state.
|
||||
let holds = $state<Record<string, { from?: number; to?: number } | null>>({})
|
||||
$effect(() => {
|
||||
for (const m of flowModules) {
|
||||
if (!m.limited) continue
|
||||
for (const j of items?.[m.id] ?? []) {
|
||||
if (!j.started_at || j.id in untrack(() => holds)) continue
|
||||
holds[j.id] = null
|
||||
ConcurrencyGroupsService.getConcurrencyKeyStatus({ id: j.id })
|
||||
.then((s) => {
|
||||
if (s?.deferred_from)
|
||||
holds[j.id] = {
|
||||
from: new Date(s.deferred_from).getTime(),
|
||||
to: s.released_at ? new Date(s.released_at).getTime() : undefined
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
type WaitSegment = { start: number; len: number; kind: 'sleep' | 'held' | 'wait' }
|
||||
/** A job's wait split into the sleep before it, its concurrency hold and the rest. */
|
||||
function waitSegments(
|
||||
m: FlowModuleForTimeline,
|
||||
job: { id: string; created_at?: number; started_at?: number },
|
||||
single: boolean
|
||||
): WaitSegment[] {
|
||||
const b = { ...job, created_at: job.created_at ?? now }
|
||||
const end = b.started_at ?? now
|
||||
const state = localModuleStates[m.id]
|
||||
const live = b.started_at == undefined && state?.type === 'WaitingForExecutor'
|
||||
let sleepEnd: number | undefined
|
||||
if (single && live && state?.waiting_reason === 'sleep' && state.scheduled_for)
|
||||
sleepEnd = new Date(state.scheduled_for).getTime()
|
||||
else if (single && m.sleepBefore) sleepEnd = b.created_at + m.sleepBefore * 1000
|
||||
const hold =
|
||||
live && state?.waiting_reason === 'concurrency' && state.held_since
|
||||
? { from: new Date(state.held_since).getTime(), to: undefined }
|
||||
: holds[b.id]
|
||||
const clamp = (t: number) => Math.min(Math.max(t, b.created_at), end)
|
||||
const segments: WaitSegment[] = []
|
||||
let at = b.created_at
|
||||
const push = (to: number, kind: WaitSegment['kind']) => {
|
||||
to = clamp(to)
|
||||
if (to > at) segments.push({ start: at, len: to - at, kind })
|
||||
at = Math.max(at, to)
|
||||
}
|
||||
if (sleepEnd != undefined) push(sleepEnd, 'sleep')
|
||||
if (hold?.from != undefined) {
|
||||
push(hold.from, 'wait')
|
||||
push(hold.to ?? end, 'held')
|
||||
}
|
||||
push(end, 'wait')
|
||||
return segments
|
||||
}
|
||||
const segmentStyle = {
|
||||
// A wait like the gray one, striped as one the flow asked for.
|
||||
sleep: {
|
||||
colorClass:
|
||||
'bg-[repeating-linear-gradient(135deg,#d1d5db_0_4px,#e5e7eb_4px_8px)] dark:bg-[repeating-linear-gradient(135deg,#4b5563_0_4px,#374151_4px_8px)] !text-gray-700 dark:!text-gray-100',
|
||||
label: 'Sleep'
|
||||
},
|
||||
held: { colorClass: 'bg-orange-400/90', label: 'Held by concurrency limit' },
|
||||
wait: { colorClass: undefined, label: 'Wait' }
|
||||
}
|
||||
const hasSleep = $derived(
|
||||
flowModules.some((m) => m.sleepBefore) ||
|
||||
Object.values(localModuleStates).some((s) => s.waiting_reason === 'sleep')
|
||||
)
|
||||
const hasHold = $derived(
|
||||
Object.values(holds).some((h) => h?.from != undefined) ||
|
||||
Object.values(localModuleStates).some((s) => s.waiting_reason === 'concurrency')
|
||||
)
|
||||
</script>
|
||||
|
||||
<OnChange
|
||||
@@ -160,6 +236,20 @@
|
||||
<div class="h-2.5 w-2.5 rounded-sm bg-blue-500/90"></div>
|
||||
<span>Execution</span>
|
||||
</div>
|
||||
{#if hasSleep}
|
||||
<div class="flex gap-1.5 items-center">
|
||||
<div
|
||||
class="h-2.5 w-2.5 rounded-sm bg-[repeating-linear-gradient(135deg,#d1d5db_0_4px,#e5e7eb_4px_8px)] dark:bg-[repeating-linear-gradient(135deg,#4b5563_0_4px,#374151_4px_8px)]"
|
||||
></div>
|
||||
<span>Sleep</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if hasHold}
|
||||
<div class="flex gap-1.5 items-center">
|
||||
<div class="h-2.5 w-2.5 rounded-sm bg-orange-400/90"></div>
|
||||
<span>Concurrency limit</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if hasApprovalWait}
|
||||
<div class="flex gap-1.5 items-center">
|
||||
<div class="h-2.5 w-2.5 rounded-sm bg-purple-400/80"></div>
|
||||
@@ -184,8 +274,11 @@
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
{#each flowModules as { id: k, type: typ, suspend: isSuspend, label } (k)}
|
||||
{@const subItems = items?.[k]?.filter((x) => x.created_at && x.started_at)}
|
||||
{#each flowModules as m (m.id)}
|
||||
{@const { id: k, type: typ, suspend: isSuspend, label } = m}
|
||||
{@const subItems = items?.[k]?.filter(
|
||||
(x) => x.created_at && (x.started_at || localModuleStates[k]?.waiting_reason)
|
||||
)}
|
||||
<div class="relative px-3 py-1.5">
|
||||
<div class="flex items-center justify-between mb-0.5">
|
||||
<div class="text-xs font-medium"
|
||||
@@ -238,20 +331,50 @@
|
||||
: now - b?.created_at
|
||||
: 0}
|
||||
{@const aw = isSuspend ? approvalWaitByModule[k] : undefined}
|
||||
{@const segments =
|
||||
waitingLen < 100 ? [] : waitSegments(m, b, subItems?.length === 1)}
|
||||
<div class="flex w-full py-0.5 items-center" {style}>
|
||||
<TimelineBar
|
||||
position="left"
|
||||
id={b?.id}
|
||||
{total}
|
||||
{min}
|
||||
{compact}
|
||||
gray
|
||||
followedByBar={!!b.started_at}
|
||||
spacerClass="bg-gray-100 dark:bg-gray-800/50 rounded-l-md"
|
||||
started_at={b.created_at}
|
||||
len={waitingLen < 100 ? 0 : waitingLen - 100}
|
||||
running={b?.started_at == undefined}
|
||||
/>
|
||||
{#if segments.length <= 1}
|
||||
<TimelineBar
|
||||
position="left"
|
||||
id={b?.id}
|
||||
{total}
|
||||
{min}
|
||||
{compact}
|
||||
gray
|
||||
colorClass={segmentStyle[segments[0]?.kind ?? 'wait'].colorClass}
|
||||
tooltip={segments[0] && segments[0].kind !== 'wait'
|
||||
? `${segmentStyle[segments[0].kind].label} · ${msToCompactDuration(segments[0].len, 1)}`
|
||||
: undefined}
|
||||
followedByBar={!!b.started_at}
|
||||
spacerClass="bg-gray-100 dark:bg-gray-800/50 rounded-l-md"
|
||||
started_at={b.created_at}
|
||||
len={waitingLen < 100 ? 0 : waitingLen - 100}
|
||||
running={b?.started_at == undefined}
|
||||
/>
|
||||
{:else}
|
||||
{#each segments as seg, i (i)}
|
||||
<TimelineBar
|
||||
position={i === 0 ? 'left' : 'none'}
|
||||
id={b?.id}
|
||||
{total}
|
||||
{min}
|
||||
{compact}
|
||||
gray
|
||||
concat={i > 0}
|
||||
colorClass={segmentStyle[seg.kind].colorClass}
|
||||
tooltip="{segmentStyle[seg.kind].label} · {msToCompactDuration(
|
||||
seg.len,
|
||||
1
|
||||
)}"
|
||||
followedByBar
|
||||
spacerClass="bg-gray-100 dark:bg-gray-800/50 rounded-l-md"
|
||||
started_at={seg.start}
|
||||
len={i === segments.length - 1 ? Math.max(seg.len - 100, 0) : seg.len}
|
||||
running={b?.started_at == undefined}
|
||||
/>
|
||||
{/each}
|
||||
{/if}
|
||||
{#if b.started_at}
|
||||
<TimelineBar
|
||||
position={aw || waitingLen < 100 ? 'center' : 'right'}
|
||||
|
||||
@@ -148,8 +148,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
/** The compare page opened on one direction, for a badge that counts exactly that. The button
|
||||
* beside them still chooses on the reader's behalf; a badge means the one thing it names. */
|
||||
/** The compare page opened on one direction, for a badge that counts exactly that. */
|
||||
function compareDirHref(dir: 'deploy_to' | 'update'): string | undefined {
|
||||
if (!parentWorkspaceId || !$workspaceStore) return undefined
|
||||
return (
|
||||
@@ -245,9 +244,13 @@
|
||||
: total > 0
|
||||
? 'drift'
|
||||
: undefined}
|
||||
<!-- What the comparison has to say is a mark beside the button, never instead of it: a fork
|
||||
still being counted, or one whose count failed, is exactly when a reader wants the page
|
||||
that does the counting properly. The button below renders in every state. -->
|
||||
<!-- Each badge opens the side of the compare page it counts, so badges make the button redundant.
|
||||
The button stays for a fork still being counted, one whose count failed, or one with nothing
|
||||
to count: that is when a reader wants the page that does the counting properly. -->
|
||||
{@const badged =
|
||||
status === 'drafts' ||
|
||||
(status === 'drift' &&
|
||||
(changesAhead > 0 || changesBehind > 0 || conflicts > 0 || draftCount > 0))}
|
||||
<!-- Keyed on what it says, so each answer the comparison lands with fades in rather than
|
||||
popping into a bar that is already showing. -->
|
||||
{#key status}
|
||||
@@ -256,10 +259,6 @@
|
||||
<span class="text-2xs text-tertiary">Checking for changes…</span>
|
||||
{:else if error}
|
||||
<span class="text-2xs text-red-600 dark:text-red-400" title={error}>Comparison failed</span>
|
||||
{:else if showDraftsOnly}
|
||||
<Badge color="blue" small>
|
||||
{draftCount} draft{draftCount !== 1 ? 's' : ''}
|
||||
</Badge>
|
||||
{:else if total > 0}
|
||||
<!-- Which way the drift goes is the thing to know at a glance: ahead is what this fork has
|
||||
to give its parent, behind is what it has yet to take. -->
|
||||
@@ -303,39 +302,29 @@
|
||||
{conflicts}{compactCounts ? '' : ` conflict${conflicts !== 1 ? 's' : ''}`}
|
||||
</Badge>
|
||||
{/if}
|
||||
<!-- Drafts are a different axis from the drift beside them: ahead and behind count deployed
|
||||
items against the parent, this counts work in this fork that is not deployed anywhere
|
||||
yet. It shares blue with "behind" and is told apart by the pencil and by naming what it
|
||||
counts, rather than by an arrow that would read as a third direction. Clicking goes to
|
||||
the drafts half of the compare page rather than the drawer the button opens. It shows at
|
||||
every drift — a fork both behind and holding drafts said nothing about the drafts. -->
|
||||
{#if draftCount > 0}
|
||||
<Badge
|
||||
color="blue"
|
||||
small
|
||||
clickable
|
||||
href={draftCompareHref}
|
||||
title="{draftCount} draft{draftCount !== 1
|
||||
? 's'
|
||||
: ''} in this {currentNoun}, not deployed anywhere yet — review and deploy"
|
||||
>
|
||||
<Pencil class="w-3 h-3 inline" />
|
||||
{draftCount}{compactCounts ? '' : ` draft${draftCount !== 1 ? 's' : ''}`}
|
||||
</Badge>
|
||||
{/if}
|
||||
{/if}
|
||||
<!-- Drafts are a different axis from the drift beside them: ahead and behind count deployed
|
||||
items against the parent, this counts work in this fork that is not deployed anywhere
|
||||
yet. It shares blue with "behind" and is told apart by the pencil and by naming what it
|
||||
counts, rather than by an arrow that would read as a third direction. It shows at every
|
||||
drift, and on its own when drafts are all there is. -->
|
||||
{#if (status === 'drafts' || status === 'drift') && draftCount > 0}
|
||||
<Badge
|
||||
color="blue"
|
||||
small
|
||||
clickable
|
||||
href={draftCompareHref}
|
||||
title="{draftCount} draft{draftCount !== 1
|
||||
? 's'
|
||||
: ''} in this {currentNoun}, not deployed anywhere yet — review and deploy"
|
||||
>
|
||||
<Pencil class="w-3 h-3 inline" />
|
||||
{draftCount}{compactCounts ? '' : ` draft${draftCount !== 1 ? 's' : ''}`}
|
||||
</Badge>
|
||||
{/if}
|
||||
</span>
|
||||
{/key}
|
||||
{#if showDraftsOnly}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
href={draftCompareHref}
|
||||
title={`Review and deploy this workspace's drafts`}
|
||||
>
|
||||
Review & deploy drafts
|
||||
</Button>
|
||||
{:else}
|
||||
{#if !badged}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
|
||||
@@ -325,7 +325,8 @@
|
||||
loadFilePreviewRequest={HelpersService.loadGitRepoFilePreview}
|
||||
testConnectionRequest={(async (_d) => {
|
||||
const bucketConfig: any = await SettingService.getGlobal({
|
||||
key: 'object_store_cache_config'
|
||||
key: 'object_store_cache_config',
|
||||
dangerouslyRevealSecrets: true
|
||||
})
|
||||
return SettingService.testObjectStorageConfig({
|
||||
requestBody: bucketConfig
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
import { apiErrorMessage, classNames } from '$lib/utils'
|
||||
import { AlertTriangle, CornerDownLeft, Loader2 } from 'lucide-svelte'
|
||||
import { UserService, FolderService } from '$lib/gen'
|
||||
import type { WorkspaceOffboardPreview } from '$lib/gen'
|
||||
import type { OffboardPathConflict, WorkspaceOffboardPreview } from '$lib/gen'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import OffboardWorkspaceSection from './OffboardWorkspaceSection.svelte'
|
||||
import { countPaths } from './offboarding-utils'
|
||||
import OffboardConflictList from './OffboardConflictList.svelte'
|
||||
import { countPaths, withoutConflict } from './offboarding-utils'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
@@ -25,7 +26,7 @@
|
||||
let submitting = $state(false)
|
||||
let doReassign = $state(true)
|
||||
let deleteUser = $state(true)
|
||||
let conflicts: string[] = $state([])
|
||||
let conflicts: OffboardPathConflict[] = $state([])
|
||||
|
||||
$effect(() => {
|
||||
deleteUser = !reassignOnly
|
||||
@@ -169,8 +170,8 @@
|
||||
delete_user: deleteUser
|
||||
}
|
||||
})
|
||||
if (result.conflicts && result.conflicts.length > 0) {
|
||||
conflicts = result.conflicts
|
||||
if (result.conflict_items && result.conflict_items.length > 0) {
|
||||
conflicts = result.conflict_items
|
||||
} else {
|
||||
sendUserToast(
|
||||
deleteUser
|
||||
@@ -315,17 +316,11 @@
|
||||
{/if}
|
||||
|
||||
{#if conflicts.length > 0}
|
||||
<Alert type="error" title="Path conflicts detected">
|
||||
<p class="text-xs mb-1"
|
||||
>These items already exist at the target. Rename or delete them, or choose a
|
||||
different user/folder.</p
|
||||
>
|
||||
<ul class="text-xs list-disc list-inside max-h-32 overflow-y-auto">
|
||||
{#each conflicts as conflict, i (i)}
|
||||
<li>{conflict}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</Alert>
|
||||
<OffboardConflictList
|
||||
{conflicts}
|
||||
showWorkspace
|
||||
onResolved={(c) => (conflicts = withoutConflict(conflicts, c))}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -195,8 +195,8 @@
|
||||
)
|
||||
const instanceConnects = $derived(new Set(oauthConnects.current ?? []))
|
||||
/**
|
||||
* Matches what the dialog itself decides (`AppConnectInner.open`: `manual = !inConnects &&
|
||||
* !registryCcCapable()`). An instance client is the usual route, but a provider the
|
||||
* The types worth offering Connect for: an instance OAuth entry, or a provider the
|
||||
* registry marks client-credentials-capable. An instance client is the usual route, but a provider the
|
||||
* registry marks client-credentials-capable is connectable without one, because those
|
||||
* credentials are entered per resource rather than held by a superadmin. Test only the
|
||||
* first half and Connect disappears on the eight such providers, where it would work.
|
||||
|
||||
@@ -18,6 +18,9 @@
|
||||
username?: string | undefined
|
||||
automateUsernameCreation?: boolean
|
||||
login_type: string
|
||||
/** Whether the user has two-factor authentication; the section shows only then. */
|
||||
totpEnabled?: boolean
|
||||
totpRequired?: boolean
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -25,7 +28,9 @@
|
||||
email,
|
||||
username = undefined,
|
||||
automateUsernameCreation = false,
|
||||
login_type = $bindable()
|
||||
login_type = $bindable(),
|
||||
totpEnabled = false,
|
||||
totpRequired = false
|
||||
}: Props = $props()
|
||||
|
||||
let password: string = $state('')
|
||||
@@ -44,6 +49,11 @@
|
||||
sendUserToast(`Password updated for ${email}`)
|
||||
}
|
||||
|
||||
async function removeTotp() {
|
||||
sendUserToast(await UserService.resetTotpOfUser({ user: email }))
|
||||
dispatch('refresh')
|
||||
}
|
||||
|
||||
async function saveLoginType() {
|
||||
await UserService.setLoginTypeForUser({ user: email, requestBody: { login_type } })
|
||||
sendUserToast(`Login type updated for ${email}`)
|
||||
@@ -173,6 +183,25 @@
|
||||
Update login type
|
||||
</Button>
|
||||
</label>
|
||||
{#if totpEnabled}
|
||||
<div class="block text-primary">
|
||||
<div class="pb-1 text-xs font-semibold text-emphasis">Two-factor authentication</div>
|
||||
<div class="text-2xs text-secondary mb-1">
|
||||
For a user who lost their authenticator and recovery codes. {totpRequired
|
||||
? 'They set it up again at their next login.'
|
||||
: 'They can set it up again from their user settings.'}
|
||||
</div>
|
||||
<Button
|
||||
unifiedSize="md"
|
||||
variant="default"
|
||||
buttonType="button"
|
||||
btnClasses="mt-2"
|
||||
onclick={removeTotp}
|
||||
>
|
||||
Remove two-factor
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/snippet}
|
||||
</Popover>
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
import RetentionPeriodOverrides from './instanceSettings/RetentionPeriodOverrides.svelte'
|
||||
import AgentWorkloadIdentityIssuers from './instanceSettings/AgentWorkloadIdentityIssuers.svelte'
|
||||
import McpExternalIdp from './instanceSettings/McpExternalIdp.svelte'
|
||||
import InstanceIpAllowlist from './instanceSettings/InstanceIpAllowlist.svelte'
|
||||
import OtelAuditLogsSettings from './instanceSettings/OtelAuditLogsSettings.svelte'
|
||||
import WorkspaceRolesSetting from './instanceSettings/WorkspaceRolesSetting.svelte'
|
||||
import SmtpSettings from './instanceSettings/SmtpSettings.svelte'
|
||||
import SecretBackendConfig from './instanceSettings/SecretBackendConfig.svelte'
|
||||
@@ -128,7 +130,8 @@
|
||||
|
||||
async function reloadLicenseKey() {
|
||||
$values['license_key'] = await SettingService.getGlobal({
|
||||
key: 'license_key'
|
||||
key: 'license_key',
|
||||
dangerouslyRevealSecrets: true
|
||||
})
|
||||
}
|
||||
|
||||
@@ -646,6 +649,8 @@
|
||||
<AgentWorkloadIdentityIssuers {values} disabled={!$enterpriseLicense} />
|
||||
{:else if setting.fieldType == 'mcp_external_idp'}
|
||||
<McpExternalIdp {values} disabled={!$enterpriseLicense} />
|
||||
{:else if setting.fieldType == 'instance_ip_allowlist'}
|
||||
<InstanceIpAllowlist {values} licensed={!!$enterpriseLicense} />
|
||||
{:else if setting.fieldType == 'critical_error_channels'}
|
||||
<CriticalAlertChannels {values} {openSmtpSettings} {oauths} />
|
||||
{:else if setting.fieldType == 'otel'}
|
||||
@@ -724,6 +729,7 @@
|
||||
Service name, environment, resource attributes, metrics temporality and other
|
||||
options are set with environment variables.
|
||||
</Description>
|
||||
<OtelAuditLogsSettings {values} disabled={!$enterpriseLicense} />
|
||||
{/if}
|
||||
</div>
|
||||
{:else if setting.fieldType == 'otel_tracing_proxy'}
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
import WorkspaceRegistries from './instanceSettings/WorkspaceRegistries.svelte'
|
||||
import DbHealth from './instanceSettings/DbHealth.svelte'
|
||||
import OidcSigningStatus from './instanceSettings/OidcSigningStatus.svelte'
|
||||
import ClientIpStatus from './instanceSettings/ClientIpStatus.svelte'
|
||||
|
||||
interface Props {
|
||||
tab?: string
|
||||
@@ -135,7 +136,7 @@
|
||||
loading = true
|
||||
|
||||
// Bulk-load all settings in a single API call
|
||||
const config = await SettingService.getInstanceConfig()
|
||||
const config = await SettingService.getInstanceConfig({ dangerouslyRevealSecrets: true })
|
||||
const gs = (config.global_settings ?? {}) as Record<string, any>
|
||||
|
||||
initialOauths = gs['oauths'] ?? {}
|
||||
@@ -1165,6 +1166,13 @@
|
||||
{#if $enterpriseLicense}
|
||||
<OidcSigningStatus />
|
||||
{/if}
|
||||
{:else if category == 'Client IP'}
|
||||
<SettingsPageHeader
|
||||
title="Client IP"
|
||||
description="The address Windmill records as a request's client: in audit logs, for login rate limits and for token IP allowlists. Forwarding headers are believed only from the proxies trusted here. The TRUSTED_PROXIES, TRUST_CLOUDFLARE and CLIENT_IP_HEADER environment variables, when set, take precedence."
|
||||
link="https://www.windmill.dev/docs/advanced/self_host#client-ip-behind-a-reverse-proxy"
|
||||
/>
|
||||
<ClientIpStatus {values} {loading} />
|
||||
{:else if category == 'Agent workers'}
|
||||
<SettingsPageHeader
|
||||
title="Agent workers"
|
||||
@@ -1202,7 +1210,7 @@
|
||||
<div class="flex-col flex gap-6 pb-6">
|
||||
{#each settings[category] as setting}
|
||||
<!-- slack connect is handled with the alert channels settings, smtp_connect is handled in InstanceSetting -->
|
||||
{#if setting.fieldType != 'slack_connect' && !(quickSetup && setting.hideInQuickSetup) && !(quickSetup && category === 'Core' && setting.key === 'license_key') && !(setting.key === 'mcp_external_idp' && authSubTab !== 'sso')}
|
||||
{#if setting.fieldType != 'slack_connect' && setting.fieldType != 'client_ip' && !(quickSetup && setting.hideInQuickSetup) && !(quickSetup && category === 'Core' && setting.key === 'license_key') && !(setting.key === 'mcp_external_idp' && authSubTab !== 'sso')}
|
||||
<InstanceSetting
|
||||
{openSmtpSettings}
|
||||
on:closeDrawer={() => closeDrawer?.()}
|
||||
|
||||
@@ -14,9 +14,13 @@
|
||||
interface Props {
|
||||
job: QueuedJob | CompletedJob | undefined
|
||||
large?: boolean
|
||||
/** Its concurrency limit has held the job back, so a later due time is the next check. */
|
||||
heldByConcurrency?: boolean
|
||||
/** Why the step the flow is at has not started. */
|
||||
stepWaiting?: 'sleep' | 'concurrency'
|
||||
}
|
||||
|
||||
let { job, large = false }: Props = $props()
|
||||
let { job, large = false, heldByConcurrency = false, stepWaiting }: Props = $props()
|
||||
|
||||
let continuedOnError = $derived(job?.flow_status?.continued_on_error ?? [])
|
||||
</script>
|
||||
@@ -90,6 +94,12 @@
|
||||
{/if}
|
||||
</Badge>
|
||||
</div>
|
||||
{:else if job && 'running' in job && job.running && stepWaiting}
|
||||
<div>
|
||||
<Badge {large} color={stepWaiting === 'sleep' ? 'gray' : 'orange'}>
|
||||
{stepWaiting === 'sleep' ? 'Sleeping' : 'Step held by concurrency limit'}
|
||||
</Badge>
|
||||
</div>
|
||||
{:else if job && 'running' in job && job.running}
|
||||
<div class="flex flex-row flex-wrap gap-1 items-center">
|
||||
<Badge {large} color="yellow">
|
||||
@@ -100,6 +110,12 @@
|
||||
</Badge>
|
||||
{@render continuedOnErrorBadge()}
|
||||
</div>
|
||||
{:else if job && 'running' in job && heldByConcurrency}
|
||||
<div>
|
||||
<Badge color="orange" {large} title="Next check by {displayDate(job.scheduled_for, true)}">
|
||||
Held by concurrency limit
|
||||
</Badge>
|
||||
</div>
|
||||
{:else if job && 'running' in job && 'scheduled_for' in job && job.scheduled_for && forLater(job.scheduled_for)}
|
||||
<div>
|
||||
<Badge color="blue" {large}>
|
||||
|
||||
@@ -40,9 +40,20 @@
|
||||
import Password from './Password.svelte'
|
||||
import TextInput from './text_input/TextInput.svelte'
|
||||
import { sameTopDomainOrigin } from '$lib/cookies'
|
||||
import { isValidLogoutRedirect, toSameOriginRelativePath } from '$lib/logoutRedirect'
|
||||
import {
|
||||
isValidLogoutRedirect,
|
||||
toRedirectTarget,
|
||||
toSameOriginRelativePath
|
||||
} from '$lib/logoutRedirect'
|
||||
import InputError from './InputError.svelte'
|
||||
import { loginErrorMessage } from '$lib/loginError'
|
||||
import {
|
||||
loginErrorDetail,
|
||||
loginErrorMessage,
|
||||
TOTP_INVALID_MESSAGE,
|
||||
TOTP_REQUIRED,
|
||||
TOTP_SETUP_REQUIRED
|
||||
} from '$lib/loginError'
|
||||
import { parseAccountSettingsHash } from './sidebar/settings'
|
||||
import Badge from './common/badge/Badge.svelte'
|
||||
import {
|
||||
getLastLoginMethod,
|
||||
@@ -78,6 +89,9 @@
|
||||
* same sign-in without this, which provisions them for real. Password login
|
||||
* ignores it: a guest has no stored credential to check. */
|
||||
guestApp?: string | undefined
|
||||
/** Once a password login succeeds, offer to set up two-factor authentication before
|
||||
* leaving the card, for an account that has none. The user can skip it. */
|
||||
offerTotpSetup?: boolean
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -92,7 +106,8 @@
|
||||
onLoginError = undefined,
|
||||
preview = undefined,
|
||||
onOptionsLoaded = undefined,
|
||||
guestApp = undefined
|
||||
guestApp = undefined,
|
||||
offerTotpSetup = false
|
||||
}: Props = $props()
|
||||
|
||||
// The harness never takes effect in a production bundle, whatever a caller passes.
|
||||
@@ -108,6 +123,7 @@
|
||||
const emailId = `${uid}-email`
|
||||
const passwordId = `${uid}-password`
|
||||
const errorId = `${uid}-error`
|
||||
const totpId = `${uid}-totp`
|
||||
const emailErrorId = `${uid}-email-error`
|
||||
|
||||
const providers = [
|
||||
@@ -182,6 +198,43 @@
|
||||
|
||||
let showPassword = $state(false)
|
||||
let passwordField = $state<Password | undefined>(undefined)
|
||||
// The account the server asked an authenticator code for, or asked to set up two-factor
|
||||
// authentication when the instance requires it. These steps replace the form and resend the
|
||||
// password kept here, so the server needs no half-logged-in state.
|
||||
let totpFor = $state<string | undefined>(undefined)
|
||||
let totpCode = $state('')
|
||||
let totpField = $state<TextInput | undefined>(undefined)
|
||||
let showTotp = $derived(totpFor !== undefined && totpFor === email)
|
||||
let enrollSetup = $state<{ secret: string; otpauth_url: string } | undefined>(undefined)
|
||||
// Kept across Back: asking the server again replaces the pending secret, and the QR code the
|
||||
// user already scanned would stop working.
|
||||
let issuedSetup: { email: string; setup: { secret: string; otpauth_url: string } } | undefined
|
||||
let enrollCodes = $state<string[] | undefined>(undefined)
|
||||
// The setup was offered after a successful login, rather than required before one: a
|
||||
// session exists, so it goes through the signed-in routes and can be skipped.
|
||||
let enrollOptional = $state(false)
|
||||
let enrollSaved = $state(false)
|
||||
|
||||
async function openTotpStep(forEmail: string, setup?: { secret: string; otpauth_url: string }) {
|
||||
formError = undefined
|
||||
shake = false
|
||||
totpFor = forEmail
|
||||
totpCode = ''
|
||||
enrollSetup = setup
|
||||
await tick()
|
||||
totpField?.focus()
|
||||
}
|
||||
|
||||
async function leaveTotp() {
|
||||
totpFor = undefined
|
||||
totpCode = ''
|
||||
enrollSetup = undefined
|
||||
formError = undefined
|
||||
// The swapped-in markup would otherwise replay a shake left on from a failed attempt.
|
||||
shake = false
|
||||
await tick()
|
||||
passwordField?.focus()
|
||||
}
|
||||
// Type argument rather than annotation: annotating narrows the declaration to the
|
||||
// initializer's `undefined`, so a top-level read sees `never` instead of the array.
|
||||
let logins = $state<OAuthLogin[] | undefined>(undefined)
|
||||
@@ -199,7 +252,7 @@
|
||||
let formError = $state<
|
||||
| {
|
||||
message: string
|
||||
fields: 'both' | 'email' | 'password'
|
||||
fields: 'both' | 'email' | 'password' | 'totp'
|
||||
email: string | undefined
|
||||
password: string | undefined
|
||||
}
|
||||
@@ -220,7 +273,7 @@
|
||||
|
||||
async function failLogin(
|
||||
message: string,
|
||||
fields: 'both' | 'email' | 'password' = 'both',
|
||||
fields: 'both' | 'email' | 'password' | 'totp' = 'both',
|
||||
// The pair the message is about. Defaults to what is in the fields right now, but a
|
||||
// rejected request passes what it actually submitted: the user may have typed on since.
|
||||
attempted: { email: string | undefined; password: string | undefined } = { email, password }
|
||||
@@ -244,7 +297,20 @@
|
||||
displayName: string
|
||||
}
|
||||
|
||||
// One submit at a time: a second setup request would replace the pending secret, and the
|
||||
// page could then show a QR code the server no longer accepts.
|
||||
let submitting = false
|
||||
async function login(): Promise<void> {
|
||||
if (submitting) return
|
||||
submitting = true
|
||||
try {
|
||||
await submitLogin()
|
||||
} finally {
|
||||
submitting = false
|
||||
}
|
||||
}
|
||||
|
||||
async function submitLogin(): Promise<void> {
|
||||
if (!email || !password) {
|
||||
if (!email && !password) failLogin('Enter both your email and password.')
|
||||
else if (!email) failLogin('Enter your email.', 'email')
|
||||
@@ -257,9 +323,20 @@
|
||||
return
|
||||
}
|
||||
|
||||
if (showTotp && !totpCode.trim()) {
|
||||
failLogin('Enter the code from your authenticator app.', 'totp')
|
||||
return
|
||||
}
|
||||
|
||||
if (showTotp && enrollSetup) {
|
||||
await enableTotpAtLogin()
|
||||
return
|
||||
}
|
||||
|
||||
const requestBody = {
|
||||
email,
|
||||
password
|
||||
password,
|
||||
totp_code: showTotp ? totpCode : undefined
|
||||
}
|
||||
|
||||
// Await the DOM update: the field must be back to type="password" before the
|
||||
@@ -273,10 +350,66 @@
|
||||
// previous account must not be served to this one.
|
||||
noteSessionEmail(email)
|
||||
} catch (err) {
|
||||
failLogin(loginErrorMessage(err), 'both', requestBody)
|
||||
const detail = loginErrorDetail(err)
|
||||
if (detail === TOTP_REQUIRED) {
|
||||
await openTotpStep(requestBody.email)
|
||||
return
|
||||
}
|
||||
if (detail === TOTP_SETUP_REQUIRED) {
|
||||
try {
|
||||
const setup =
|
||||
issuedSetup?.email === requestBody.email
|
||||
? issuedSetup.setup
|
||||
: await UserService.loginTotpSetup({
|
||||
requestBody: { email: requestBody.email, password: requestBody.password }
|
||||
})
|
||||
issuedSetup = { email: requestBody.email, setup }
|
||||
await openTotpStep(requestBody.email, setup)
|
||||
} catch (setupErr) {
|
||||
failLogin(loginErrorMessage(setupErr), 'both', requestBody)
|
||||
}
|
||||
return
|
||||
}
|
||||
const message = loginErrorMessage(err)
|
||||
failLogin(message, message === TOTP_INVALID_MESSAGE ? 'totp' : 'both', requestBody)
|
||||
return
|
||||
}
|
||||
|
||||
if (offerTotpSetup && !requestBody.totp_code) {
|
||||
// Refused when the account already has a second factor, or by a build or edition
|
||||
// that cannot give it one: the login then simply goes on.
|
||||
const setup = await UserService.setupTotp({
|
||||
requestBody: { password: requestBody.password }
|
||||
}).catch(() => undefined)
|
||||
if (setup) {
|
||||
enrollOptional = true
|
||||
await openTotpStep(requestBody.email, setup)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
await finishLogin()
|
||||
}
|
||||
|
||||
// Turns the second factor on and, when it was required, starts the session in the same
|
||||
// request; the recovery codes it returns are shown before leaving the page.
|
||||
async function enableTotpAtLogin(): Promise<void> {
|
||||
const requestBody = { email: email!, password: password!, code: totpCode }
|
||||
try {
|
||||
const { recovery_codes } = enrollOptional
|
||||
? await UserService.enableTotp({ requestBody: { code: totpCode } })
|
||||
: await UserService.loginTotpEnable({ requestBody })
|
||||
noteSessionEmail(requestBody.email)
|
||||
formError = undefined
|
||||
enrollSetup = undefined
|
||||
enrollCodes = recovery_codes
|
||||
} catch (err) {
|
||||
const message = loginErrorMessage(err)
|
||||
failLogin(message, message === TOTP_INVALID_MESSAGE ? 'totp' : 'both', requestBody)
|
||||
}
|
||||
}
|
||||
|
||||
async function finishLogin(): Promise<void> {
|
||||
formError = undefined
|
||||
rememberLoginMethod({ kind: 'password' })
|
||||
|
||||
@@ -305,8 +438,9 @@
|
||||
async function redirectUser() {
|
||||
// Reduce same-origin full URLs to relative paths so deep links from
|
||||
// e.g. /a/[...path] (which carry the full URL as rd) still navigate
|
||||
// correctly instead of falling through to the cross-origin branch.
|
||||
let resolvedRd = toSameOriginRelativePath(rd) ?? rd
|
||||
// correctly instead of falling through to the cross-origin branch. A value that is
|
||||
// not a valid target is dropped rather than handed to `goto`.
|
||||
let resolvedRd = toRedirectTarget(rd) ?? undefined
|
||||
if (resolvedRd?.startsWith('http')) {
|
||||
if (isValidLogoutRedirect(resolvedRd)) {
|
||||
window.location.href = resolvedRd
|
||||
@@ -357,8 +491,8 @@
|
||||
resolvedRd?.startsWith('/projects/import')
|
||||
) {
|
||||
goto(resolvedRd)
|
||||
} else if (resolvedRd == '/#user-settings') {
|
||||
goto(`/user/workspaces#user-settings`)
|
||||
} else if (resolvedRd?.startsWith('/#') && parseAccountSettingsHash(resolvedRd.slice(1))) {
|
||||
goto(`/user/workspaces${resolvedRd.slice(1)}`)
|
||||
} else {
|
||||
goto(`/user/workspaces${resolvedRd ? `?rd=${encodeURIComponent(resolvedRd)}` : ''}`)
|
||||
}
|
||||
@@ -759,130 +893,219 @@
|
||||
<p class="text-sm text-center text-secondary py-4">Signing you in…</p>
|
||||
{/if}
|
||||
|
||||
{#if !passwordFirst}
|
||||
{@render providerButtons()}
|
||||
{#if !autoRedirecting && !disablePasswordLogin && (saml || (logins && logins.length > 0))}
|
||||
{@render orDivider()}
|
||||
<!-- Only an entry point to the form below: once that is open the divider is what
|
||||
separates the two ways in. -->
|
||||
{#if !showPassword}
|
||||
<div class="center-center">
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
onClick={() => {
|
||||
showPassword = true
|
||||
}}
|
||||
>
|
||||
Log in without third-party
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
{#if !autoRedirecting && showPassword && !disablePasswordLogin}
|
||||
<div>
|
||||
{#if firstTime}
|
||||
<p class="text-xs text-center w-full pb-4 text-secondary">
|
||||
Welcome! Default credentials admin@windmill.dev / changeme have been prefilled.
|
||||
{#if enrollCodes}
|
||||
<div class="space-y-4">
|
||||
<div class="space-y-1">
|
||||
<h2 class="text-sm font-semibold text-emphasis">Two-factor authentication is on</h2>
|
||||
<p class="text-xs text-secondary">
|
||||
Logging in with your password now also asks for a code from your authenticator app.
|
||||
</p>
|
||||
{/if}
|
||||
<div class="space-y-4">
|
||||
{#if cloudHosted}
|
||||
<p class="text-xs text-secondary pb-6">
|
||||
To get credentials without the OAuth providers above, send an email at
|
||||
contact@windmill.dev
|
||||
</div>
|
||||
<!-- Loaded on demand: the login page every visitor gets stays free of the QR encoder
|
||||
and the code highlighter, which only these screens use. -->
|
||||
{#await import('./settings/TotpRecoveryCodes.svelte') then { default: TotpRecoveryCodes }}
|
||||
<TotpRecoveryCodes codes={enrollCodes} bind:saved={enrollSaved} />
|
||||
{/await}
|
||||
<Button onClick={finishLogin} variant="accent" unifiedSize="lg" disabled={!enrollSaved}>
|
||||
Continue
|
||||
</Button>
|
||||
</div>
|
||||
{:else if showTotp}
|
||||
<div class="space-y-4">
|
||||
<div class="space-y-1">
|
||||
{#if enrollSetup && enrollOptional}
|
||||
<h2 class="text-sm font-semibold text-emphasis">Set up two-factor authentication</h2>
|
||||
<p class="text-xs text-secondary">
|
||||
Protect {email} with a code from an authenticator app on top of its password. You can also
|
||||
do this later from your user settings.
|
||||
</p>
|
||||
{:else if enrollSetup}
|
||||
<h2 class="text-sm font-semibold text-emphasis">Set up two-factor authentication</h2>
|
||||
<p class="text-xs text-secondary">
|
||||
This instance asks for a code from an authenticator app at each password login. Add
|
||||
{email} to your app to continue.
|
||||
</p>
|
||||
{:else}
|
||||
<h2 class="text-sm font-semibold text-emphasis">Two-factor authentication</h2>
|
||||
<p class="text-xs text-secondary">
|
||||
Enter the code from your authenticator app for {email}, or one of your recovery codes.
|
||||
</p>
|
||||
{/if}
|
||||
<div bind:this={fieldsEl} class="space-y-2 {shake ? 'motion-safe:animate-shake' : ''}">
|
||||
<div class="space-y-1">
|
||||
<label for={emailId} class="block text-xs font-semibold text-emphasis"> Email </label>
|
||||
<div>
|
||||
<TextInput
|
||||
size="md"
|
||||
error={emailErrored}
|
||||
bind:value={email}
|
||||
inputProps={{
|
||||
id: emailId,
|
||||
type: 'email',
|
||||
autocomplete: 'username',
|
||||
'aria-invalid': emailErrored ? 'true' : undefined,
|
||||
'aria-describedby':
|
||||
errorField === 'email' ? emailErrorId : emailErrored ? errorId : undefined,
|
||||
onkeydown: (e) => {
|
||||
// Only move on once the field holds something: while the browser's
|
||||
// credential dropdown is open, Enter belongs to the dropdown
|
||||
if (e.key === 'Enter' && !e.isComposing && !e.repeat && e.currentTarget.value) {
|
||||
e.preventDefault()
|
||||
passwordField?.focus()
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div id={emailErrorId} role="alert" class="min-h-5">
|
||||
{#if errorField === 'email'}
|
||||
<InputError error={credentialsError} />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1">
|
||||
<label for={passwordId} class="block text-xs font-semibold text-emphasis">
|
||||
Password
|
||||
</label>
|
||||
<div>
|
||||
<Password
|
||||
bind:this={passwordField}
|
||||
bind:password
|
||||
id={passwordId}
|
||||
placeholder=""
|
||||
autocomplete="current-password"
|
||||
allowMultiline={false}
|
||||
error={passwordErrored}
|
||||
describedBy={passwordErrored ? errorId : undefined}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
</div>
|
||||
{@render errorMessage()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Button onClick={login} variant="accent" unifiedSize="lg" disabled={!email || !password}>
|
||||
Log in
|
||||
</Button>
|
||||
{#if smtpConfigured}
|
||||
<div class="text-center pt-2">
|
||||
<a
|
||||
href="/user/forgot-password"
|
||||
class="text-2xs text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
>
|
||||
Forgot password?
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
{#if enrollSetup}
|
||||
{#await import('./settings/TotpAuthenticator.svelte') then { default: TotpAuthenticator }}
|
||||
<TotpAuthenticator setup={enrollSetup} />
|
||||
{/await}
|
||||
{/if}
|
||||
<div bind:this={fieldsEl} class="space-y-1 {shake ? 'motion-safe:animate-shake' : ''}">
|
||||
<label for={totpId} class="block text-xs font-semibold text-emphasis">
|
||||
{enrollSetup ? 'The 6-digit code your app shows' : 'Authentication code'}
|
||||
</label>
|
||||
<TextInput
|
||||
bind:this={totpField}
|
||||
size="md"
|
||||
bind:value={totpCode}
|
||||
error={!!errorField}
|
||||
inputProps={{
|
||||
id: totpId,
|
||||
name: 'totp',
|
||||
'aria-invalid': errorField ? 'true' : undefined,
|
||||
'aria-describedby': errorField ? errorId : undefined,
|
||||
autocomplete: 'one-time-code',
|
||||
onkeydown: handleKeyDown
|
||||
}}
|
||||
/>
|
||||
{@render errorMessage()}
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<Button onClick={login} variant="accent" unifiedSize="lg" disabled={!totpCode.trim()}>
|
||||
{enrollOptional ? 'Turn on' : enrollSetup ? 'Turn on and log in' : 'Verify'}
|
||||
</Button>
|
||||
<div class="center-center">
|
||||
{#if enrollOptional}
|
||||
<Button unifiedSize="sm" variant="subtle" onClick={finishLogin}>Skip for now</Button>
|
||||
{:else}
|
||||
<Button unifiedSize="sm" variant="subtle" onClick={leaveTotp}>Back</Button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if cloudHosted}
|
||||
<p class="text-2xs text-secondary mt-10 text-center">
|
||||
By logging in, you agree to our
|
||||
<a href="https://windmill.dev/terms_of_service" target="_blank" rel="noreferrer">
|
||||
Terms of service
|
||||
</a>
|
||||
and
|
||||
<a href="https://windmill.dev/privacy_policy" target="_blank" rel="noreferrer">
|
||||
Privacy policy
|
||||
</a>
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
{#if !passwordFirst}
|
||||
{@render providerButtons()}
|
||||
{#if !autoRedirecting && !disablePasswordLogin && (saml || (logins && logins.length > 0))}
|
||||
{@render orDivider()}
|
||||
<!-- Only an entry point to the form below: once that is open the divider is what
|
||||
separates the two ways in. -->
|
||||
{#if !showPassword}
|
||||
<div class="center-center">
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
onClick={() => {
|
||||
showPassword = true
|
||||
}}
|
||||
>
|
||||
Log in without third-party
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
{#if passwordFirst && (saml || (logins && logins.length > 0))}
|
||||
{@render orDivider()}
|
||||
{@render providerButtons()}
|
||||
{#if !autoRedirecting && showPassword && !disablePasswordLogin}
|
||||
<div>
|
||||
{#if firstTime}
|
||||
<p class="text-xs text-center w-full pb-4 text-secondary">
|
||||
Welcome! Default credentials admin@windmill.dev / changeme have been prefilled.
|
||||
</p>
|
||||
{/if}
|
||||
<div class="space-y-4">
|
||||
{#if cloudHosted}
|
||||
<p class="text-xs text-secondary pb-6">
|
||||
To get credentials without the OAuth providers above, send an email at
|
||||
contact@windmill.dev
|
||||
</p>
|
||||
{/if}
|
||||
<div bind:this={fieldsEl} class="space-y-2 {shake ? 'motion-safe:animate-shake' : ''}">
|
||||
<div class="space-y-1">
|
||||
<label for={emailId} class="block text-xs font-semibold text-emphasis"> Email </label>
|
||||
<div>
|
||||
<TextInput
|
||||
size="md"
|
||||
error={emailErrored}
|
||||
bind:value={email}
|
||||
inputProps={{
|
||||
id: emailId,
|
||||
type: 'email',
|
||||
autocomplete: 'username',
|
||||
'aria-invalid': emailErrored ? 'true' : undefined,
|
||||
'aria-describedby':
|
||||
errorField === 'email' ? emailErrorId : emailErrored ? errorId : undefined,
|
||||
onkeydown: (e) => {
|
||||
// Only move on once the field holds something: while the browser's
|
||||
// credential dropdown is open, Enter belongs to the dropdown
|
||||
if (
|
||||
e.key === 'Enter' &&
|
||||
!e.isComposing &&
|
||||
!e.repeat &&
|
||||
e.currentTarget.value
|
||||
) {
|
||||
e.preventDefault()
|
||||
passwordField?.focus()
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div id={emailErrorId} role="alert" class="min-h-5">
|
||||
{#if errorField === 'email'}
|
||||
<InputError error={credentialsError} />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1">
|
||||
<label for={passwordId} class="block text-xs font-semibold text-emphasis">
|
||||
Password
|
||||
</label>
|
||||
<div>
|
||||
<Password
|
||||
bind:this={passwordField}
|
||||
bind:password
|
||||
id={passwordId}
|
||||
placeholder=""
|
||||
autocomplete="current-password"
|
||||
allowMultiline={false}
|
||||
error={passwordErrored}
|
||||
describedBy={passwordErrored ? errorId : undefined}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
</div>
|
||||
{@render errorMessage()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Button
|
||||
onClick={login}
|
||||
variant="accent"
|
||||
unifiedSize="lg"
|
||||
disabled={!email || !password}
|
||||
>
|
||||
Log in
|
||||
</Button>
|
||||
{#if smtpConfigured}
|
||||
<div class="text-center pt-2">
|
||||
<a
|
||||
href="/user/forgot-password"
|
||||
class="text-2xs text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
>
|
||||
Forgot password?
|
||||
</a>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if cloudHosted}
|
||||
<p class="text-2xs text-secondary mt-10 text-center">
|
||||
By logging in, you agree to our
|
||||
<a href="https://windmill.dev/terms_of_service" target="_blank" rel="noreferrer">
|
||||
Terms of service
|
||||
</a>
|
||||
and
|
||||
<a href="https://windmill.dev/privacy_policy" target="_blank" rel="noreferrer">
|
||||
Privacy policy
|
||||
</a>
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if passwordFirst && (saml || (logins && logins.length > 0))}
|
||||
{@render orDivider()}
|
||||
{@render providerButtons()}
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -1,32 +1,73 @@
|
||||
<script lang="ts">
|
||||
import type { FlowStatusModule } from '$lib/gen'
|
||||
import type { GraphModuleState } from './graph'
|
||||
import { Badge } from './common'
|
||||
import { forLater } from '$lib/forLater'
|
||||
import { displayDate } from '$lib/utils'
|
||||
import { Hourglass } from 'lucide-svelte'
|
||||
import { displayDate, msToCompactDuration } from '$lib/utils'
|
||||
import { Gauge, Hourglass, Moon } from 'lucide-svelte'
|
||||
import { useApprovalCount } from './graph/approvalCount.svelte'
|
||||
|
||||
interface Props {
|
||||
type: FlowStatusModule['type'];
|
||||
scheduled_for: Date | undefined;
|
||||
skipped?: boolean;
|
||||
type: FlowStatusModule['type']
|
||||
scheduled_for: Date | undefined
|
||||
waiting_reason?: GraphModuleState['waiting_reason']
|
||||
concurrency_key?: string
|
||||
/** When its concurrency limit first held the step back. */
|
||||
held_since?: string
|
||||
approval_wait?: GraphModuleState['approval_wait']
|
||||
skipped?: boolean
|
||||
}
|
||||
|
||||
let { type, scheduled_for, skipped = false }: Props = $props();
|
||||
let {
|
||||
type,
|
||||
scheduled_for,
|
||||
waiting_reason = undefined,
|
||||
concurrency_key = undefined,
|
||||
held_since = undefined,
|
||||
approval_wait = undefined,
|
||||
skipped = false
|
||||
}: Props = $props()
|
||||
|
||||
const approval = useApprovalCount(() => approval_wait)
|
||||
|
||||
let now = $state(Date.now())
|
||||
$effect(() => {
|
||||
if (!waiting_reason) return
|
||||
const id = setInterval(() => (now = Date.now()), 1000)
|
||||
return () => clearInterval(id)
|
||||
})
|
||||
let sleepLeft = $derived(Math.max(new Date(scheduled_for ?? now).getTime() - now, 0))
|
||||
let heldFor = $derived(held_since ? Math.max(now - new Date(held_since).getTime(), 0) : undefined)
|
||||
</script>
|
||||
|
||||
{#if type == 'WaitingForEvents'}
|
||||
<span class="italic text-xs text-violet-700 dark:text-violet-400">
|
||||
<Hourglass class="inline" size={14} />
|
||||
Waiting to be resumed by resume events such as approvals
|
||||
<span class="italic text-xs text-primary">
|
||||
<Hourglass class="inline text-violet-500" size={14} />
|
||||
{approval_wait ? approval.label : 'Waiting to be resumed by resume events such as approvals'}
|
||||
</span>
|
||||
{:else if type == 'WaitingForPriorSteps'}
|
||||
<span class="italic text-xs text-primary">
|
||||
<Hourglass class="inline" size={14} />
|
||||
Waiting for prior steps to complete
|
||||
</span>
|
||||
{:else if type == 'WaitingForExecutor' && waiting_reason === 'sleep'}
|
||||
<span class="italic text-xs text-primary">
|
||||
<Moon class="inline" size={14} />
|
||||
Sleeping until {displayDate(scheduled_for, true)} · {msToCompactDuration(sleepLeft, 0)} left
|
||||
</span>
|
||||
{:else if type == 'WaitingForExecutor' && waiting_reason === 'concurrency'}
|
||||
<span class="italic text-xs text-primary">
|
||||
<Gauge class="inline text-orange-500" size={14} />
|
||||
Held by concurrency limit{heldFor != undefined
|
||||
? ` · ${msToCompactDuration(heldFor, 0)}`
|
||||
: ''}{concurrency_key ? ` (key ${concurrency_key})` : ''}, next check by {displayDate(
|
||||
scheduled_for,
|
||||
true
|
||||
)}
|
||||
</span>
|
||||
{:else if type == 'WaitingForExecutor'}
|
||||
<span class="italic text-xs text-primary">
|
||||
<Hourglass class="inline" />
|
||||
<Hourglass class="inline" size={14} />
|
||||
{#if scheduled_for && forLater(scheduled_for.toString())}
|
||||
Job is scheduled to be executed at {displayDate(scheduled_for, true)}
|
||||
{:else}
|
||||
|
||||
@@ -98,25 +98,6 @@
|
||||
bind:password={value['secret']}
|
||||
/>
|
||||
</label>
|
||||
<div>
|
||||
<Toggle
|
||||
options={{
|
||||
right:
|
||||
'Allow workspace admins to set up Nextcloud integration triggers using these credentials'
|
||||
}}
|
||||
checked={value['share_with_workspaces'] ?? false}
|
||||
on:change={(e) => {
|
||||
value = { ...value, share_with_workspaces: e.detail }
|
||||
}}
|
||||
/>
|
||||
{#if value['share_with_workspaces']}
|
||||
<p class="text-xs text-tertiary mt-1">
|
||||
Workspace admins will be able to connect Nextcloud integration triggers without
|
||||
configuring their own OAuth client. The credentials are not exposed to them. Connections
|
||||
use whichever redirect URI the client is registered with.
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
<CollapseLink text="Instructions">
|
||||
<div class="text-xs text-primary border rounded-md p-4">
|
||||
1. Go to your Nextcloud instance as an administrator<br />
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
<script lang="ts">
|
||||
import { Alert, Button } from '$lib/components/common'
|
||||
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
|
||||
import type { OffboardPathConflict } from '$lib/gen'
|
||||
import { apiErrorMessage } from '$lib/utils'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import {
|
||||
canDeleteKind,
|
||||
conflictsGoneAfterDelete,
|
||||
deleteItemOfKind,
|
||||
isTrashedKind,
|
||||
itemHref,
|
||||
kindLabel
|
||||
} from './offboarding-utils'
|
||||
|
||||
type Props = {
|
||||
conflicts: OffboardPathConflict[]
|
||||
/** Prefix each line with its workspace (instance-level offboarding). */
|
||||
showWorkspace?: boolean
|
||||
onResolved: (conflict: OffboardPathConflict) => void
|
||||
}
|
||||
|
||||
let { conflicts, showWorkspace = false, onResolved }: Props = $props()
|
||||
|
||||
type Action = 'overwrite' | 'discard'
|
||||
let pending: { conflict: OffboardPathConflict; action: Action } | undefined = $state(undefined)
|
||||
let deleting = $state(false)
|
||||
|
||||
function pathToDelete(p: NonNullable<typeof pending>): string {
|
||||
return p.action === 'overwrite' ? p.conflict.target_path : p.conflict.source_path
|
||||
}
|
||||
|
||||
async function confirm() {
|
||||
if (!pending) return
|
||||
const { conflict } = pending
|
||||
const path = pathToDelete(pending)
|
||||
deleting = true
|
||||
try {
|
||||
await deleteItemOfKind(conflict.kind, conflict.workspace_id, path)
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not delete ${path}: ${apiErrorMessage(e)}`, true)
|
||||
deleting = false
|
||||
return
|
||||
}
|
||||
sendUserToast(`Deleted ${kindLabel(conflict.kind)} ${path}`)
|
||||
const remaining = conflicts.filter((c) => c !== conflict)
|
||||
onResolved(conflict)
|
||||
pending = undefined
|
||||
try {
|
||||
for (const gone of await conflictsGoneAfterDelete(conflict.kind, remaining)) {
|
||||
onResolved(gone)
|
||||
}
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not refresh the remaining conflicts: ${apiErrorMessage(e)}`, true)
|
||||
} finally {
|
||||
deleting = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Alert type="error" title="Path conflicts detected">
|
||||
<p class="text-xs mb-2">
|
||||
These items already exist at the target. For each one, overwrite the existing item with the
|
||||
reassigned one, or discard the reassigned one and keep the existing item. You can also choose a
|
||||
different user/folder.
|
||||
</p>
|
||||
<ul class="flex flex-col gap-1 max-h-48 overflow-y-auto">
|
||||
{#each conflicts as conflict (`${conflict.workspace_id}:${conflict.kind}:${conflict.source_path}`)}
|
||||
{@const href = itemHref(conflict.kind, conflict.target_path)}
|
||||
<li class="flex items-center gap-2 text-xs">
|
||||
<span class="flex-1 min-w-0 truncate" title={conflict.target_path}>
|
||||
{#if showWorkspace}
|
||||
<span class="text-secondary">[{conflict.workspace_id}]</span>
|
||||
{/if}
|
||||
<span class="text-secondary">{kindLabel(conflict.kind)}:</span>
|
||||
{#if href && !showWorkspace}
|
||||
<a {href} target="_blank" rel="noopener noreferrer">{conflict.target_path}</a>
|
||||
{:else}
|
||||
{conflict.target_path}
|
||||
{/if}
|
||||
</span>
|
||||
{#if canDeleteKind(conflict.kind)}
|
||||
<Button
|
||||
unifiedSize="xs"
|
||||
variant="default"
|
||||
disabled={deleting}
|
||||
destructive
|
||||
title="Delete the existing {conflict.target_path} so {conflict.source_path} can take its place"
|
||||
onclick={() => (pending = { conflict, action: 'overwrite' })}
|
||||
>
|
||||
Overwrite target
|
||||
</Button>
|
||||
<Button
|
||||
unifiedSize="xs"
|
||||
variant="default"
|
||||
disabled={deleting}
|
||||
title="Delete {conflict.source_path} and keep the existing {conflict.target_path}"
|
||||
onclick={() => (pending = { conflict, action: 'discard' })}
|
||||
>
|
||||
Discard
|
||||
</Button>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</Alert>
|
||||
|
||||
<ConfirmationModal
|
||||
open={pending != undefined}
|
||||
title={pending?.action === 'overwrite' ? 'Overwrite target' : 'Discard reassigned item'}
|
||||
confirmationText="Delete"
|
||||
loading={deleting}
|
||||
trashbin={pending != undefined && isTrashedKind(pending.conflict.kind)}
|
||||
zIndexClass="z-[6000]"
|
||||
alwaysPortal
|
||||
onConfirmed={confirm}
|
||||
onCanceled={() => (pending = undefined)}
|
||||
>
|
||||
{#if pending}
|
||||
<p class="text-sm">
|
||||
{#if pending.action === 'overwrite'}
|
||||
The existing {kindLabel(pending.conflict.kind)}
|
||||
<span class="font-mono">{pending.conflict.target_path}</span> will be deleted, and
|
||||
<span class="font-mono">{pending.conflict.source_path}</span> will be moved to that path on reassignment.
|
||||
{:else}
|
||||
The {kindLabel(pending.conflict.kind)}
|
||||
<span class="font-mono">{pending.conflict.source_path}</span> will be deleted instead of
|
||||
being reassigned. The existing
|
||||
<span class="font-mono">{pending.conflict.target_path}</span> is kept.
|
||||
{/if}
|
||||
</p>
|
||||
{/if}
|
||||
</ConfirmationModal>
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts" module>
|
||||
import { isTriggerOrScheduleKind } from 'windmill-utils-internal'
|
||||
import { isTriggerOrScheduleKind } from 'windmill-utils-internal/deploy'
|
||||
|
||||
export type OnBehalfOfChoice = 'target' | 'me' | 'custom' | undefined
|
||||
|
||||
|
||||
@@ -1,296 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { run } from 'svelte/legacy'
|
||||
|
||||
import { type GridApi, createGrid, type IDatasource } from 'ag-grid-community'
|
||||
|
||||
import 'ag-grid-community/styles/ag-grid.css'
|
||||
import 'ag-grid-community/styles/ag-theme-alpine.css'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import DarkModeObserver from './DarkModeObserver.svelte'
|
||||
import { AppService, HelpersService } from '$lib/gen'
|
||||
import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile'
|
||||
import { enterpriseLicense } from '$lib/stores'
|
||||
import { Download } from 'lucide-svelte'
|
||||
import { Loader2 } from 'lucide-svelte'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
|
||||
// import 'ag-grid-community/dist/styles/ag-theme-alpine-dark.css'
|
||||
|
||||
let selectedRowIndex = -1
|
||||
interface Props {
|
||||
s3resource: string
|
||||
storage: string | undefined
|
||||
workspaceId: string | undefined
|
||||
disable_download?: boolean
|
||||
// When set (deployed app view), read the file on-behalf of the app author
|
||||
// through the app-scoped, provenance-gated `apps_u/*` endpoints instead of
|
||||
// the viewer-scoped `job_helpers/*` API. Undefined in the editor/preview.
|
||||
appPath?: string | undefined
|
||||
// HMAC bearer (`exp=..&sig=..`) minted by `signS3Objects`. When present on a
|
||||
// deployed-app read, it bypasses the provenance gate — matching the download
|
||||
// and image routes. Forwarded to every app-scoped preview/count/export call.
|
||||
presigned?: string | undefined
|
||||
}
|
||||
|
||||
let {
|
||||
s3resource,
|
||||
storage,
|
||||
workspaceId,
|
||||
disable_download = false,
|
||||
appPath = undefined,
|
||||
presigned = undefined
|
||||
}: Props = $props()
|
||||
|
||||
// Split the presigned bearer into typed query params for the generated client.
|
||||
// Only meaningful in deployed-app (`appPath`) reads; empty otherwise.
|
||||
function presignedParams(): { sig?: string; exp?: string } {
|
||||
if (!appPath || !presigned) return {}
|
||||
const p = new URLSearchParams(presigned)
|
||||
return { sig: p.get('sig') ?? undefined, exp: p.get('exp') ?? undefined }
|
||||
}
|
||||
|
||||
// Route the parquet/csv read through the app-scoped endpoints when `appPath`
|
||||
// is set, else the viewer-scoped helpers. Same request/response shape either
|
||||
// way — the only difference is which identity authorizes the S3 read.
|
||||
function loadRowCount(searchCol: string | undefined, searchTerm: string | undefined) {
|
||||
const workspace = workspaceId ?? $operatingWorkspace!
|
||||
return appPath
|
||||
? AppService.appLoadTableCount({
|
||||
workspace,
|
||||
path: appPath,
|
||||
fileKey: s3resource,
|
||||
searchCol,
|
||||
searchTerm,
|
||||
storage,
|
||||
...presignedParams()
|
||||
})
|
||||
: HelpersService.loadTableRowCount({
|
||||
workspace,
|
||||
path: s3resource,
|
||||
searchCol,
|
||||
searchTerm,
|
||||
storage
|
||||
})
|
||||
}
|
||||
|
||||
function loadChunk(args: {
|
||||
offset?: number
|
||||
limit?: number
|
||||
sortCol?: string
|
||||
sortDesc?: boolean
|
||||
searchCol?: string
|
||||
searchTerm?: string
|
||||
csvSeparator?: string
|
||||
}) {
|
||||
const workspace = workspaceId ?? $operatingWorkspace!
|
||||
const csv = s3resource.endsWith('.csv')
|
||||
if (appPath) {
|
||||
const data = {
|
||||
workspace,
|
||||
path: appPath,
|
||||
fileKey: s3resource,
|
||||
storage,
|
||||
...args,
|
||||
...presignedParams()
|
||||
}
|
||||
return csv ? AppService.appLoadCsvPreview(data) : AppService.appLoadParquetPreview(data)
|
||||
}
|
||||
const data = { workspace, path: s3resource, storage, ...args }
|
||||
return csv ? HelpersService.loadCsvPreview(data) : HelpersService.loadParquetPreview(data)
|
||||
}
|
||||
|
||||
let lastSearch: string | undefined = undefined
|
||||
|
||||
let nbRows: number | undefined = $state(undefined)
|
||||
let csvSeparatorChar: string = $state(',')
|
||||
let datasource: IDatasource = {
|
||||
rowCount: 0,
|
||||
getRows: async function (params) {
|
||||
try {
|
||||
const searchCol = params.filterModel ? Object.keys(params.filterModel)?.[0] : undefined
|
||||
const searchTerm = searchCol ? params.filterModel?.[searchCol]?.filter : undefined
|
||||
const csv = s3resource.endsWith('.csv')
|
||||
const newSearch = searchCol ? searchCol + searchTerm : undefined
|
||||
if (!nbRows || lastSearch != newSearch) {
|
||||
nbRows = undefined
|
||||
const res = await loadRowCount(searchCol, searchTerm)
|
||||
nbRows = res.count
|
||||
lastSearch = newSearch
|
||||
}
|
||||
|
||||
const res = (await loadChunk({
|
||||
offset: params.startRow,
|
||||
limit: params.endRow - params.startRow,
|
||||
sortCol: params.sortModel?.[0]?.colId,
|
||||
sortDesc: params.sortModel?.[0]?.sort == 'desc',
|
||||
searchCol,
|
||||
searchTerm,
|
||||
csvSeparator: csv ? csvSeparatorChar : undefined
|
||||
})) as any
|
||||
for (let i = 0; i < res.rows.length; i++) {
|
||||
res.rows[i]['__index'] = i + params.startRow
|
||||
if (!$enterpriseLicense) {
|
||||
Object.keys(res.rows[i]).forEach((key) => {
|
||||
if (key != '__index') {
|
||||
res.rows[i][key] = 'Require EE'
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
params.successCallback(res.rows, nbRows)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
params.failCallback()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toggleRow(row: any) {
|
||||
if (row) {
|
||||
let rowIndex = row.rowIndex
|
||||
let data = { ...row.data }
|
||||
delete data['__index']
|
||||
if (selectedRowIndex !== rowIndex) {
|
||||
selectedRowIndex = rowIndex
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function toggleRows(rows: any[]) {
|
||||
toggleRow(rows[0])
|
||||
}
|
||||
|
||||
let eGui: HTMLDivElement | undefined = $state()
|
||||
|
||||
let error: string | undefined = $state(undefined)
|
||||
async function mountGrid() {
|
||||
if (eGui) {
|
||||
try {
|
||||
const csv = s3resource.endsWith('.csv')
|
||||
|
||||
const res = (await loadChunk({
|
||||
limit: 0,
|
||||
csvSeparator: csv ? csvSeparatorChar : undefined
|
||||
})) as any
|
||||
|
||||
createGrid(
|
||||
eGui,
|
||||
{
|
||||
rowModelType: 'infinite',
|
||||
datasource,
|
||||
// @ts-ignore
|
||||
columnDefs: res.columns.map((c) => {
|
||||
return {
|
||||
field: c,
|
||||
sortable: true,
|
||||
filter: true,
|
||||
filterParams: {
|
||||
filterOptions: ['contains'],
|
||||
maxNumConditions: 1
|
||||
}
|
||||
}
|
||||
}),
|
||||
pagination: false,
|
||||
// defaultColDef: {
|
||||
// flex: 1
|
||||
// },
|
||||
suppressColumnMoveAnimation: true,
|
||||
rowSelection: 'multiple',
|
||||
rowMultiSelectWithClick: true,
|
||||
suppressRowDeselection: true,
|
||||
|
||||
onSelectionChanged: (e) => {
|
||||
onSelectionChanged(e.api)
|
||||
},
|
||||
getRowId: (data) => {
|
||||
return (data as any).data['__index']
|
||||
}
|
||||
},
|
||||
{}
|
||||
)
|
||||
error = undefined
|
||||
} catch (e) {
|
||||
error = e.body
|
||||
console.error(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onSelectionChanged(api: GridApi<any>) {
|
||||
const rows = api.getSelectedNodes()
|
||||
if (rows != undefined) {
|
||||
toggleRows(rows)
|
||||
}
|
||||
}
|
||||
|
||||
let darkMode: boolean = $state(false)
|
||||
run(() => {
|
||||
eGui && mountGrid()
|
||||
})
|
||||
</script>
|
||||
|
||||
<DarkModeObserver bind:darkMode />
|
||||
|
||||
<div class={twMerge('mt-2 flex flex-col h-full min-h-[600px]')}>
|
||||
{#if s3resource.endsWith('.csv')}
|
||||
<div class="flex flex-row-reverse w-full">
|
||||
<div class="flex items-baseline">
|
||||
<label for="csvSeparatorChar" class="text-2xs text-secondary">Separator</label>
|
||||
|
||||
<div class="w-12 ml-2 mr-2">
|
||||
<select class="h-8" bind:value={csvSeparatorChar} onchange={(e) => mountGrid()}>
|
||||
<option value=",">,</option>
|
||||
<option value=";">;</option>
|
||||
<option value="\t">\t</option>
|
||||
<option value="|">|</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{#if !disable_download && !s3resource.endsWith('.csv')}
|
||||
{@const csvApiPath = appPath
|
||||
? `/w/${workspaceId}/apps_u/download_s3_parquet_file_as_csv/${appPath}?file_key=${encodeURIComponent(s3resource)}${storage ? `&storage=${storage}` : ''}${presigned ? `&${presigned}` : ''}`
|
||||
: `/w/${workspaceId}/job_helpers/download_s3_parquet_file_as_csv?file_key=${encodeURIComponent(s3resource)}${storage ? `&storage=${storage}` : ''}`}
|
||||
{@const csvName = (s3resource.split('/').pop() ?? 'download') + '.csv'}
|
||||
{#if shouldDownloadViaClient()}
|
||||
<button
|
||||
class="text-secondary w-full text-right underline text-2xs whitespace-nowrap"
|
||||
onclick={() => downloadViaClient(csvApiPath, csvName)}
|
||||
><div class="flex flex-row-reverse gap-2 items-center"><Download size={12} /> CSV</div
|
||||
></button
|
||||
>
|
||||
{:else}
|
||||
<a
|
||||
target="_blank"
|
||||
href="/api{csvApiPath}"
|
||||
class="text-secondary w-full text-right underline text-2xs whitespace-nowrap"
|
||||
><div class="flex flex-row-reverse gap-2 items-center"><Download size={12} /> CSV</div></a
|
||||
>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
{#if nbRows != undefined}
|
||||
<div class="text-secondary ml-0.5 text-2xs">{nbRows} rows</div>
|
||||
{:else}
|
||||
<Loader2 class="animate-spin ml-0.5" size={12} />
|
||||
{/if}
|
||||
<div
|
||||
class="ag-theme-alpine shadow-sm h-full"
|
||||
class:ag-theme-alpine-dark={darkMode}
|
||||
style="height: 600px;"
|
||||
>
|
||||
{#if error}
|
||||
<div class="text-red-500">{error}</div>
|
||||
<div>Try changing separator to fix it</div>
|
||||
{/if}
|
||||
<div bind:this={eGui} style="height:100%; "></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- <div class="flex gap-1 absolute bottom-1 right-2 text-sm text-secondary"
|
||||
>{firstRow}{'->'}{lastRow + 1} of {datasource?.rowCount} rows</div
|
||||
> -->
|
||||
@@ -119,7 +119,8 @@
|
||||
'aria-describedby': describedBy,
|
||||
onblur: (e) => onBlur?.(e),
|
||||
onkeydown: (e) => {
|
||||
if (allowMultiline && e.key === 'Enter') {
|
||||
// A modified Enter is left to the caller, which may submit on it.
|
||||
if (allowMultiline && e.key === 'Enter' && !e.metaKey && !e.ctrlKey) {
|
||||
e.preventDefault()
|
||||
insertAndSwitchToMultiline(e.currentTarget as HTMLInputElement, '\n')
|
||||
return
|
||||
|
||||
@@ -104,6 +104,8 @@
|
||||
/** Show the "moving may break other items" warning on a rename. Off for items nothing
|
||||
* can reference by path and whose dependents move with them (eval datasets). */
|
||||
warnOnRename?: boolean
|
||||
/** The error shown when the path is taken, for a caller that offers to overwrite it. */
|
||||
takenError?: string
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -124,7 +126,8 @@
|
||||
workspaceOverride = undefined,
|
||||
actingUser = undefined,
|
||||
allowedExistingPath = undefined,
|
||||
warnOnRename = true
|
||||
warnOnRename = true,
|
||||
takenError = 'path already used'
|
||||
}: Props = $props()
|
||||
|
||||
let ws = $derived(workspaceOverride ?? $operatingWorkspace)
|
||||
@@ -270,7 +273,7 @@
|
||||
(path == '' || checkInitialPathExistence || path != initialPath) &&
|
||||
(await pathExists(path, kind))
|
||||
) {
|
||||
error = 'path already used'
|
||||
error = takenError
|
||||
} else if (meta && validateName(meta)) {
|
||||
error = ''
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@
|
||||
<div class="flex flex-col gap-2">
|
||||
<a
|
||||
class="text-xs flex flex-row items-center gap-1 w-fit"
|
||||
href="{target.base_url}/#user-settings"
|
||||
href="{target.base_url}/#user-settings-tokens"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
|
||||
@@ -322,7 +322,7 @@
|
||||
<select class="h-8" bind:value={csvSeparatorChar} onchange={onCsvControlsChanged}>
|
||||
<option value=",">,</option>
|
||||
<option value=";">;</option>
|
||||
<option value="\t">\t</option>
|
||||
<option value={'\t'}>\t</option>
|
||||
<option value="|">|</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
import OpenInSessionButton, {
|
||||
type OpenInSessionSource
|
||||
} from './sessions/OpenInSessionButton.svelte'
|
||||
import { assertDraftSaved } from './sessions/pageDrawerSession'
|
||||
import {
|
||||
defaultScripts,
|
||||
enterpriseLicense,
|
||||
@@ -1071,17 +1072,19 @@
|
||||
// discardIf baseline, safe only when there is none.
|
||||
async function persistDraftForSession(): Promise<void> {
|
||||
await saveDraft()
|
||||
if (opWorkspace && userDraftPath && savedScript?.no_deployed === true) {
|
||||
if (!opWorkspace || !userDraftPath) return
|
||||
if (savedScript?.no_deployed === true) {
|
||||
await UserDraft.forcePersist('script', userDraftPath, { workspace: opWorkspace })
|
||||
}
|
||||
assertDraftSaved({ workspace: opWorkspace, itemKind: 'script', path: userDraftPath })
|
||||
}
|
||||
|
||||
const sessionOpen: OpenInSessionSource | undefined = $derived(
|
||||
userDraftPath
|
||||
indicatorPath
|
||||
? {
|
||||
// URL draft path the editor loads/saves by, not the friendly
|
||||
// Draft path the editor loads/saves by, not the friendly
|
||||
// `script.path` (a new script's has no row → "not found").
|
||||
target: { kind: 'script', path: userDraftPath },
|
||||
target: { kind: 'script', path: indicatorPath },
|
||||
workspaceId: opWorkspace ?? undefined,
|
||||
beforeOpen: persistDraftForSession
|
||||
}
|
||||
@@ -2404,6 +2407,7 @@
|
||||
bind:this={scriptEditor}
|
||||
bind:schema={script.schema}
|
||||
path={script.path}
|
||||
storagePath={indicatorPath}
|
||||
bind:code={script.content}
|
||||
timeout={script.timeout}
|
||||
tag={script.tag}
|
||||
|
||||
@@ -2763,6 +2763,10 @@
|
||||
lineNumbersMinChars={4}
|
||||
folding
|
||||
{path}
|
||||
codeSource={customUi?.editorBar?.aiGen != false &&
|
||||
(inSessionPane || SUPPORTED_CHAT_SCRIPT_LANGUAGES.includes(lang ?? ''))
|
||||
? { kind: 'script', path: path ?? '', part: activeModuleTab ?? undefined }
|
||||
: undefined}
|
||||
bind:code={editorCode}
|
||||
bind:websocketAlive
|
||||
bind:this={editor}
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
import InstanceAISettings from './instanceSettings/InstanceAISettings.svelte'
|
||||
import ExternalJwtTokens from './instanceSettings/ExternalJwtTokens.svelte'
|
||||
import GuestActivityList from './instanceSettings/GuestActivityList.svelte'
|
||||
import TokenReview from './instanceSettings/TokenReview.svelte'
|
||||
import { Alert, Skeleton } from '$lib/components/common'
|
||||
|
||||
let filter = $state('')
|
||||
@@ -98,15 +99,24 @@
|
||||
let editWrappers: Record<string, HTMLDivElement> = $state({})
|
||||
let activeOnly = $state(false)
|
||||
|
||||
// Who has two-factor authentication, fetched beside the list. Undefined on a build without
|
||||
// two-factor support, which hides the column.
|
||||
let totp = $state<{ required: boolean; users: Set<string> } | undefined>(undefined)
|
||||
|
||||
async function listUsers(activeOnly: boolean): Promise<void> {
|
||||
users = await UserService.listUsersAsSuperAdmin({ perPage: 100000, activeOnly: activeOnly })
|
||||
const [list, enabled] = await Promise.all([
|
||||
UserService.listUsersAsSuperAdmin({ perPage: 100000, activeOnly: activeOnly }),
|
||||
UserService.listTotpEnabledUsers().catch(() => undefined)
|
||||
])
|
||||
users = list
|
||||
totp = enabled && { required: enabled.required, users: new Set(enabled.users) }
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
listUsers(activeOnly)
|
||||
})
|
||||
|
||||
let usersSubTab: 'users' | 'ext_jwt' | 'guests' = $state('users')
|
||||
let usersSubTab: 'users' | 'ext_jwt' | 'guests' | 'tokens' = $state('users')
|
||||
let guestList: GuestList | undefined = $state(undefined)
|
||||
let guestHasMore = $state(true)
|
||||
let guestLoading = $state(false)
|
||||
@@ -382,6 +392,7 @@
|
||||
<Tab value="ext_jwt" label="External JWTs" />
|
||||
{/if}
|
||||
<Tab value="guests" label="Guests" />
|
||||
<Tab value="tokens" label="Token review" />
|
||||
</Tabs>
|
||||
|
||||
{#if usersListShown}
|
||||
@@ -437,6 +448,9 @@
|
||||
{/if}
|
||||
<Cell head>Name</Cell>
|
||||
<Cell head>Auth</Cell>
|
||||
{#if totp}
|
||||
<Cell head>2FA</Cell>
|
||||
{/if}
|
||||
{#if activeOnly}
|
||||
<Cell head>Kind</Cell>
|
||||
{/if}
|
||||
@@ -510,6 +524,17 @@
|
||||
><span title={login_type} class="truncate block">{login_type}</span
|
||||
></Cell
|
||||
>
|
||||
{#if totp}
|
||||
<Cell>
|
||||
{#if login_type != 'password'}
|
||||
<span class="text-secondary">–</span>
|
||||
{:else if totp.users.has(email)}
|
||||
On
|
||||
{:else}
|
||||
<span class="text-secondary">Off</span>
|
||||
{/if}
|
||||
</Cell>
|
||||
{/if}
|
||||
{#if activeOnly}
|
||||
<Cell>
|
||||
<span>
|
||||
@@ -679,6 +704,8 @@
|
||||
value={name}
|
||||
{username}
|
||||
{email}
|
||||
totpEnabled={totp?.users.has(email) ?? false}
|
||||
totpRequired={totp?.required ?? false}
|
||||
on:refresh={() => {
|
||||
listUsers(activeOnly)
|
||||
}}
|
||||
@@ -768,7 +795,8 @@
|
||||
<Cell
|
||||
colspan={5 +
|
||||
(automateUsernameCreation ? 1 : 0) +
|
||||
(activeOnly ? 1 : 0)}
|
||||
(activeOnly ? 1 : 0) +
|
||||
(totp ? 1 : 0)}
|
||||
>
|
||||
<Button
|
||||
variant="subtle"
|
||||
@@ -800,6 +828,8 @@
|
||||
loadExtJwtPage(1)
|
||||
}}
|
||||
/>
|
||||
{:else if usersSubTab === 'tokens'}
|
||||
<TokenReview />
|
||||
{:else if usersSubTab === 'guests' && !guestList}
|
||||
{#if guestLoading}
|
||||
<Skeleton layout={[[2], 1, [8]]} />
|
||||
|
||||
@@ -26,6 +26,13 @@
|
||||
let contentEditableDiv: HTMLDivElement
|
||||
let isUpdating = false
|
||||
|
||||
/** A fresh global copy of `regex` for an exec loop, keeping its other flags (`u`, `i`).
|
||||
* Not sticky: a sticky scan stops at the first text that is not a match. */
|
||||
function globalCopy(regex: RegExp): RegExp {
|
||||
const flags = regex.flags.replace('y', '')
|
||||
return new RegExp(regex, flags.includes('g') ? flags : flags + 'g')
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!value.trim() && value !== '') value = ''
|
||||
})
|
||||
@@ -37,7 +44,9 @@
|
||||
const currentText = getTextContent()
|
||||
if (currentText !== value) {
|
||||
updateDisplay(value)
|
||||
if (!_preventCursorMoveOnNextSync) {
|
||||
// Placing the caret focuses this input: never take focus from another field
|
||||
// that wrote the value, such as a table's column filter.
|
||||
if (!_preventCursorMoveOnNextSync && !typingElsewhere()) {
|
||||
restoreCursor(value.length)
|
||||
const cursorPos = getCursorPosition()
|
||||
updateCurrentTag(cursorPos)
|
||||
@@ -47,6 +56,15 @@
|
||||
_preventCursorMoveOnNextSync = false
|
||||
})
|
||||
|
||||
function typingElsewhere(): boolean {
|
||||
const active = document.activeElement
|
||||
return (
|
||||
active instanceof HTMLElement &&
|
||||
!contentEditableDiv.contains(active) &&
|
||||
active.matches('input, textarea, select, [contenteditable]:not([contenteditable="false"])')
|
||||
)
|
||||
}
|
||||
|
||||
export function preventCursorMoveOnNextSync() {
|
||||
_preventCursorMoveOnNextSync = true
|
||||
}
|
||||
@@ -70,7 +88,7 @@
|
||||
// Find all highlight matches in the raw text
|
||||
const hlMatches: Array<{ start: number; end: number; classes: string }> = []
|
||||
for (const hl of highlights) {
|
||||
const regex = new RegExp(hl.regex, 'g')
|
||||
const regex = globalCopy(hl.regex)
|
||||
let m
|
||||
while ((m = regex.exec(rawText)) !== null) {
|
||||
hlMatches.push({ start: m.index, end: m.index + m[0].length, classes: hl.classes })
|
||||
@@ -111,7 +129,7 @@
|
||||
const matches: Array<{ start: number; end: number; tagIndex: number }> = []
|
||||
|
||||
tags.forEach((tag, tagIndex) => {
|
||||
const regex = new RegExp(tag.regex, 'g')
|
||||
const regex = globalCopy(tag.regex)
|
||||
let match
|
||||
while ((match = regex.exec(text)) !== null) {
|
||||
matches.push({
|
||||
@@ -251,7 +269,7 @@
|
||||
// Find all tag positions
|
||||
const tagPositions: Array<{ start: number; end: number }> = []
|
||||
for (const tag of tags) {
|
||||
const regex = new RegExp(tag.regex, 'g')
|
||||
const regex = globalCopy(tag.regex)
|
||||
let match
|
||||
while ((match = regex.exec(value)) !== null) {
|
||||
tagPositions.push({
|
||||
@@ -293,7 +311,7 @@
|
||||
let currentTag: { id: string } | null = null
|
||||
|
||||
for (const tag of tags) {
|
||||
const regex = new RegExp(tag.regex, 'g')
|
||||
const regex = globalCopy(tag.regex)
|
||||
let match
|
||||
while ((match = regex.exec(value)) !== null) {
|
||||
const start = match.index
|
||||
|
||||
@@ -1,32 +1,23 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
type CompletedJob,
|
||||
JobService,
|
||||
type Preview,
|
||||
ResourceService,
|
||||
SettingService,
|
||||
UserService,
|
||||
VariableService
|
||||
} from '$lib/gen'
|
||||
|
||||
import { Database, Loader2 } from 'lucide-svelte'
|
||||
import Button from './common/button/Button.svelte'
|
||||
import Tooltip from './meltComponents/Tooltip.svelte'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
import {
|
||||
canTestConnection,
|
||||
connectionTestTooltip,
|
||||
testResourceConnection
|
||||
} from './resourceConnectionTest'
|
||||
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
import { tryEvery } from '$lib/utils'
|
||||
|
||||
interface Props {
|
||||
workspaceOverride?: string | undefined
|
||||
resourceType: string | undefined
|
||||
args?: Record<string, any> | any
|
||||
buttonTextOverride?: string | undefined
|
||||
// Object-storage types only: probe from a preview job (proves a worker reaches the API)
|
||||
// instead of the browser. The job gets a short-lived token minted for the caller, since a
|
||||
// job token is never a super admin, and that token is readable in the job's stored args
|
||||
// until revoked: only use it where the workspace's job readers may hold the caller's rights.
|
||||
/** See `testResourceConnection`. */
|
||||
viaWorker?: boolean
|
||||
}
|
||||
|
||||
@@ -38,316 +29,30 @@
|
||||
viaWorker = false
|
||||
}: Props = $props()
|
||||
|
||||
// Object-storage resource types share one probe, the API's own connectivity test, which runs
|
||||
// on the API server with the caller's privileges. Each type maps its resource to the
|
||||
// ObjectSettings body that route expects.
|
||||
const objectStorageBody: { [key: string]: (args: any) => Record<string, any> } = {
|
||||
s3: (s3) => ({
|
||||
type: 'S3',
|
||||
region: s3.region,
|
||||
bucket: s3.bucket,
|
||||
endpoint: s3.endPoint,
|
||||
port: s3.port,
|
||||
allow_http: !s3.useSSL,
|
||||
access_key: s3.accessKey,
|
||||
secret_key: s3.secretKey,
|
||||
path_style: s3.pathStyle
|
||||
}),
|
||||
azure_blob: (s3) => ({ type: 'Azure', ...s3 }),
|
||||
s3_bucket: (bucket) => bucket
|
||||
}
|
||||
|
||||
const OBJECT_STORAGE_TEST_SCRIPT = `
|
||||
export async function main(bucket: any, api_token: string) {
|
||||
const res = await fetch(process.env.BASE_URL + '/api/settings/test_object_storage_config', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer ' + api_token,
|
||||
},
|
||||
body: JSON.stringify(bucket),
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new Error(await res.text())
|
||||
}
|
||||
return await res.text()
|
||||
}
|
||||
`
|
||||
|
||||
const scripts: {
|
||||
[key: string]: {
|
||||
code: string
|
||||
lang: string
|
||||
argName: string
|
||||
// Shown as an info tooltip next to the button, e.g. to clarify where the test executes
|
||||
tooltip?: string
|
||||
additionalCheck?: (testResult: CompletedJob) => CompletedJob
|
||||
}
|
||||
} = {
|
||||
postgresql: {
|
||||
code: `SELECT 1`,
|
||||
lang: 'postgresql',
|
||||
argName: 'database'
|
||||
},
|
||||
mysql: {
|
||||
code: `SELECT 1`,
|
||||
lang: 'mysql',
|
||||
argName: 'database'
|
||||
},
|
||||
bigquery: {
|
||||
code: `select 1`,
|
||||
lang: 'bigquery',
|
||||
argName: 'database'
|
||||
},
|
||||
snowflake: {
|
||||
code: `select 1`,
|
||||
lang: 'snowflake',
|
||||
argName: 'database'
|
||||
},
|
||||
snowflake_oauth: {
|
||||
code: `select 1`,
|
||||
lang: 'snowflake',
|
||||
argName: 'database'
|
||||
},
|
||||
mssql: {
|
||||
code: `SELECT 1`,
|
||||
lang: 'mssql',
|
||||
argName: 'database'
|
||||
},
|
||||
oracledb: {
|
||||
code: `SELECT 1 FROM DUAL`,
|
||||
lang: 'oracledb',
|
||||
argName: 'database'
|
||||
},
|
||||
s3: {
|
||||
code: OBJECT_STORAGE_TEST_SCRIPT,
|
||||
lang: 'bun',
|
||||
argName: 'bucket',
|
||||
tooltip:
|
||||
'The storage operations of this test run on the Windmill server (the API process) with your permissions, not on the worker. Non-super-admins can only test public endpoints with an explicit access key and secret key; super admins can also test private endpoints and rely on the ambient AWS credentials of the server (environment variables, instance role). Scripts using this resource directly through an S3 SDK resolve credentials on the worker instead, so results may differ.'
|
||||
},
|
||||
azure_blob: {
|
||||
code: OBJECT_STORAGE_TEST_SCRIPT,
|
||||
lang: 'bun',
|
||||
argName: 'bucket',
|
||||
tooltip:
|
||||
'The storage operations of this test run on the Windmill server (the API process) with your permissions, not on the worker. Non-super-admins can only test public endpoints with an explicit access key.'
|
||||
},
|
||||
graphql: {
|
||||
code: '{ __typename }',
|
||||
lang: 'graphql',
|
||||
argName: 'api',
|
||||
additionalCheck: (testResult: CompletedJob) => {
|
||||
if (
|
||||
testResult.success &&
|
||||
(typeof testResult.result !== 'object' || !('__typename' in (testResult.result ?? {})))
|
||||
) {
|
||||
return {
|
||||
...testResult,
|
||||
result: {
|
||||
error: {
|
||||
message: 'Invalid GraphQL API response'
|
||||
}
|
||||
},
|
||||
success: false
|
||||
}
|
||||
} else {
|
||||
return testResult
|
||||
}
|
||||
}
|
||||
},
|
||||
s3_bucket: {
|
||||
code: OBJECT_STORAGE_TEST_SCRIPT,
|
||||
lang: 'bun',
|
||||
argName: 'bucket',
|
||||
tooltip:
|
||||
"The storage operations of this test run on the Windmill server (the API process) with your permissions. Non-super-admins can only test public endpoints with explicit credentials; super admins can also test private endpoints and rely on the server's ambient credentials for the configured provider (environment variables, instance role)."
|
||||
}
|
||||
}
|
||||
|
||||
let loading = $state(false)
|
||||
|
||||
// The token is revoked as soon as the job settles; the expiry only covers a browser that
|
||||
// goes away mid-test. It is readable in the job's stored args until then, hence the short life.
|
||||
const API_TOKEN_TTL_MS = 60_000
|
||||
// Tokens are addressed by their first 10 characters (TOKEN_PREFIX_LEN on the backend).
|
||||
const API_TOKEN_PREFIX_LEN = 10
|
||||
|
||||
async function mintApiToken(): Promise<string> {
|
||||
return await UserService.createToken({
|
||||
requestBody: {
|
||||
label: `ephemeral-test-connection: ${resourceType}`,
|
||||
expiration: new Date(Date.now() + API_TOKEN_TTL_MS).toISOString(),
|
||||
scopes: ['settings:write']
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function revokeApiToken(token: string | undefined) {
|
||||
if (!token) return
|
||||
try {
|
||||
await UserService.deleteToken({ tokenPrefix: token.slice(0, API_TOKEN_PREFIX_LEN) })
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A preview job gets its arguments interpolated on the worker: `$var:`, `$jsonvar:` and
|
||||
// `$res:` references are replaced with the job's privileges before the script runs. The
|
||||
// browser path has to do the same with the caller's session, or a secret stored as a linked
|
||||
// variable (what the "Add resource" drawer saves) is sent verbatim as the credential.
|
||||
async function resolveReferences(value: any, workspace: string): Promise<any> {
|
||||
if (typeof value === 'string') {
|
||||
if (value.startsWith('$var:')) {
|
||||
return await VariableService.getVariableValue({
|
||||
workspace,
|
||||
path: value.slice('$var:'.length)
|
||||
})
|
||||
}
|
||||
if (value.startsWith('$jsonvar:')) {
|
||||
return JSON.parse(
|
||||
await VariableService.getVariableValue({
|
||||
workspace,
|
||||
path: value.slice('$jsonvar:'.length)
|
||||
})
|
||||
)
|
||||
}
|
||||
if (value.startsWith('$res:')) {
|
||||
return await ResourceService.getResourceValueInterpolated({
|
||||
workspace,
|
||||
path: value.slice('$res:'.length)
|
||||
})
|
||||
}
|
||||
return value
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return await Promise.all(value.map((v) => resolveReferences(v, workspace)))
|
||||
}
|
||||
if (value && typeof value === 'object') {
|
||||
const resolved: Record<string, any> = {}
|
||||
for (const [key, v] of Object.entries(value)) {
|
||||
resolved[key] = await resolveReferences(v, workspace)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// The route bounds the probe only for non-super-admins; a super admin's probe against an
|
||||
// endpoint that accepts the connection and never answers would otherwise spin here forever.
|
||||
const BROWSER_TEST_TIMEOUT_MS = 15_000
|
||||
|
||||
async function testObjectStorageFromBrowser(body: Record<string, any>, workspace: string) {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined = undefined
|
||||
try {
|
||||
const request = SettingService.testObjectStorageConfig({
|
||||
requestBody: await resolveReferences(body, workspace)
|
||||
})
|
||||
await Promise.race([
|
||||
request,
|
||||
new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
request.cancel()
|
||||
reject(
|
||||
new Error(
|
||||
`no answer from the storage endpoint after ${BROWSER_TEST_TIMEOUT_MS / 1000}s`
|
||||
)
|
||||
)
|
||||
}, BROWSER_TEST_TIMEOUT_MS)
|
||||
})
|
||||
])
|
||||
sendUserToast('Connection successful', false)
|
||||
} catch (err: any) {
|
||||
sendUserToast('Connection error: ' + (err?.body ?? err?.message ?? err), true)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
loading = false
|
||||
}
|
||||
}
|
||||
const tooltip = $derived(resourceType ? connectionTestTooltip(resourceType) : undefined)
|
||||
|
||||
async function testConnection() {
|
||||
if (!resourceType) return
|
||||
loading = true
|
||||
|
||||
const resourceScript = scripts[resourceType]
|
||||
const workspace = workspaceOverride ?? $operatingWorkspace!
|
||||
const objectStorageArgs: Record<string, any> | undefined =
|
||||
resourceType in objectStorageBody ? objectStorageBody[resourceType](args) : undefined
|
||||
|
||||
if (objectStorageArgs && !viaWorker) {
|
||||
await testObjectStorageFromBrowser(objectStorageArgs, workspace)
|
||||
return
|
||||
}
|
||||
|
||||
let apiToken: string | undefined = undefined
|
||||
let job: string
|
||||
try {
|
||||
if (objectStorageArgs) {
|
||||
apiToken = await mintApiToken()
|
||||
}
|
||||
job = await JobService.runScriptPreview({
|
||||
workspace,
|
||||
requestBody: {
|
||||
path: `testConnection: ${resourceType}`,
|
||||
language: resourceScript.lang as Preview['language'],
|
||||
content: resourceScript.code,
|
||||
args: objectStorageArgs
|
||||
? { bucket: objectStorageArgs, api_token: apiToken }
|
||||
: { [resourceScript.argName]: args }
|
||||
}
|
||||
const result = await testResourceConnection({
|
||||
workspace: workspaceOverride ?? $operatingWorkspace!,
|
||||
resourceType,
|
||||
args,
|
||||
viaWorker
|
||||
})
|
||||
} catch (err: any) {
|
||||
sendUserToast(
|
||||
result.ok ? 'Connection successful' : 'Connection error: ' + result.error,
|
||||
!result.ok
|
||||
)
|
||||
} finally {
|
||||
loading = false
|
||||
await revokeApiToken(apiToken)
|
||||
sendUserToast('Connection error: ' + (err?.body ?? err?.message ?? err), true)
|
||||
return
|
||||
}
|
||||
|
||||
tryEvery({
|
||||
tryCode: async () => {
|
||||
let testResult = await JobService.getCompletedJob({
|
||||
workspace,
|
||||
id: job
|
||||
})
|
||||
if (resourceScript.additionalCheck) {
|
||||
testResult = resourceScript.additionalCheck(testResult)
|
||||
}
|
||||
loading = false
|
||||
revokeApiToken(apiToken)
|
||||
sendUserToast(
|
||||
testResult.success
|
||||
? 'Connection successful'
|
||||
: 'Connection error: ' + testResult.result?.['error']?.['message'],
|
||||
!testResult.success
|
||||
)
|
||||
},
|
||||
timeoutCode: async () => {
|
||||
loading = false
|
||||
revokeApiToken(apiToken)
|
||||
sendUserToast(
|
||||
'Connection did not resolve after 5s or job did not start. Do you have native workers or a worker group listening to the proper tag available?',
|
||||
true
|
||||
)
|
||||
try {
|
||||
await JobService.cancelQueuedJob({
|
||||
workspace,
|
||||
id: job,
|
||||
requestBody: {
|
||||
reason:
|
||||
'Connection did not resolve after 5s. Do you have native workers or a worker group listening to the proper tag available?'
|
||||
}
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
},
|
||||
interval: 500,
|
||||
timeout: 5000
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if resourceType && Object.keys(scripts).includes(resourceType)}
|
||||
{#if canTestConnection(resourceType)}
|
||||
<div class="flex items-center gap-1">
|
||||
<Button spacingSize="sm" size="xs" unifiedSize="md" variant="default" on:click={testConnection}>
|
||||
{#if loading}
|
||||
@@ -357,9 +62,9 @@ export async function main(bucket: any, api_token: string) {
|
||||
{/if}
|
||||
{buttonTextOverride ?? 'Test connection'}
|
||||
</Button>
|
||||
{#if scripts[resourceType].tooltip}
|
||||
{#if tooltip}
|
||||
<Tooltip>
|
||||
{#snippet text()}{scripts[resourceType].tooltip}{/snippet}
|
||||
{#snippet text()}{tooltip}{/snippet}
|
||||
</Tooltip>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -168,8 +168,11 @@
|
||||
|
||||
// Original mode
|
||||
const nbSecondsAgo = secondsAgo(date)
|
||||
if (nbSecondsAgo < 600) {
|
||||
if (nbSecondsAgo < 60) {
|
||||
return `${nbSecondsAgo}s ago`
|
||||
} else if (nbSecondsAgo < 600) {
|
||||
const mins = Math.floor(nbSecondsAgo / 60)
|
||||
return `${mins} min${mins !== 1 ? 's' : ''} ago`
|
||||
} else if (isToday(date)) {
|
||||
isRecent = false
|
||||
return `today at ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
import Popover from './Popover.svelte'
|
||||
|
||||
interface Props {
|
||||
position?: 'center' | 'left' | 'right'
|
||||
/** `none`: a middle piece of a bar split in several. */
|
||||
position?: 'center' | 'left' | 'right' | 'none'
|
||||
total: number
|
||||
min: number | undefined
|
||||
started_at: number | undefined
|
||||
@@ -61,7 +62,9 @@
|
||||
? 'rounded-l-md'
|
||||
: position == 'right'
|
||||
? 'rounded-r-md'
|
||||
: 'rounded-md'} center-center text-white text-2xs whitespace-nowrap hover:outline outline-1 outline-black"
|
||||
: position == 'none'
|
||||
? ''
|
||||
: 'rounded-md'} center-center text-white text-2xs whitespace-nowrap hover:outline outline-1 outline-black"
|
||||
>
|
||||
{#snippet text()}
|
||||
{#if tooltip}
|
||||
|
||||
@@ -4,12 +4,13 @@
|
||||
import { apiErrorMessage, classNames } from '$lib/utils'
|
||||
import { AlertTriangle, CornerDownLeft, Loader2 } from 'lucide-svelte'
|
||||
import { UserService, FolderService } from '$lib/gen'
|
||||
import type { OffboardPreview } from '$lib/gen/types.gen'
|
||||
import type { OffboardPathConflict, OffboardPreview } from '$lib/gen/types.gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import OffboardWorkspaceSection from './OffboardWorkspaceSection.svelte'
|
||||
import { countPaths } from './offboarding-utils'
|
||||
import OffboardConflictList from './OffboardConflictList.svelte'
|
||||
import { countPaths, withoutConflict } from './offboarding-utils'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
@@ -24,7 +25,7 @@
|
||||
let preview = $state(undefined as OffboardPreview | undefined)
|
||||
let loading = $state(false)
|
||||
let submitting = $state(false)
|
||||
let conflicts: string[] = $state([])
|
||||
let conflicts: OffboardPathConflict[] = $state([])
|
||||
|
||||
let doReassign = $state(true)
|
||||
let targetKind: 'user' | 'folder' = $state('user')
|
||||
@@ -117,8 +118,8 @@
|
||||
delete_user: deleteUser
|
||||
}
|
||||
})
|
||||
if (result.conflicts && result.conflicts.length > 0) {
|
||||
conflicts = result.conflicts
|
||||
if (result.conflict_items && result.conflict_items.length > 0) {
|
||||
conflicts = result.conflict_items
|
||||
} else {
|
||||
sendUserToast(
|
||||
deleteUser
|
||||
@@ -221,17 +222,10 @@
|
||||
{/if}
|
||||
|
||||
{#if conflicts.length > 0}
|
||||
<Alert type="error" title="Path conflicts detected">
|
||||
<p class="text-xs mb-1"
|
||||
>These items already exist at the target. Rename or delete them, or choose a
|
||||
different user/folder.</p
|
||||
>
|
||||
<ul class="text-xs list-disc list-inside max-h-32 overflow-y-auto">
|
||||
{#each conflicts as conflict, i (i)}
|
||||
<li>{conflict}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</Alert>
|
||||
<OffboardConflictList
|
||||
{conflicts}
|
||||
onResolved={(c) => (conflicts = withoutConflict(conflicts, c))}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
<script lang="ts">
|
||||
import Drawer from '$lib/components/common/drawer/Drawer.svelte'
|
||||
import DrawerContent from '$lib/components/common/drawer/DrawerContent.svelte'
|
||||
import Version from './Version.svelte'
|
||||
import DarkModeToggle from './sidebar/DarkModeToggle.svelte'
|
||||
import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte'
|
||||
import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import TokensTable from './settings/TokensTable.svelte'
|
||||
import { createEventDispatcher, tick } from 'svelte'
|
||||
import CreateToken from './settings/CreateToken.svelte'
|
||||
import UserInfoSettings from './settings/UserInfoSettings.svelte'
|
||||
import AIUserSettings from './settings/AIUserSettings.svelte'
|
||||
import AiUsagePanel from './workspaceSettings/AiUsagePanel.svelte'
|
||||
import { copilotInfo, copilotWorkspace } from '$lib/aiStore'
|
||||
import {
|
||||
getDarkModeVariant,
|
||||
setDarkModeVariant,
|
||||
type DarkModeVariant
|
||||
} from '$lib/darkModeVariant'
|
||||
|
||||
interface Props {
|
||||
scopes?: string[] | undefined
|
||||
newTokenLabel?: string | undefined
|
||||
newTokenWorkspace?: string | undefined
|
||||
newToken?: string | undefined
|
||||
showMcpMode?: boolean
|
||||
}
|
||||
|
||||
let {
|
||||
scopes = undefined,
|
||||
newTokenLabel = undefined,
|
||||
newTokenWorkspace = undefined,
|
||||
newToken = $bindable(undefined),
|
||||
showMcpMode = false
|
||||
}: Props = $props()
|
||||
|
||||
let drawer: Drawer | undefined = $state()
|
||||
let mcpSection: HTMLDivElement | undefined = $state()
|
||||
let tokensTable: TokensTable | undefined = $state()
|
||||
let darkVariant = $state<DarkModeVariant>(getDarkModeVariant())
|
||||
|
||||
const dispatch = createEventDispatcher()
|
||||
|
||||
export async function openDrawer(mcpMode: boolean = false) {
|
||||
drawer?.openDrawer()
|
||||
if (mcpMode) {
|
||||
await tick()
|
||||
mcpSection?.scrollIntoView({ block: 'start' })
|
||||
}
|
||||
}
|
||||
|
||||
export function closeDrawer() {
|
||||
drawer?.closeDrawer()
|
||||
removeHash()
|
||||
}
|
||||
|
||||
function removeHash() {
|
||||
window.location.hash = ''
|
||||
}
|
||||
|
||||
function handleTokenCreated(token: string) {
|
||||
newToken = token
|
||||
dispatch('tokenCreated', token)
|
||||
}
|
||||
</script>
|
||||
|
||||
<Drawer
|
||||
bind:this={drawer}
|
||||
size="900px"
|
||||
on:open={() => (darkVariant = getDarkModeVariant())}
|
||||
on:close={removeHash}
|
||||
>
|
||||
<DrawerContent title="User settings" on:close={closeDrawer}>
|
||||
<div class="flex flex-col gap-6 pb-8">
|
||||
{#if scopes == undefined}
|
||||
<div
|
||||
class="flex flex-row justify-between items-start gap-2 border border-border-light p-4 rounded-md"
|
||||
>
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="font-semibold text-emphasis text-xs flex items-center">
|
||||
Theme <DarkModeToggle forcedDarkMode={false} />
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-xs text-secondary">Dark variant</span>
|
||||
<ToggleButtonGroup
|
||||
selected={darkVariant}
|
||||
class="w-fit"
|
||||
onSelected={(v) => {
|
||||
darkVariant = v
|
||||
setDarkModeVariant(v)
|
||||
}}
|
||||
>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton value="default" label="Default" size="sm" {item} />
|
||||
<ToggleButton value="github" label="GitHub" size="sm" {item} />
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-xs text-emphasis flex-col flex">
|
||||
Windmill <Version />
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 w-full gap-4">
|
||||
<div class="min-w-0">
|
||||
<UserInfoSettings />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<AIUserSettings />
|
||||
</div>
|
||||
</div>
|
||||
<!-- Keyed on the workspace `copilotInfo` reflects, not on `$workspaceStore`,
|
||||
which is ahead of it while a switch loads: pricing usage from one
|
||||
workspace with another's rates would silently misstate it. -->
|
||||
{#if $copilotWorkspace}
|
||||
<AiUsagePanel
|
||||
workspace={$copilotWorkspace}
|
||||
modelPricing={$copilotInfo.modelPricing ?? {}}
|
||||
scope="self"
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
{#if showMcpMode}
|
||||
<div bind:this={mcpSection} class="flex flex-col p-4 border border-border-light rounded-md">
|
||||
<h2 class="text-emphasis text-sm font-semibold mb-1">
|
||||
Build and run from your AI client
|
||||
</h2>
|
||||
<div class="text-xs text-secondary mb-2">
|
||||
Connect Claude, ChatGPT or Cursor to Windmill over MCP: build scripts, flows and apps,
|
||||
run your automations and check their runs, from your chat.
|
||||
</div>
|
||||
<CreateToken mcpOnly onTokenCreated={() => tokensTable?.listTokens()} />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="grow min-h-0">
|
||||
<TokensTable
|
||||
bind:this={tokensTable}
|
||||
defaultNewTokenLabel={newTokenLabel}
|
||||
defaultNewTokenWorkspace={newTokenWorkspace}
|
||||
{scopes}
|
||||
onTokenCreated={handleTokenCreated}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
@@ -1,12 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { workspaceStore, userWorkspaces } from '$lib/stores'
|
||||
import { workspaceIsFork } from '$lib/utils/workspaceHierarchy'
|
||||
import { Badge, Button } from './common'
|
||||
import { Badge } from './common'
|
||||
import { Pencil } from 'lucide-svelte'
|
||||
import { useWorkspaceDrafts } from '$lib/workspaceDrafts.svelte'
|
||||
import PageHeaderContent from '$lib/components/PageHeaderContent.svelte'
|
||||
import { pageHeader, PHONE_BAR } from '$lib/components/pageHeaderRegistry.svelte'
|
||||
import { onDestroy } from 'svelte'
|
||||
import { homeActionsGathered, homeHeaderMenu } from './home/homeHeaderMenu.svelte'
|
||||
import {
|
||||
homeActionsGathered,
|
||||
homeCountLabels,
|
||||
homeHeaderMenu
|
||||
} from './home/homeHeaderMenu.svelte'
|
||||
|
||||
// Surfaces pending drafts (scripts/flows/apps) for the current workspace and
|
||||
// links to the compare page in draft mode. Mutually exclusive with
|
||||
@@ -43,32 +48,19 @@
|
||||
|
||||
{#if !isFork && draftCount > 0 && !homeActionsGathered()}
|
||||
<!-- In the band rather than a banner over the page: it is a standing fact about the workspace,
|
||||
not an interruption, and one button says it and acts on it. -->
|
||||
not an interruption, and one badge says it and acts on it. -->
|
||||
<PageHeaderContent actions={draftsAction} actionsOrder={-100} />
|
||||
{/if}
|
||||
|
||||
{#snippet draftsAction()}
|
||||
<!-- On a phone the badge becomes the button: the count is the part that has to be seen, and
|
||||
the bar has room for one thing. -->
|
||||
{#if phone}
|
||||
<Button
|
||||
btnClasses="wm-page-in"
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
href={draftCompareHref}
|
||||
title="Review & deploy drafts"
|
||||
>
|
||||
<Badge color="blue" small>{draftCount}</Badge>
|
||||
</Button>
|
||||
{:else}
|
||||
<!-- Fades in: the count lands after the bar it joins has already painted. -->
|
||||
<span class="flex items-center gap-2 wm-page-in">
|
||||
<Badge color="blue" small>
|
||||
{draftCount} draft{draftCount !== 1 ? 's' : ''}
|
||||
</Badge>
|
||||
<Button variant="subtle" unifiedSize="sm" href={draftCompareHref}>
|
||||
Review & deploy drafts
|
||||
</Button>
|
||||
</span>
|
||||
{/if}
|
||||
<!-- The same badge a fork shows for its drafts. Fades in: the count lands after the bar it joins
|
||||
has already painted. -->
|
||||
{@const label = `Review and deploy ${draftCount} draft${draftCount !== 1 ? 's' : ''}`}
|
||||
<span class="flex items-center wm-page-in">
|
||||
<!-- Named in full: in compact widths its text is a bare number. -->
|
||||
<Badge color="blue" small clickable href={draftCompareHref} title={label} aria-label={label}>
|
||||
<Pencil class="w-3 h-3 inline" />
|
||||
{draftCount}{phone || !homeCountLabels() ? '' : ` draft${draftCount !== 1 ? 's' : ''}`}
|
||||
</Badge>
|
||||
</span>
|
||||
{/snippet}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<!--
|
||||
@component
|
||||
The account settings drawers, one per concern, opened by `#user-settings[-<panel>]`.
|
||||
At most one is open: opening another closes the current one without clearing the hash.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import {
|
||||
parseAccountSettingsHash,
|
||||
type AccountSettingsPanel
|
||||
} from '$lib/components/sidebar/settings'
|
||||
import ProfileDrawer from './ProfileDrawer.svelte'
|
||||
import TokensDrawer from './TokensDrawer.svelte'
|
||||
import AiSettingsDrawer from './AiSettingsDrawer.svelte'
|
||||
import McpDrawer from './McpDrawer.svelte'
|
||||
|
||||
let active = $state<AccountSettingsPanel | undefined>(undefined)
|
||||
|
||||
export function open(panel: AccountSettingsPanel) {
|
||||
active = panel
|
||||
}
|
||||
|
||||
export function openFromHash(hash: string) {
|
||||
const panel = parseAccountSettingsHash(hash)
|
||||
if (panel) active = panel
|
||||
}
|
||||
|
||||
function binding(panel: AccountSettingsPanel) {
|
||||
return {
|
||||
get: () => active === panel,
|
||||
set: (value: boolean) => {
|
||||
if (value) {
|
||||
active = panel
|
||||
} else if (active === panel) {
|
||||
active = undefined
|
||||
if (parseAccountSettingsHash(window.location.hash)) window.location.hash = ''
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const profile = binding('profile')
|
||||
const tokens = binding('tokens')
|
||||
const ai = binding('ai')
|
||||
const mcp = binding('mcp')
|
||||
</script>
|
||||
|
||||
<ProfileDrawer bind:open={profile.get, profile.set} />
|
||||
<TokensDrawer bind:open={tokens.get, tokens.set} />
|
||||
<AiSettingsDrawer bind:open={ai.get, ai.set} />
|
||||
<McpDrawer bind:open={mcp.get, mcp.set} />
|
||||
@@ -0,0 +1,32 @@
|
||||
<script lang="ts">
|
||||
import { Drawer, DrawerContent } from '$lib/components/common'
|
||||
import AIUserSettings from '$lib/components/settings/AIUserSettings.svelte'
|
||||
import AiUsagePanel from '$lib/components/workspaceSettings/AiUsagePanel.svelte'
|
||||
import { copilotInfo, copilotWorkspace } from '$lib/aiStore'
|
||||
import { accountSettingsHref } from '$lib/components/sidebar/settings'
|
||||
|
||||
let { open = $bindable() }: { open?: boolean } = $props()
|
||||
</script>
|
||||
|
||||
<Drawer bind:open size="800px">
|
||||
<DrawerContent title="AI settings" on:close={() => (open = false)}>
|
||||
<div class="flex flex-col gap-6 pb-8">
|
||||
<div class="text-xs text-secondary">
|
||||
To use Windmill from Claude, ChatGPT or Cursor, see
|
||||
<a href={accountSettingsHref('mcp')}>Connect an AI client</a>.
|
||||
</div>
|
||||
<AIUserSettings />
|
||||
<!-- Keyed on the workspace `copilotInfo` reflects, not on `$workspaceStore`:
|
||||
a session acting on another workspace loads that workspace's AI config
|
||||
while navigation stays put, and pricing usage from one workspace with
|
||||
another's rates would silently misstate it. -->
|
||||
{#if $copilotWorkspace}
|
||||
<AiUsagePanel
|
||||
workspace={$copilotWorkspace}
|
||||
modelPricing={$copilotInfo.modelPricing ?? {}}
|
||||
scope="self"
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
@@ -0,0 +1,31 @@
|
||||
<script lang="ts">
|
||||
import { Drawer, DrawerContent } from '$lib/components/common'
|
||||
import CreateToken from '$lib/components/settings/CreateToken.svelte'
|
||||
import { accountSettingsHref } from '$lib/components/sidebar/settings'
|
||||
|
||||
let { open = $bindable() }: { open?: boolean } = $props()
|
||||
</script>
|
||||
|
||||
<Drawer bind:open size="800px">
|
||||
<DrawerContent
|
||||
title="Connect an AI client"
|
||||
documentationLink="https://www.windmill.dev/docs/core_concepts/mcp"
|
||||
on:close={() => (open = false)}
|
||||
>
|
||||
<div class="flex flex-col gap-2 pb-8">
|
||||
<div class="text-xs text-secondary mb-2">
|
||||
Connect Claude, ChatGPT or Cursor to Windmill over MCP: build scripts, flows and apps, run
|
||||
your automations and check their runs, from your chat.
|
||||
</div>
|
||||
<CreateToken mcpOnly onTokenCreated={() => {}} />
|
||||
<div class="text-xs text-secondary">
|
||||
Tokens you create here are listed, and can be revoked, in
|
||||
<a href={accountSettingsHref('tokens')}>Tokens</a>.
|
||||
</div>
|
||||
<div class="text-xs text-secondary">
|
||||
Windmill's own AI assistant is configured in
|
||||
<a href={accountSettingsHref('ai')}>AI settings</a>.
|
||||
</div>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
@@ -0,0 +1,63 @@
|
||||
<script lang="ts">
|
||||
import { Drawer, DrawerContent, ListRow } from '$lib/components/common'
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import DarkModeToggle from '$lib/components/sidebar/DarkModeToggle.svelte'
|
||||
import Version from '$lib/components/Version.svelte'
|
||||
import UserInfoSettings from '$lib/components/settings/UserInfoSettings.svelte'
|
||||
import {
|
||||
getDarkModeVariant,
|
||||
setDarkModeVariant,
|
||||
type DarkModeVariant
|
||||
} from '$lib/darkModeVariant'
|
||||
import { ACCOUNT_SETTINGS_LINKS } from './accountSettingsLinks'
|
||||
|
||||
let { open = $bindable() }: { open?: boolean } = $props()
|
||||
|
||||
let darkVariant = $state<DarkModeVariant>(getDarkModeVariant())
|
||||
|
||||
const otherLinks = ACCOUNT_SETTINGS_LINKS.filter((l) => l.panel !== 'profile')
|
||||
</script>
|
||||
|
||||
<Drawer bind:open size="600px" on:open={() => (darkVariant = getDarkModeVariant())}>
|
||||
<DrawerContent title="Profile" on:close={() => (open = false)}>
|
||||
<div class="flex flex-col gap-6 pb-8">
|
||||
<UserInfoSettings />
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="text-xs text-emphasis font-semibold flex items-center">
|
||||
Theme <DarkModeToggle forcedDarkMode={false} />
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-xs text-secondary">Dark variant</span>
|
||||
<ToggleButtonGroup
|
||||
selected={darkVariant}
|
||||
class="w-fit"
|
||||
onSelected={(v) => {
|
||||
darkVariant = v
|
||||
setDarkModeVariant(v)
|
||||
}}
|
||||
>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton value="default" label="Default" size="sm" {item} />
|
||||
<ToggleButton value="github" label="GitHub" size="sm" {item} />
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-1">
|
||||
<h2 class="text-emphasis text-sm font-semibold mb-1">More account settings</h2>
|
||||
{#each otherLinks as link (link.panel)}
|
||||
<ListRow onClick={() => (window.location.hash = link.href)}>
|
||||
{#snippet icon()}<link.icon size={16} />{/snippet}
|
||||
{#snippet title()}{link.label}{/snippet}
|
||||
{#snippet subtitle()}{link.description}{/snippet}
|
||||
</ListRow>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-1 text-xs text-secondary">Windmill <Version /></div>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
@@ -0,0 +1,47 @@
|
||||
<script lang="ts">
|
||||
import { Drawer, DrawerContent } from '$lib/components/common'
|
||||
import TokensTable from '$lib/components/settings/TokensTable.svelte'
|
||||
|
||||
interface Props {
|
||||
open?: boolean
|
||||
/** Given, the drawer mints a token restricted to these scopes, for the caller to use. */
|
||||
scopes?: string[]
|
||||
newTokenLabel?: string
|
||||
newTokenWorkspace?: string
|
||||
newToken?: string
|
||||
onTokenCreated?: (token: string) => void
|
||||
}
|
||||
|
||||
let {
|
||||
open = $bindable(),
|
||||
scopes = undefined,
|
||||
newTokenLabel = undefined,
|
||||
newTokenWorkspace = undefined,
|
||||
newToken = $bindable(undefined),
|
||||
onTokenCreated
|
||||
}: Props = $props()
|
||||
|
||||
export function openDrawer() {
|
||||
open = true
|
||||
}
|
||||
|
||||
export function closeDrawer() {
|
||||
open = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<Drawer bind:open size="900px">
|
||||
<DrawerContent title="Tokens" on:close={closeDrawer}>
|
||||
<div class="pb-8">
|
||||
<TokensTable
|
||||
defaultNewTokenLabel={newTokenLabel}
|
||||
defaultNewTokenWorkspace={newTokenWorkspace}
|
||||
{scopes}
|
||||
onTokenCreated={(token) => {
|
||||
newToken = token
|
||||
onTokenCreated?.(token)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
@@ -0,0 +1,27 @@
|
||||
import { KeyRound, Plug, Sparkles, UserCog } from 'lucide-svelte'
|
||||
import { accountSettingsHref, type AccountSettingsPanel } from '$lib/components/sidebar/settings'
|
||||
|
||||
export type AccountSettingsLink = {
|
||||
panel: AccountSettingsPanel
|
||||
label: string
|
||||
description: string
|
||||
href: string
|
||||
icon: typeof UserCog
|
||||
}
|
||||
|
||||
function link(
|
||||
panel: AccountSettingsPanel,
|
||||
label: string,
|
||||
description: string,
|
||||
icon: typeof UserCog
|
||||
): AccountSettingsLink {
|
||||
return { panel, label, description, href: accountSettingsHref(panel), icon }
|
||||
}
|
||||
|
||||
/** The account settings drawers, in the order every menu lists them. */
|
||||
export const ACCOUNT_SETTINGS_LINKS: AccountSettingsLink[] = [
|
||||
link('profile', 'Profile', 'Email, password and theme', UserCog),
|
||||
link('tokens', 'Tokens', 'Personal access tokens for the API and the CLI', KeyRound),
|
||||
link('ai', 'AI settings', 'Completions, custom prompts and your AI usage', Sparkles),
|
||||
link('mcp', 'Connect an AI client', 'Use Windmill from Claude, ChatGPT or Cursor over MCP', Plug)
|
||||
]
|
||||
@@ -205,7 +205,10 @@
|
||||
>
|
||||
<span class="text-2xs font-normal text-secondary">
|
||||
{#if status === 'pending' && approvalInfo.approvers.length > 0}
|
||||
Already approved by {approvalInfo.approvers.map((a) => a.approver).join(', ')}
|
||||
{approvalInfo.required_events
|
||||
? `${approvalInfo.approvers.length} of ${approvalInfo.required_events} approvals:`
|
||||
: 'Already approved by'}
|
||||
{approvalInfo.approvers.map((a) => a.approver).join(', ')}
|
||||
{/if}
|
||||
</span>
|
||||
{#if isWorkspaceMember}
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
init(wasmUrl)
|
||||
|
||||
import { argSigToJsonSchemaType } from 'windmill-utils-internal'
|
||||
import { argSigToJsonSchemaType } from 'windmill-utils-internal/parse/parse-schema'
|
||||
import SchemaForm from '$lib/components/SchemaForm.svelte'
|
||||
import { untrack } from 'svelte'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
|
||||
@@ -69,8 +69,9 @@
|
||||
function handleDefault(defaultValue: string | undefined) {
|
||||
value = defaultValue
|
||||
|
||||
if (value) {
|
||||
const date = parseISO(value)
|
||||
const date = value ? parseISO(value) : undefined
|
||||
// A default that is not a date yet (one being typed in a linked input) leaves the selects as they are.
|
||||
if (date && !isNaN(date.getTime())) {
|
||||
const locale = getLocale(resolvedConfig.locale)
|
||||
selectedDay = String(date.getDate())
|
||||
selectedMonth = formatDateFns(date, 'MMMM', { locale })
|
||||
@@ -198,7 +199,7 @@
|
||||
}
|
||||
$effect.pre(() => {
|
||||
resolvedConfig.defaultValue
|
||||
untrack(() => !value && handleDefault(resolvedConfig.defaultValue))
|
||||
untrack(() => handleDefault(resolvedConfig.defaultValue))
|
||||
})
|
||||
let monthItems = $derived(computeMonthItems(resolvedConfig?.locale))
|
||||
$effect.pre(() => {
|
||||
|
||||
@@ -115,6 +115,7 @@
|
||||
const r = formatDate(value, resolvedConfig.outputFormat)
|
||||
outputs?.result.set(r)
|
||||
const valueDate = new Date(value)
|
||||
let isValid = true
|
||||
|
||||
if (resolvedConfig.minDateTime) {
|
||||
const minDate = new Date(resolvedConfig.minDateTime)
|
||||
@@ -123,11 +124,11 @@
|
||||
minDate.getMonth() === valueDate.getMonth() &&
|
||||
minDate.getFullYear() === valueDate.getFullYear()
|
||||
) {
|
||||
outputs?.validity.set(minDate.getTime() < valueDate.getTime())
|
||||
isValid &&= minDate.getTime() < valueDate.getTime()
|
||||
}
|
||||
|
||||
if (minDate.getTime() > valueDate.getTime()) {
|
||||
outputs?.validity.set(false)
|
||||
isValid = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,13 +140,14 @@
|
||||
maxDate.getMonth() === valueDate.getMonth() &&
|
||||
maxDate.getFullYear() === valueDate.getFullYear()
|
||||
) {
|
||||
outputs?.validity.set(maxDate.getTime() > valueDate.getTime())
|
||||
isValid &&= maxDate.getTime() > valueDate.getTime()
|
||||
}
|
||||
|
||||
if (maxDate.getTime() < valueDate.getTime()) {
|
||||
outputs?.validity.set(false)
|
||||
isValid = false
|
||||
}
|
||||
}
|
||||
outputs?.validity.set(isValid)
|
||||
untrack(() => setIterValue(value))
|
||||
} else {
|
||||
outputs?.result.set(undefined)
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
let css = $state(initCss($app.css?.timeinputcomponent, untrack(() => customCss)))
|
||||
$effect.pre(() => {
|
||||
resolvedConfig.defaultValue
|
||||
!value && untrack(() => handleDefault(resolvedConfig.defaultValue))
|
||||
untrack(() => handleDefault(resolvedConfig.defaultValue))
|
||||
})
|
||||
$effect.pre(() => {
|
||||
if (value) {
|
||||
@@ -102,6 +102,9 @@
|
||||
|
||||
// At the end, set the validity
|
||||
outputs?.validity.set(isValid)
|
||||
} else {
|
||||
outputs?.result.set(undefined)
|
||||
outputs?.validity.set(true)
|
||||
}
|
||||
fireOnChange()
|
||||
})
|
||||
|
||||
@@ -108,7 +108,9 @@
|
||||
{:else}
|
||||
<Alert type="warning" title="Not isolated" size="xs">
|
||||
The app's frontend code runs with each viewer's full Windmill permissions. A future version
|
||||
will ask viewers to approve this. Keep isolation off only if the app needs it.
|
||||
will ask viewers to approve this. Keep isolation off only if the app needs it. Viewers who are
|
||||
not members of this workspace (public link, guests, other workspaces) always get the isolated
|
||||
render, whatever this setting says. Test a public app from a private window.
|
||||
</Alert>
|
||||
{/if}
|
||||
{/snippet}
|
||||
@@ -232,7 +234,7 @@
|
||||
<SettingToggle
|
||||
setting="sandbox"
|
||||
label="Sandbox isolation"
|
||||
tooltip="Controls what the app's browser-side code can reach in each viewer's browser, separately from who its runnables run as. A sandboxed app gets a narrowly scoped token on every surface, public URL and in-workspace. On by default for new apps. Turn it off only if the app needs IndexedDB, third-party sign-in or OAuth redirects."
|
||||
tooltip="Controls what the app's browser-side code can reach in each viewer's browser, separately from who its runnables run as. A sandboxed app gets a narrowly scoped token on every surface, public URL and in-workspace. On by default for new apps. Turn it off only if the app needs IndexedDB, third-party sign-in or OAuth redirects. Viewers who are not members of this workspace (public link, guests, other workspaces) always get the isolated render, whatever this setting says."
|
||||
checked={composeOnlyApps || policy.sandbox == true}
|
||||
disabled={composeOnlyApps}
|
||||
hint={composeOnlyApps || policy.sandbox != true ? sandboxHint : undefined}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
* scoped embed token / opaque isolation.
|
||||
*/
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { encodePathParam } from '$lib/apiPathParams'
|
||||
import PublicApp from '$lib/components/apps/editor/PublicApp.svelte'
|
||||
import PublicAppFrame from '$lib/components/apps/editor/PublicAppFrame.svelte'
|
||||
import PageHeaderContent from '$lib/components/PageHeaderContent.svelte'
|
||||
@@ -124,9 +125,8 @@
|
||||
headers['Authorization'] = `Bearer ${OpenAPI.TOKEN}`
|
||||
}
|
||||
const consent = opts?.sdkConsent ? '?sdk_consent=true' : ''
|
||||
const res = await fetch(`${OpenAPI.BASE}/w/${workspace}/apps/embed_token/p/${path}${consent}`, {
|
||||
headers
|
||||
})
|
||||
const url = `${OpenAPI.BASE}/w/${encodePathParam('workspace', workspace)}/apps/embed_token/p/${encodePathParam('path', path)}${consent}`
|
||||
const res = await fetch(url, { headers })
|
||||
if (!res.ok) {
|
||||
// Minted for the deployed app under the caller's RLS: a 404 is "nothing deployed here" or
|
||||
// "not visible to this member", the same reading as `getAppLiteByPath`'s 404 below.
|
||||
|
||||
@@ -14,8 +14,10 @@
|
||||
* - Raw, sandboxed: rendered directly here as a **single** opaque bundle iframe
|
||||
* (the author bundle is already isolated in its own opaque iframe); no opaque
|
||||
* viewer / embed token needed.
|
||||
* - Unsandboxed (default): the app runs same-origin with the viewer's full
|
||||
* session, the pre-isolation behavior. Rendered directly here.
|
||||
* - Unsandboxed: the app runs same-origin with the viewer's full session.
|
||||
* Rendered directly here. Only for a member of the app's workspace viewing an
|
||||
* app its publisher left unsandboxed; the embed-token response decides it, and
|
||||
* anyone else gets one of the isolated renders above.
|
||||
*
|
||||
* No `PUBLIC_APP_DOMAIN` is required: the opaque origin is, for same-origin-policy
|
||||
* purposes, as foreign to the main app as a different domain. The opaque viewer's
|
||||
@@ -28,6 +30,7 @@
|
||||
import { onDestroy, onMount, setContext, type Snippet } from 'svelte'
|
||||
import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte'
|
||||
import { goto } from '$app/navigation'
|
||||
import { parseHttpUrl, toSameOriginRelativePath } from '$lib/navigationTarget'
|
||||
import { WINDMILL_RESERVED_QUERY_PARAMS } from '$lib/utils/queryParams'
|
||||
import { EMBED_NAV_CONTEXT_KEY, type EmbedNav } from '../types'
|
||||
import { loadAppPreview } from './loadAppPreview'
|
||||
@@ -316,10 +319,11 @@
|
||||
let modeChangeRestarts = 0
|
||||
const MAX_MODE_CHANGE_RESTARTS = 3
|
||||
|
||||
// WIN-2006: publisher opted this app into sandbox isolation (alpha). When false
|
||||
// (the default) the app runs same-origin with the viewer's full session — the
|
||||
// pre-isolation behavior.
|
||||
let sandboxed = $state(false)
|
||||
// Whether the server says this viewer gets the isolated render (the publisher
|
||||
// opted in, or the viewer is not a member of the app's workspace). Read only from
|
||||
// the embed-token response, and a response without it counts as isolated: the
|
||||
// app's own policy must never decide this on the client.
|
||||
let sandboxed = $state(true)
|
||||
|
||||
// WIN-2006 Variant A: raw apps render single-iframe. The author's bundle is
|
||||
// already isolated in its own opaque iframe (served + CSP-sandboxed by the
|
||||
@@ -371,7 +375,7 @@
|
||||
try {
|
||||
const resp = await fetchEmbedToken()
|
||||
embedToken = resp.token ?? null
|
||||
sandboxed = resp.sandbox ?? false
|
||||
sandboxed = resp.sandbox !== false
|
||||
isRaw = resp.raw_app ?? false
|
||||
appPath = resp.app_path ?? undefined
|
||||
workspaceId = resp.workspace_id ?? undefined
|
||||
@@ -416,7 +420,7 @@
|
||||
// response's mode would bypass new isolation or leave the viewer
|
||||
// unauthenticated. Start over; bounded so redeploys can't bounce forever.
|
||||
const modeChanged =
|
||||
(resp.raw_app ?? false) !== wasRaw || (resp.sandbox ?? false) !== wasSandboxed
|
||||
(resp.raw_app ?? false) !== wasRaw || (resp.sandbox !== false) !== wasSandboxed
|
||||
if (modeChanged) {
|
||||
if (modeChangeRestarts < MAX_MODE_CHANGE_RESTARTS) {
|
||||
modeChangeRestarts++
|
||||
@@ -428,7 +432,7 @@
|
||||
status = 'notExists'
|
||||
return false
|
||||
}
|
||||
sandboxed = resp.sandbox ?? false
|
||||
sandboxed = resp.sandbox !== false
|
||||
isRaw = resp.raw_app ?? false
|
||||
appPath = resp.app_path ?? appPath
|
||||
workspaceId = resp.workspace_id ?? workspaceId
|
||||
@@ -568,12 +572,16 @@
|
||||
// the app ran on it pre-sandbox. Same-origin paths use SPA navigation;
|
||||
// full http(s) URLs do a real load (pre-sandbox apps could already do
|
||||
// this via window.location, so it grants nothing new). Everything else —
|
||||
// javascript:, data:, protocol-relative `//host` — is rejected.
|
||||
// javascript:, data:, protocol-relative `//host`, and this instance's own
|
||||
// `/api/` routes, which this page would reach as a same-origin request — is
|
||||
// rejected.
|
||||
const href = typeof e.data.href === 'string' ? e.data.href : ''
|
||||
if (href.startsWith('/') && !href.startsWith('//')) {
|
||||
goto(href)
|
||||
if (href.startsWith('/')) {
|
||||
const path = toSameOriginRelativePath(href)
|
||||
if (path) goto(path)
|
||||
} else if (/^https?:\/\//i.test(href)) {
|
||||
window.location.href = href
|
||||
const url = parseHttpUrl(href)
|
||||
if (url) window.location.href = url.href
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ export async function getS3File({
|
||||
|
||||
// Editor/preview runs execute as the *caller* (Viewer mode), so read their
|
||||
// results back as the caller through the viewer-scoped `job_helpers` endpoint —
|
||||
// never author-mode — consistent with DisplayResult/ParqetCsvTableRenderer. Only
|
||||
// never author-mode — consistent with DisplayResult. Only
|
||||
// a deployed app view reads on-behalf of the author via the provenance-gated
|
||||
// `apps_u` endpoint.
|
||||
if (isEditor) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { OpenAPI } from '$lib/gen/core/OpenAPI'
|
||||
import type { AppWithLastVersion, User } from '$lib/gen/types.gen'
|
||||
import type { UserExt } from '$lib/stores'
|
||||
import { mapUserToUserExt } from '$lib/userExt'
|
||||
import { encodePathParam } from '$lib/apiPathParams'
|
||||
|
||||
export type PublicAppValue = AppWithLastVersion & { value: any; workspace_id?: string }
|
||||
|
||||
@@ -57,7 +58,7 @@ export async function publicGet<T>(path: string): Promise<T> {
|
||||
export async function getUserExtOrUndefined(workspace: string): Promise<UserExt | undefined> {
|
||||
try {
|
||||
return mapUserToUserExt(
|
||||
await publicGet<User>(`/w/${encodeURI(workspace)}/users/whoami`),
|
||||
await publicGet<User>(`/w/${encodePathParam('workspace', workspace)}/users/whoami`),
|
||||
workspace
|
||||
)
|
||||
} catch {
|
||||
|
||||
@@ -62,6 +62,30 @@
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if log.client_ip}
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="font-semibold text-xs text-emphasis">Client IP</span>
|
||||
<span class="text-xs break-all">{log.client_ip}</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if log.peer_ip}
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="font-semibold text-xs text-emphasis">Forwarded by</span>
|
||||
<span class="text-xs break-all">{log.peer_ip}</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if log.forwarded_for}
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="font-semibold text-xs text-emphasis">Forwarding header</span>
|
||||
<span class="text-xs break-all font-mono">{log.forwarded_for}</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if log.user_agent}
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="font-semibold text-xs text-emphasis">User agent</span>
|
||||
<span class="text-xs break-all">{log.user_agent}</span>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="font-semibold text-xs text-emphasis">Parameters</span>
|
||||
<div class="text-xs p-2 bg-surface-secondary rounded-md overflow-x-auto">
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import 'chart.js/auto'
|
||||
import 'chartjs-adapter-date-fns'
|
||||
import { untrack } from 'svelte'
|
||||
import { clone } from '$lib/utils'
|
||||
|
||||
interface Props extends HTMLCanvasAttributes {
|
||||
type: T
|
||||
@@ -28,7 +29,7 @@
|
||||
chart = new Chart(canvasElem, {
|
||||
type,
|
||||
data: $state.snapshot(data) as typeof data,
|
||||
options: $state.snapshot(options) as typeof options
|
||||
options: clone(options)
|
||||
})
|
||||
})
|
||||
return () => {
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
<script lang="ts">
|
||||
import { ChevronDown, Download, Loader2 } from 'lucide-svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import Select from '$lib/components/select/Select.svelte'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import type { IDbTableOps } from '$lib/components/dbOps'
|
||||
import { s3TableOps, serverTableFormat } from '$lib/components/s3TableOps'
|
||||
import {
|
||||
setOperatingWorkspace,
|
||||
useOperatingWorkspace
|
||||
} from '$lib/components/operatingWorkspace.svelte'
|
||||
import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile'
|
||||
|
||||
interface Props {
|
||||
s3object: { s3: string; storage?: string; presigned?: string; disable_download?: boolean }
|
||||
workspaceId?: string | undefined
|
||||
/** Set in a deployed app: the file is read through the app-scoped `apps_u/*` routes. */
|
||||
appPath?: string | undefined
|
||||
}
|
||||
|
||||
let { s3object, workspaceId = undefined, appPath = undefined }: Props = $props()
|
||||
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
// DBTable loads no rows without an operating workspace, and a public app sets none.
|
||||
setOperatingWorkspace(() => workspaceId)
|
||||
|
||||
const CSV_SEPARATORS = [
|
||||
{ value: ',', label: ',' },
|
||||
{ value: ';', label: ';' },
|
||||
{ value: '\t', label: 'Tab' },
|
||||
{ value: '|', label: '|' }
|
||||
]
|
||||
// DBTable's search bar, header row and body rows, in px.
|
||||
const TOOLBAR_HEIGHT = 40
|
||||
// Below about this width the toolbar wraps the row count and buttons under the search bar.
|
||||
const TOOLBAR_WRAP_WIDTH = 480
|
||||
const HEADER_HEIGHT = 30
|
||||
const ROW_HEIGHT = 34
|
||||
const SCROLLBAR = 12
|
||||
|
||||
let separator: string | undefined = $state(undefined)
|
||||
let hasHeader = $state(true)
|
||||
/** The separator the server guessed while none is picked. */
|
||||
let detectedSeparator: string | undefined = $state(undefined)
|
||||
/** Rows in the whole file, kept while a search narrows them so the table keeps its height. */
|
||||
let totalRows: number | undefined = $state(undefined)
|
||||
let width = $state(0)
|
||||
|
||||
// JSON lines are read through the CSV route too, but have no separator or header row.
|
||||
let isCsv = $derived(/\.(csv|tsv)$/i.test(s3object.s3))
|
||||
let isParquet = $derived(serverTableFormat(s3object.s3) === 'parquet')
|
||||
let workspace = $derived(workspaceId ?? $operatingWorkspace!)
|
||||
// The server converts the whole file; the table's own export only has the rows it loaded.
|
||||
let parquetCsvPath = $derived(
|
||||
appPath
|
||||
? `/w/${workspace}/apps_u/download_s3_parquet_file_as_csv/${appPath}?file_key=${encodeURIComponent(s3object.s3)}${s3object.storage ? `&storage=${s3object.storage}` : ''}${s3object.presigned ? `&${s3object.presigned}` : ''}`
|
||||
: `/w/${workspace}/job_helpers/download_s3_parquet_file_as_csv?file_key=${encodeURIComponent(s3object.s3)}${s3object.storage ? `&storage=${s3object.storage}` : ''}`
|
||||
)
|
||||
let parquetCsvName = $derived((s3object.s3.split('/').pop() ?? 'download') + '.csv')
|
||||
|
||||
let height = $derived(
|
||||
totalRows === undefined
|
||||
? 240
|
||||
: Math.min(
|
||||
600,
|
||||
Math.max(
|
||||
180,
|
||||
(width && width < TOOLBAR_WRAP_WIDTH ? 2 : 1) * TOOLBAR_HEIGHT +
|
||||
HEADER_HEIGHT +
|
||||
totalRows * ROW_HEIGHT +
|
||||
SCROLLBAR
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
function recordingTotal(ops: IDbTableOps, source: Promise<unknown>): IDbTableOps {
|
||||
return {
|
||||
...ops,
|
||||
getCount: async (params) => {
|
||||
const n = await ops.getCount(params)
|
||||
const filtered = !!params.quicksearch || Object.keys(params.columnFilters ?? {}).length > 0
|
||||
// A count from a table the separator, header row or file replaced is not this one's.
|
||||
if (!filtered && table === source) totalRows = n
|
||||
return n
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Lazy: DBTable reaches Monaco, and every page that shows a job result imports this table.
|
||||
const dbTable = import('$lib/components/DBTable.svelte')
|
||||
|
||||
let table = $derived.by(() => {
|
||||
const pending = s3TableOps({
|
||||
workspace,
|
||||
fileKey: s3object.s3,
|
||||
storage: s3object.storage,
|
||||
csvSeparator: separator,
|
||||
csvHasHeader: hasHeader,
|
||||
app: appPath ? { path: appPath, presigned: s3object.presigned } : undefined
|
||||
}).then((t) => {
|
||||
// A table superseded while loading must not label the current one.
|
||||
if (table !== pending) return t as never
|
||||
detectedSeparator = t.csvSeparator
|
||||
return dbTable.then((m) => ({
|
||||
...t,
|
||||
ops: recordingTotal(t.ops, pending),
|
||||
DBTable: m.default
|
||||
}))
|
||||
})
|
||||
return pending
|
||||
})
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-1 mt-2">
|
||||
{#if isCsv || (isParquet && !s3object.disable_download)}
|
||||
<div class="flex items-center justify-end gap-4 text-xs text-secondary">
|
||||
{#if isCsv}
|
||||
<div class="flex items-center gap-2">
|
||||
<span>Separator</span>
|
||||
<Select
|
||||
size="sm"
|
||||
class="w-20"
|
||||
clearable
|
||||
RightIcon={ChevronDown}
|
||||
items={CSV_SEPARATORS}
|
||||
bind:value={separator}
|
||||
placeholder={CSV_SEPARATORS.find((s) => s.value === detectedSeparator)?.label ?? 'Auto'}
|
||||
/>
|
||||
</div>
|
||||
<Toggle size="xs" bind:checked={hasHeader} options={{ right: 'Header row' }} />
|
||||
{:else if shouldDownloadViaClient()}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
startIcon={{ icon: Download }}
|
||||
onClick={() => downloadViaClient(parquetCsvPath, parquetCsvName)}
|
||||
>
|
||||
Download as CSV
|
||||
</Button>
|
||||
{:else}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="xs"
|
||||
startIcon={{ icon: Download }}
|
||||
href="/api{parquetCsvPath}"
|
||||
download={parquetCsvName}
|
||||
>
|
||||
Download as CSV
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div
|
||||
class="overflow-hidden border rounded-md"
|
||||
style="height: {height}px"
|
||||
bind:clientWidth={width}
|
||||
data-interactive
|
||||
>
|
||||
{#await table}
|
||||
<div class="flex h-full items-center justify-center gap-1 text-2xs text-secondary">
|
||||
<Loader2 size={12} class="animate-spin" /> Loading table
|
||||
</div>
|
||||
{:then t}
|
||||
<t.DBTable dbTableOps={t.ops} disableDownload={s3object.disable_download || isParquet} />
|
||||
{:catch e}
|
||||
{@const message = String(e?.body ?? e?.message ?? e)}
|
||||
<!-- The storage reports an empty file as a failed range read. -->
|
||||
{#if /Range started at 0 and ended at 0/.test(message)}
|
||||
<div class="p-3 text-xs text-secondary">This file is empty.</div>
|
||||
{:else}
|
||||
<div class="p-3 text-xs text-red-600 dark:text-red-400 break-words">
|
||||
Could not read this file as a table: {message}
|
||||
</div>
|
||||
{/if}
|
||||
{/await}
|
||||
</div>
|
||||
</div>
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
<script lang="ts">
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import Modal2 from '../modal/Modal2.svelte'
|
||||
import ImageViewer from './ImageViewer.svelte'
|
||||
|
||||
interface Props {
|
||||
/** Source of both the inline thumbnail and the expanded view. */
|
||||
@@ -25,9 +25,12 @@
|
||||
title?: string
|
||||
/** Classes for the inline thumbnail — sizing, border, radius. */
|
||||
class?: string
|
||||
/** Opens the image in a viewer elsewhere (a session's preview panel), offered as a
|
||||
* button in the expanded view. */
|
||||
onOpen?: () => void
|
||||
}
|
||||
|
||||
let { src, alt = '', title, class: className = '' }: Props = $props()
|
||||
let { src, alt = '', title, class: className = '', onOpen }: Props = $props()
|
||||
|
||||
let isOpen = $state(false)
|
||||
|
||||
@@ -69,13 +72,4 @@
|
||||
}}
|
||||
/>
|
||||
|
||||
<Modal2
|
||||
bind:isOpen
|
||||
title={title || alt || 'Image'}
|
||||
fixedHeight="adaptive"
|
||||
css={{ popup: { style: 'width: auto;' } }}
|
||||
>
|
||||
<!-- Capped, never stretched: the image keeps its natural size up to the
|
||||
viewport bound, so a small source gains room without turning blurry. -->
|
||||
<img {src} {alt} class="max-h-[75vh] max-w-[80vw] object-contain mx-auto" />
|
||||
</Modal2>
|
||||
<ImageViewer bind:isOpen {src} {alt} {title} onOpenInPreview={onOpen} />
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
<script lang="ts">
|
||||
import { Download, Grid2x2, Maximize, Moon, Sun } from 'lucide-svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import ZoomControl from './ZoomControl.svelte'
|
||||
import { useZoomPan } from './zoomPan.svelte'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import { useIsDarkMode } from '$lib/components/DarkModeObserver.svelte'
|
||||
|
||||
interface Props {
|
||||
src: string
|
||||
/** Shown in the header and used as the download's file name. */
|
||||
name: string
|
||||
/** Byte size, shown beside the dimensions when known. */
|
||||
bytes?: number
|
||||
}
|
||||
|
||||
let { src, name, bytes }: Props = $props()
|
||||
|
||||
type Backdrop = 'checker' | 'light' | 'dark'
|
||||
const BACKDROPS = {
|
||||
light: { label: 'Light', icon: Sun },
|
||||
dark: { label: 'Dark', icon: Moon },
|
||||
checker: { label: 'Checkerboard', icon: Grid2x2 }
|
||||
} as const
|
||||
|
||||
// Room kept around a fitted image so its edges stay visible against the backdrop.
|
||||
const view = useZoomPan({ margin: { x: 32, y: 32 } })
|
||||
// The source that failed, not a flag: a new `src` (the file fixed and re-read) must mount
|
||||
// the image again, and only the image's own load event could clear a flag.
|
||||
let failedSrc = $state<string>()
|
||||
const failed = $derived(failedSrc === src)
|
||||
// Until the viewer picks one, the backdrop is Windmill's own theme, and follows it.
|
||||
const isDark = useIsDarkMode()
|
||||
let chosenBackdrop = $state<Backdrop | undefined>(undefined)
|
||||
const backdrop = $derived<Backdrop>(chosenBackdrop ?? (isDark.val ? 'dark' : 'light'))
|
||||
// The cycle starts at the theme's own backdrop, so the first click swaps light and dark.
|
||||
const backdropCycle = $derived<Backdrop[]>(
|
||||
isDark.val ? ['dark', 'light', 'checker'] : ['light', 'dark', 'checker']
|
||||
)
|
||||
const nextBackdrop = $derived(
|
||||
backdropCycle[(backdropCycle.indexOf(backdrop) + 1) % backdropCycle.length]
|
||||
)
|
||||
function humanSize(n: number): string {
|
||||
if (n < 1024) return `${n} B`
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`
|
||||
return `${(n / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
// A 16px checkerboard, the usual stand-in for "transparent".
|
||||
const CHECKER_STYLE =
|
||||
'background-color:#ffffff;background-image:linear-gradient(45deg,#e5e7eb 25%,transparent 25%,transparent 75%,#e5e7eb 75%),linear-gradient(45deg,#e5e7eb 25%,transparent 25%,transparent 75%,#e5e7eb 75%);background-size:16px 16px;background-position:0 0,8px 8px'
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full min-h-0 bg-surface">
|
||||
<!-- The file name is the tab's label already; this bar carries what the tab cannot. -->
|
||||
<div
|
||||
class="flex flex-wrap items-center justify-between gap-x-2 gap-y-1 px-4 py-2 border-b border-border-light"
|
||||
>
|
||||
<span class="text-xs text-secondary whitespace-nowrap tabular-nums" title={name}>
|
||||
{#if view.natural}
|
||||
{view.natural.w} × {view.natural.h}{bytes !== undefined ? ` · ${humanSize(bytes)}` : ''}
|
||||
{/if}
|
||||
</span>
|
||||
<div class="flex flex-wrap items-center gap-1">
|
||||
<ZoomControl
|
||||
scale={view.natural ? view.scale : undefined}
|
||||
min={view.minScale}
|
||||
max={view.maxScale}
|
||||
onZoomOut={view.zoomOut}
|
||||
onZoomIn={view.zoomIn}
|
||||
onZoomTo={view.zoomToAnimated}
|
||||
/>
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
iconOnly
|
||||
startIcon={{ icon: Maximize }}
|
||||
title="Fit to panel (0)"
|
||||
disabled={!view.natural}
|
||||
onClick={view.fit}
|
||||
/>
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant={view.zoom === 1 ? 'default' : 'subtle'}
|
||||
title="Actual size (1)"
|
||||
disabled={!view.natural}
|
||||
onClick={view.actualSize}
|
||||
>
|
||||
1:1
|
||||
</Button>
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
iconOnly
|
||||
startIcon={{ icon: BACKDROPS[backdrop].icon }}
|
||||
title={`${BACKDROPS[backdrop].label} background, click for ${BACKDROPS[nextBackdrop].label.toLowerCase()}`}
|
||||
onClick={() => (chosenBackdrop = nextBackdrop)}
|
||||
/>
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
iconOnly
|
||||
startIcon={{ icon: Download }}
|
||||
title="Download"
|
||||
href={src}
|
||||
download={name}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- The viewport takes keys and the wheel itself: zoom follows the cursor, so it has to
|
||||
be the element under it. ARIA's `application` role is the one for a surface that
|
||||
handles its own pointer and keys, but Svelte does not count it as interactive. -->
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
|
||||
<div
|
||||
class={twMerge(
|
||||
'relative flex-1 min-h-0 overflow-hidden outline-none select-none touch-none',
|
||||
backdrop === 'light' && 'bg-white',
|
||||
// The dark theme's surface-secondary in either theme: the light theme holds it as `-inverse`.
|
||||
backdrop === 'dark' && (isDark.val ? 'bg-surface-secondary' : 'bg-surface-secondary-inverse'),
|
||||
view.pannable ? (view.panning ? 'cursor-grabbing' : 'cursor-grab') : 'cursor-default'
|
||||
)}
|
||||
style={backdrop === 'checker' ? CHECKER_STYLE : undefined}
|
||||
{@attach view.surface}
|
||||
tabindex="0"
|
||||
role="application"
|
||||
aria-roledescription="image viewer"
|
||||
aria-label={`${name}. Plus and minus zoom, 0 fits, 1 shows actual size.`}
|
||||
onkeydown={(e) => {
|
||||
if (view.handleKey(e)) e.preventDefault()
|
||||
}}
|
||||
>
|
||||
{#if failed}
|
||||
<div class="absolute inset-0 flex items-center justify-center p-4">
|
||||
<span class="rounded-md bg-surface px-3 py-2 text-xs text-secondary shadow-sm">
|
||||
This file could not be displayed as an image.
|
||||
</span>
|
||||
</div>
|
||||
{:else}
|
||||
<img
|
||||
{@attach view.image}
|
||||
{src}
|
||||
alt={name}
|
||||
draggable="false"
|
||||
onerror={() => (failedSrc = src)}
|
||||
class={view.imageClass}
|
||||
style={view.imageStyle}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,282 @@
|
||||
<script lang="ts">
|
||||
import Portal from '$lib/components/Portal.svelte'
|
||||
import { Copy, Download, ExternalLink, Maximize, PanelRight, X } from 'lucide-svelte'
|
||||
import ZoomControl from './ZoomControl.svelte'
|
||||
import { useZoomPan } from './zoomPan.svelte'
|
||||
import { fade } from 'svelte/transition'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import Button from '../button/Button.svelte'
|
||||
import Disposable from '../drawer/Disposable.svelte'
|
||||
import { overlayHostActive, overlayShown, setTopmostSurface } from '../overlayHost.svelte'
|
||||
|
||||
interface Props {
|
||||
src: string
|
||||
alt?: string
|
||||
/** Caption in the header; defaults to `alt`. Also names the downloaded file when it
|
||||
* ends in an extension (an S3 key, an attachment's file name). */
|
||||
title?: string
|
||||
isOpen: boolean
|
||||
/** Shows the image in a viewer elsewhere (a session's preview panel), closing this one. */
|
||||
onOpenInPreview?: () => void
|
||||
}
|
||||
|
||||
let { src, alt = '', title, isOpen = $bindable(), onOpenInPreview }: Props = $props()
|
||||
|
||||
const caption = $derived(title || alt || 'Image')
|
||||
|
||||
/** A plain click beside the image dismisses; one that ends a pan does not. */
|
||||
let dismissOnClick = false
|
||||
const view = useZoomPan({
|
||||
// The top bar overlays the stage, so a fitted image keeps clear of it.
|
||||
margin: { x: 48, y: 128 },
|
||||
onTap: (onImage) => (dismissOnClick = !onImage)
|
||||
})
|
||||
|
||||
let imgEl: HTMLImageElement | undefined = $state(undefined)
|
||||
let disposable: Disposable | undefined = $state(undefined)
|
||||
const hostActive = overlayHostActive()
|
||||
const shown = overlayShown()
|
||||
setTopmostSurface(() => disposable?.isTopmost() ?? true)
|
||||
|
||||
function onOpen() {
|
||||
// A bound `open` alone does not put the viewer on the disposable stack, and the stack
|
||||
// lifts it above the drawer or dialog it was opened from and gives Escape to the topmost.
|
||||
disposable?.openDrawer()
|
||||
view.reset()
|
||||
}
|
||||
|
||||
function close() {
|
||||
isOpen = false
|
||||
}
|
||||
|
||||
function onStageClick() {
|
||||
// Closed on `click`, not `pointerup`: outside-click guards elsewhere (the chat composer)
|
||||
// listen for this click and must still see the viewer open when it arrives.
|
||||
if (dismissOnClick) close()
|
||||
dismissOnClick = false
|
||||
}
|
||||
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (!isOpen || !hostActive() || !(disposable?.isTopmost() ?? true)) return
|
||||
if (view.handleKey(e)) e.preventDefault()
|
||||
}
|
||||
|
||||
const MIME_EXT: Record<string, string> = {
|
||||
'image/png': 'png',
|
||||
'image/jpeg': 'jpg',
|
||||
'image/gif': 'gif',
|
||||
'image/webp': 'webp',
|
||||
'image/svg+xml': 'svg',
|
||||
'image/avif': 'avif',
|
||||
'image/bmp': 'bmp'
|
||||
}
|
||||
|
||||
/** The caption names the file, but the bytes decide its extension: chat attachments keep
|
||||
* their original name after being re-encoded (`diagram.svg` holding PNG bytes). */
|
||||
function fileName(mime: string) {
|
||||
const base = caption.split(/[/\\]/).pop() ?? ''
|
||||
const named = base.match(/^(.+)\.([a-z0-9]{2,5})$/i)
|
||||
const ext = MIME_EXT[mime] ?? named?.[2] ?? 'png'
|
||||
return `${named?.[1] ?? 'image'}.${ext}`
|
||||
}
|
||||
|
||||
async function fetchBlob() {
|
||||
const res = await fetch(src)
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
||||
return res.blob()
|
||||
}
|
||||
|
||||
async function download() {
|
||||
try {
|
||||
const blob = await fetchBlob()
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = fileName(blob.type)
|
||||
a.click()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not download the image: ${e}`, true)
|
||||
}
|
||||
}
|
||||
|
||||
async function openInNewTab() {
|
||||
if (!src.startsWith('data:')) {
|
||||
window.open(src, '_blank', 'noopener')
|
||||
return
|
||||
}
|
||||
// Browsers refuse to open a data: URL as a page; a blob URL of the same bytes opens.
|
||||
// The blob URL takes this page's origin, so only plain raster types open as they are;
|
||||
// anything else, SVG included since it opens as a document, is re-encoded to PNG.
|
||||
try {
|
||||
const blob = await fetchBlob()
|
||||
const url = URL.createObjectURL(RASTER_TYPES.has(blob.type) ? blob : await rasterize())
|
||||
window.open(url, '_blank', 'noopener')
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000)
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not open the image: ${e}`, true)
|
||||
}
|
||||
}
|
||||
|
||||
const RASTER_TYPES = new Set([
|
||||
'image/png',
|
||||
'image/jpeg',
|
||||
'image/gif',
|
||||
'image/webp',
|
||||
'image/avif',
|
||||
'image/bmp'
|
||||
])
|
||||
|
||||
/** The displayed image as PNG bytes, drawn through a canvas. */
|
||||
function rasterize(): Promise<Blob> {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = view.natural?.w ?? imgEl!.naturalWidth
|
||||
canvas.height = view.natural?.h ?? imgEl!.naturalHeight
|
||||
canvas.getContext('2d')!.drawImage(imgEl!, 0, 0, canvas.width, canvas.height)
|
||||
return new Promise<Blob>((resolve, reject) =>
|
||||
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('encoding failed'))), 'image/png')
|
||||
)
|
||||
}
|
||||
|
||||
async function copyImage() {
|
||||
try {
|
||||
// The clipboard takes PNG in every browser, other types in few: re-encode through a canvas.
|
||||
const blob = rasterize()
|
||||
// Handed over as a promise so `write` runs within the click: Safari refuses it once
|
||||
// the user gesture has expired, which an awaited encode would let happen.
|
||||
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
|
||||
sendUserToast('Image copied to clipboard')
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not copy the image: ${e}`, true)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={onKeyDown} />
|
||||
|
||||
{#if shown()}
|
||||
<Disposable
|
||||
bind:open={isOpen}
|
||||
bind:this={disposable}
|
||||
{onOpen}
|
||||
onClose={() => disposable?.closeDrawer()}
|
||||
>
|
||||
{#snippet children({ zIndex })}
|
||||
{#if isOpen}
|
||||
<Portal name="always-mounted">
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={caption}
|
||||
class="fixed inset-0 bg-black/85"
|
||||
style="z-index: {zIndex}"
|
||||
transition:fade|local={{ duration: 150 }}
|
||||
>
|
||||
<div
|
||||
{@attach view.surface}
|
||||
class="absolute inset-0 overflow-hidden touch-none select-none"
|
||||
class:cursor-grab={view.pannable && !view.panning}
|
||||
class:cursor-grabbing={view.panning}
|
||||
role="presentation"
|
||||
onclick={onStageClick}
|
||||
>
|
||||
<img
|
||||
bind:this={imgEl}
|
||||
{@attach view.image}
|
||||
{src}
|
||||
{alt}
|
||||
draggable="false"
|
||||
class={view.imageClass}
|
||||
style={view.imageStyle}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="absolute inset-x-0 top-0 flex items-center justify-between gap-3 p-3 pointer-events-none"
|
||||
>
|
||||
<div
|
||||
class="flex items-baseline gap-2 min-w-0 h-9 px-1 leading-9 drop-shadow pointer-events-auto"
|
||||
>
|
||||
<!-- The overlay is black in both themes, and a zoomed image can pass under the
|
||||
caption, hence fixed white text with a shadow rather than theme tokens. -->
|
||||
<span class="truncate text-xs font-medium text-white/90">{caption}</span>
|
||||
{#if view.natural}
|
||||
<span class="shrink-0 text-2xs text-white/60 tabular-nums">
|
||||
{view.natural.w} × {view.natural.h}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div
|
||||
class="flex shrink-0 items-center gap-0.5 h-9 px-1 rounded-md bg-surface-tertiary shadow-lg pointer-events-auto"
|
||||
>
|
||||
<ZoomControl
|
||||
scale={view.scale}
|
||||
min={view.minScale}
|
||||
max={view.maxScale}
|
||||
onZoomOut={view.zoomOut}
|
||||
onZoomIn={view.zoomIn}
|
||||
onZoomTo={view.zoomToAnimated}
|
||||
/>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
iconOnly
|
||||
startIcon={{ icon: Maximize }}
|
||||
title="Fit to screen (0)"
|
||||
onclick={view.fit}
|
||||
/>
|
||||
<div class="w-px h-4 mx-1 bg-border-light"></div>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
iconOnly
|
||||
startIcon={{ icon: Copy }}
|
||||
title="Copy image"
|
||||
onclick={copyImage}
|
||||
/>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
iconOnly
|
||||
startIcon={{ icon: Download }}
|
||||
title="Download"
|
||||
onclick={download}
|
||||
/>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
iconOnly
|
||||
startIcon={{ icon: ExternalLink }}
|
||||
title="Open in new tab"
|
||||
onclick={openInNewTab}
|
||||
/>
|
||||
{#if onOpenInPreview}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
iconOnly
|
||||
startIcon={{ icon: PanelRight }}
|
||||
title="Open in preview"
|
||||
onclick={() => {
|
||||
close()
|
||||
onOpenInPreview?.()
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
<div class="w-px h-4 mx-1 bg-border-light"></div>
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="sm"
|
||||
iconOnly
|
||||
startIcon={{ icon: X }}
|
||||
title="Close (Esc)"
|
||||
onclick={close}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Portal>
|
||||
{/if}
|
||||
{/snippet}
|
||||
</Disposable>
|
||||
{/if}
|
||||
@@ -0,0 +1,97 @@
|
||||
<script lang="ts">
|
||||
import { Minus, Plus } from 'lucide-svelte'
|
||||
import { Button } from '$lib/components/common'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
|
||||
interface Props {
|
||||
/** Current scale, 1 is actual size; undefined while there is no image. */
|
||||
scale: number | undefined
|
||||
min: number
|
||||
max: number
|
||||
onZoomOut: () => void
|
||||
onZoomIn: () => void
|
||||
/** A scale typed by the user, already clamped to `min`..`max`. */
|
||||
onZoomTo: (scale: number) => void
|
||||
}
|
||||
|
||||
let { scale, min, max, onZoomOut, onZoomIn, onZoomTo }: Props = $props()
|
||||
|
||||
const percent = $derived(scale === undefined ? '' : `${Math.round(scale * 100)}%`)
|
||||
let draft = $state<string | undefined>(undefined)
|
||||
|
||||
function edit() {
|
||||
if (scale !== undefined) draft = String(Math.round(scale * 100))
|
||||
}
|
||||
|
||||
function commit() {
|
||||
if (draft === undefined) return
|
||||
const typed = parseFloat(draft.replace('%', '').trim())
|
||||
draft = undefined
|
||||
if (Number.isFinite(typed) && typed > 0) {
|
||||
onZoomTo(Math.min(max, Math.max(min, typed / 100)))
|
||||
}
|
||||
}
|
||||
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
// The viewers bind +, -, 0 and 1 as zoom shortcuts; typed digits must not reach them.
|
||||
e.stopPropagation()
|
||||
if (e.key === 'Enter') commit()
|
||||
else if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
draft = undefined
|
||||
}
|
||||
}
|
||||
|
||||
function focusAndSelect(node: HTMLElement) {
|
||||
const input = node.querySelector('input')
|
||||
input?.focus()
|
||||
input?.select()
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex items-center gap-0.5">
|
||||
{#if draft !== undefined}
|
||||
<div class="w-14" {@attach focusAndSelect}>
|
||||
<TextInput
|
||||
size="sm"
|
||||
bind:value={draft}
|
||||
class="text-center tabular-nums"
|
||||
inputProps={{
|
||||
'aria-label': 'Zoom level in percent',
|
||||
inputmode: 'decimal',
|
||||
onkeydown: onKeyDown,
|
||||
onblur: commit
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{:else}
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
btnClasses="w-14 justify-center tabular-nums"
|
||||
title="Set zoom level"
|
||||
disabled={scale === undefined}
|
||||
onClick={edit}
|
||||
>
|
||||
{percent}
|
||||
</Button>
|
||||
{/if}
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
iconOnly
|
||||
startIcon={{ icon: Minus }}
|
||||
title="Zoom out (-)"
|
||||
disabled={scale === undefined || scale <= min + 1e-3}
|
||||
onClick={onZoomOut}
|
||||
/>
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
iconOnly
|
||||
startIcon={{ icon: Plus }}
|
||||
title="Zoom in (+)"
|
||||
disabled={scale === undefined || scale >= max - 1e-3}
|
||||
onClick={onZoomIn}
|
||||
/>
|
||||
</div>
|
||||
@@ -0,0 +1,17 @@
|
||||
import { getContext, setContext } from 'svelte'
|
||||
import type { ImageSource } from '$lib/components/sessions/previewRouter'
|
||||
|
||||
/** Opens an image in a viewer beside the current surface: a session's preview panel. */
|
||||
export type ImageOpener = (source: ImageSource, label: string) => void
|
||||
|
||||
const KEY = 'imageOpener'
|
||||
|
||||
/** Provided by a session for everything it renders, the chat and the preview tabs. */
|
||||
export function setImageOpener(opener: ImageOpener): void {
|
||||
setContext(KEY, opener)
|
||||
}
|
||||
|
||||
/** Undefined outside a session: an image then expands in place. */
|
||||
export function getImageOpener(): ImageOpener | undefined {
|
||||
return getContext<ImageOpener | undefined>(KEY)
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
import { on } from 'svelte/events'
|
||||
|
||||
/** The scales the zoom buttons and keys step between; the wheel zooms continuously. */
|
||||
const ZOOM_STEPS = [0.1, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8, 12, 16, 24, 32]
|
||||
const MAX_SCALE = 32
|
||||
// From this scale up, pixels are drawn as hard squares: smoothing an upscaled
|
||||
// screenshot or icon blurs exactly the detail the user zoomed in to look at.
|
||||
const PIXELATED_FROM = 2
|
||||
|
||||
type Point = { x: number; y: number }
|
||||
|
||||
/**
|
||||
* Zoom and pan of one image inside a surface: fit, zoom around a point, step, wheel,
|
||||
* drag, double-click and the `+` `-` `0` `1` keys. Attach `surface` to the element that
|
||||
* clips the image and `image` to the `<img>`, which `imageStyle` positions at the
|
||||
* surface's centre.
|
||||
*/
|
||||
export function useZoomPan(opts: {
|
||||
/** Room kept around a fitted image, in total per axis. */
|
||||
margin: Point
|
||||
/** A click that did not drag; `onImage` tells whether it landed on the image. */
|
||||
onTap?: (onImage: boolean) => void
|
||||
}) {
|
||||
let natural = $state<{ w: number; h: number } | undefined>(undefined)
|
||||
let viewW = $state(0)
|
||||
let viewH = $state(0)
|
||||
/** `fit` follows the surface as it resizes; a number is a fixed scale of the natural size. */
|
||||
let zoom = $state<number | 'fit'>('fit')
|
||||
let pan = $state<Point>({ x: 0, y: 0 })
|
||||
/** Eases button and keyboard zooms; wheel and drag must track the pointer without lag. */
|
||||
let animate = $state(false)
|
||||
let panning = $state(false)
|
||||
let surfaceEl: HTMLElement | undefined
|
||||
let imageEl: HTMLImageElement | undefined
|
||||
|
||||
// Fit never enlarges: a small image is shown at its real size rather than blown up.
|
||||
const fitScale = $derived(
|
||||
natural && viewW > 0 && viewH > 0
|
||||
? Math.min(
|
||||
1,
|
||||
Math.max(viewW - opts.margin.x, 1) / natural.w,
|
||||
Math.max(viewH - opts.margin.y, 1) / natural.h
|
||||
)
|
||||
: 1
|
||||
)
|
||||
const scale = $derived(zoom === 'fit' ? fitScale : zoom)
|
||||
const minScale = $derived(Math.min(fitScale, ZOOM_STEPS[0]))
|
||||
const pannable = $derived(
|
||||
!!natural && (natural.w * scale > viewW + 1 || natural.h * scale > viewH + 1)
|
||||
)
|
||||
|
||||
function clampPan(p: Point, s: number): Point {
|
||||
if (!natural) return { x: 0, y: 0 }
|
||||
const maxX = Math.max(0, (natural.w * s - viewW) / 2)
|
||||
const maxY = Math.max(0, (natural.h * s - viewH) / 2)
|
||||
return {
|
||||
x: Math.min(maxX, Math.max(-maxX, p.x)),
|
||||
y: Math.min(maxY, Math.max(-maxY, p.y))
|
||||
}
|
||||
}
|
||||
|
||||
/** `at` is relative to the surface's centre; the image point there stays put. */
|
||||
function zoomTo(next: number, at: Point = { x: 0, y: 0 }) {
|
||||
const s = Math.min(MAX_SCALE, Math.max(minScale, next))
|
||||
const k = s / scale
|
||||
pan = clampPan({ x: at.x - (at.x - pan.x) * k, y: at.y - (at.y - pan.y) * k }, s)
|
||||
zoom = s
|
||||
}
|
||||
|
||||
function fit() {
|
||||
animate = true
|
||||
zoom = 'fit'
|
||||
pan = { x: 0, y: 0 }
|
||||
}
|
||||
|
||||
function zoomIn() {
|
||||
animate = true
|
||||
zoomTo(ZOOM_STEPS.find((z) => z > scale * 1.01) ?? MAX_SCALE)
|
||||
}
|
||||
|
||||
function zoomOut() {
|
||||
animate = true
|
||||
zoomTo(ZOOM_STEPS.findLast((z) => z < scale / 1.01) ?? minScale)
|
||||
}
|
||||
|
||||
function actualSize() {
|
||||
animate = true
|
||||
zoomTo(1)
|
||||
}
|
||||
|
||||
function surfacePoint(e: { clientX: number; clientY: number }): Point {
|
||||
const r = surfaceEl!.getBoundingClientRect()
|
||||
return { x: e.clientX - r.left - r.width / 2, y: e.clientY - r.top - r.height / 2 }
|
||||
}
|
||||
|
||||
let drag: { x: number; y: number; pan: Point; moved: boolean; onImage: boolean } | undefined
|
||||
|
||||
function endDrag() {
|
||||
drag = undefined
|
||||
panning = false
|
||||
}
|
||||
|
||||
function surface(node: HTMLElement) {
|
||||
surfaceEl = node
|
||||
const resize = new ResizeObserver(() => {
|
||||
viewW = node.clientWidth
|
||||
viewH = node.clientHeight
|
||||
})
|
||||
resize.observe(node)
|
||||
const offs = [
|
||||
// Not passive: the page must not scroll under a wheel zoom.
|
||||
on(
|
||||
node,
|
||||
'wheel',
|
||||
(e: WheelEvent) => {
|
||||
if (!natural) return
|
||||
e.preventDefault()
|
||||
animate = false
|
||||
const lines = e.deltaMode === 1 ? 33 : 1
|
||||
// Pinch on a trackpad arrives as ctrl+wheel with small deltas.
|
||||
const speed = e.ctrlKey ? 0.01 : 0.0015
|
||||
zoomTo(scale * Math.exp(-e.deltaY * lines * speed), surfacePoint(e))
|
||||
},
|
||||
{ passive: false }
|
||||
),
|
||||
on(node, 'pointerdown', (e: PointerEvent) => {
|
||||
if (e.button !== 0) return
|
||||
drag = { x: e.clientX, y: e.clientY, pan, moved: false, onImage: e.target === imageEl }
|
||||
node.setPointerCapture(e.pointerId)
|
||||
}),
|
||||
on(node, 'pointermove', (e: PointerEvent) => {
|
||||
if (!drag) return
|
||||
const dx = e.clientX - drag.x
|
||||
const dy = e.clientY - drag.y
|
||||
if (!drag.moved && Math.hypot(dx, dy) < 4) return
|
||||
drag.moved = true
|
||||
if (pannable) {
|
||||
panning = true
|
||||
animate = false
|
||||
pan = clampPan({ x: drag.pan.x + dx, y: drag.pan.y + dy }, scale)
|
||||
}
|
||||
}),
|
||||
on(node, 'pointerup', () => {
|
||||
if (drag && !drag.moved) opts.onTap?.(drag.onImage)
|
||||
endDrag()
|
||||
}),
|
||||
on(node, 'pointercancel', endDrag),
|
||||
on(node, 'dblclick', (e: MouseEvent) => {
|
||||
if (!natural) return
|
||||
animate = true
|
||||
if (zoom === 'fit' || Math.abs(scale - fitScale) < 0.001) {
|
||||
zoomTo(fitScale < 1 ? 1 : 2, surfacePoint(e))
|
||||
} else {
|
||||
fit()
|
||||
}
|
||||
})
|
||||
]
|
||||
return () => {
|
||||
resize.disconnect()
|
||||
offs.forEach((off) => off())
|
||||
surfaceEl = undefined
|
||||
}
|
||||
}
|
||||
|
||||
function image(node: HTMLImageElement) {
|
||||
imageEl = node
|
||||
const measure = () => {
|
||||
// An SVG without width/height has no intrinsic size.
|
||||
natural = { w: node.naturalWidth || 1024, h: node.naturalHeight || 768 }
|
||||
}
|
||||
if (node.complete && node.naturalWidth) measure()
|
||||
const off = on(node, 'load', measure)
|
||||
return () => {
|
||||
off()
|
||||
imageEl = undefined
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
get natural() {
|
||||
return natural
|
||||
},
|
||||
get scale() {
|
||||
return scale
|
||||
},
|
||||
get minScale() {
|
||||
return minScale
|
||||
},
|
||||
maxScale: MAX_SCALE,
|
||||
get zoom() {
|
||||
return zoom
|
||||
},
|
||||
get pannable() {
|
||||
return pannable
|
||||
},
|
||||
get panning() {
|
||||
return panning
|
||||
},
|
||||
/** Positions the image: its natural size, centred, then panned and scaled. */
|
||||
get imageStyle() {
|
||||
return `width: ${natural?.w ?? 0}px; height: ${natural?.h ?? 0}px; transform: translate(-50%, -50%) translate(${pan.x}px, ${pan.y}px) scale(${scale});`
|
||||
},
|
||||
get imageClass() {
|
||||
return [
|
||||
'absolute left-1/2 top-1/2 max-w-none',
|
||||
natural ? '' : 'opacity-0',
|
||||
animate ? 'transition-transform duration-150 ease-out' : '',
|
||||
scale >= PIXELATED_FROM ? '[image-rendering:pixelated]' : ''
|
||||
].join(' ')
|
||||
},
|
||||
surface,
|
||||
image,
|
||||
fit,
|
||||
zoomIn,
|
||||
zoomOut,
|
||||
actualSize,
|
||||
/** Eased, for a zoom the user typed or picked. */
|
||||
zoomToAnimated(next: number) {
|
||||
animate = true
|
||||
zoomTo(next)
|
||||
},
|
||||
/** Back to fit with no easing, for a viewer shown afresh. */
|
||||
reset() {
|
||||
zoom = 'fit'
|
||||
pan = { x: 0, y: 0 }
|
||||
animate = false
|
||||
},
|
||||
/** Handles a zoom key; returns whether it did, so the caller can prevent its default. */
|
||||
handleKey(e: KeyboardEvent): boolean {
|
||||
if (e.metaKey || e.ctrlKey || e.altKey) return false
|
||||
const action = {
|
||||
'+': zoomIn,
|
||||
'=': zoomIn,
|
||||
'-': zoomOut,
|
||||
_: zoomOut,
|
||||
'0': fit,
|
||||
'1': actualSize
|
||||
}[e.key]
|
||||
if (!action) return false
|
||||
action()
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
<script lang="ts">
|
||||
import Button from '../common/button/Button.svelte'
|
||||
import { tick, type ComponentProps } from 'svelte'
|
||||
import type { ComponentProps } from 'svelte'
|
||||
import OpenInSessionButton from '$lib/components/sessions/OpenInSessionButton.svelte'
|
||||
import { getOpenInSessionHandoff } from '$lib/components/sessions/openInSessionContext'
|
||||
import {
|
||||
getOpenInSessionHandoff,
|
||||
withEditorFlush
|
||||
} from '$lib/components/sessions/openInSessionContext'
|
||||
|
||||
interface Props {
|
||||
moduleId?: string
|
||||
/** Materializes Monaco's in-flight keystrokes into the draft. This button
|
||||
* sits in the code editor's own toolbar, so "type, then click" is the
|
||||
* normal case, and the session preview loads the item from its draft —
|
||||
* without this the last (sub-second) edits would not be in it. */
|
||||
/** Materializes Monaco's in-flight keystrokes into the draft: this button sits in
|
||||
* the code editor's own toolbar, so "type, then click" is the normal case. */
|
||||
flushEditor?: () => void
|
||||
btnProps?: ComponentProps<typeof Button>
|
||||
}
|
||||
@@ -21,17 +22,7 @@
|
||||
const handoff = getOpenInSessionHandoff()
|
||||
const sessionSource = $derived.by(() => {
|
||||
const source = handoff?.source({ moduleId })
|
||||
if (!source || !flushEditor) return source
|
||||
return {
|
||||
...source,
|
||||
beforeOpen: async () => {
|
||||
flushEditor()
|
||||
// The flush lands in the draft store through an effect; let it run
|
||||
// before the hand-off persists that store.
|
||||
await tick()
|
||||
await source.beforeOpen?.()
|
||||
}
|
||||
}
|
||||
return source && flushEditor ? withEditorFlush(source, flushEditor) : source
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -22,10 +22,12 @@
|
||||
|
||||
let loading = $state(false)
|
||||
interface Props {
|
||||
/** Id of the branching step, which isn't the selected id when a branch node is selected. */
|
||||
moduleId: string
|
||||
pickableProperties?: PickableProperties | undefined
|
||||
}
|
||||
|
||||
let { pickableProperties = undefined }: Props = $props()
|
||||
let { moduleId, pickableProperties = undefined }: Props = $props()
|
||||
|
||||
let instructions = $state('')
|
||||
let instructionsField: HTMLInputElement | undefined = $state(undefined)
|
||||
@@ -34,31 +36,32 @@
|
||||
})
|
||||
|
||||
let abortController = $state(new AbortController())
|
||||
const { flowStore, selectionManager } = getContext<FlowEditorContext>('FlowEditorContext')
|
||||
const { flowStore } = getContext<FlowEditorContext>('FlowEditorContext')
|
||||
|
||||
const dispatch = createEventDispatcher()
|
||||
|
||||
async function generatePredicate() {
|
||||
abortController = new AbortController()
|
||||
loading = true
|
||||
const flow: Flow = JSON.parse(JSON.stringify(flowStore.val))
|
||||
const idOrders = dfs(flow.value.modules, (x) => x.id)
|
||||
const upToIndex = idOrders.indexOf(selectionManager.getSelectedId())
|
||||
if (upToIndex === -1) {
|
||||
throw new Error('Could not find the selected id in the flow')
|
||||
}
|
||||
|
||||
const flowDetails =
|
||||
'Take into account the following information for never tested results:\n<flowDetails>\n' +
|
||||
yamlStringifyExceptKeys(sliceModules(flow.value.modules, upToIndex, idOrders), ['lock']) +
|
||||
'</flowDetails>'
|
||||
try {
|
||||
const flow: Flow = JSON.parse(JSON.stringify(flowStore.val))
|
||||
const idOrders = dfs(flow.value.modules, (x) => x.id)
|
||||
const upToIndex = idOrders.indexOf(moduleId)
|
||||
if (upToIndex === -1) {
|
||||
throw new Error('Could not find the branching step in the flow')
|
||||
}
|
||||
|
||||
const flowDetails =
|
||||
'Take into account the following information for never tested results:\n<flowDetails>\n' +
|
||||
yamlStringifyExceptKeys(sliceModules(flow.value.modules, upToIndex, idOrders), ['lock']) +
|
||||
'</flowDetails>'
|
||||
|
||||
const availableData = {
|
||||
results: pickableProperties?.priorIds,
|
||||
flow_input: pickableProperties?.flow_input
|
||||
}
|
||||
const user = `I'm building a workflow which is a DAG of script steps.
|
||||
The current step is ${selectionManager.getSelectedId()} and is a branching step (if-else).
|
||||
The current step is ${moduleId} and is a branching step (if-else).
|
||||
The user wants to generate a predicate for the branching condition.
|
||||
Here's the user's request: ${instructions}
|
||||
You can find the details of all the steps below:
|
||||
|
||||
@@ -22,10 +22,14 @@
|
||||
import { AlertTriangle, Ban, Check, ExternalLink, HistoryIcon, Wand2, X } from 'lucide-svelte'
|
||||
import { fade } from 'svelte/transition'
|
||||
import { isInitialCode } from '$lib/script_helpers'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import { onDestroy, type ComponentProps } from 'svelte'
|
||||
import ProviderModelSelector from './chat/ProviderModelSelector.svelte'
|
||||
import { copilotInfo } from '$lib/aiStore'
|
||||
import {
|
||||
copilotInfo,
|
||||
scriptGenModel,
|
||||
setScriptGenModelPick,
|
||||
tryResolveModelFor
|
||||
} from '$lib/aiStore'
|
||||
|
||||
interface Props {
|
||||
// props
|
||||
@@ -62,6 +66,7 @@
|
||||
let generatedCode = writable<string>('')
|
||||
let dbSchema: DBSchema | undefined = $state(undefined)
|
||||
let abortController: AbortController | undefined = $state(undefined)
|
||||
let model = $derived(tryResolveModelFor($copilotInfo, $scriptGenModel))
|
||||
let blockPopupOpen = $state(false)
|
||||
let mode: 'gen' | 'edit' = $state('gen')
|
||||
|
||||
@@ -71,34 +76,19 @@
|
||||
trimmedDesc = funcDesc.trim()
|
||||
})
|
||||
async function callCopilot() {
|
||||
if (mode === 'edit') {
|
||||
await copilot(
|
||||
{
|
||||
// @ts-ignore
|
||||
language: transformer && lang === 'frontend' ? 'transformer' : lang!,
|
||||
description: trimmedDesc,
|
||||
code: editor?.getCode() || '',
|
||||
dbSchema: dbSchema,
|
||||
type: 'edit',
|
||||
workspace: $workspaceStore!
|
||||
},
|
||||
generatedCode,
|
||||
abortController!
|
||||
)
|
||||
} else {
|
||||
await copilot(
|
||||
{
|
||||
// @ts-ignore
|
||||
language: transformer && lang === 'frontend' ? 'transformer' : lang!,
|
||||
description: trimmedDesc,
|
||||
dbSchema: dbSchema,
|
||||
type: 'gen',
|
||||
workspace: $workspaceStore!
|
||||
},
|
||||
generatedCode,
|
||||
abortController!
|
||||
)
|
||||
}
|
||||
await copilot(
|
||||
{
|
||||
// @ts-ignore
|
||||
language: transformer && lang === 'frontend' ? 'transformer' : lang!,
|
||||
description: trimmedDesc,
|
||||
dbSchema: dbSchema,
|
||||
workspace: $workspaceStore!,
|
||||
...(mode === 'edit' ? { type: 'edit', code: editor?.getCode() || '' } : { type: 'gen' })
|
||||
},
|
||||
generatedCode,
|
||||
abortController!,
|
||||
{ forceModelProvider: model }
|
||||
)
|
||||
}
|
||||
|
||||
function handleAiButtonClick() {
|
||||
@@ -132,13 +122,13 @@
|
||||
showDiff()
|
||||
funcDesc = ''
|
||||
} catch (err) {
|
||||
if (!abortController?.signal.aborted) {
|
||||
if (err?.message) {
|
||||
sendUserToast('Failed to generate code: ' + err.message, true)
|
||||
} else {
|
||||
sendUserToast('Failed to generate code', true)
|
||||
console.error(err)
|
||||
}
|
||||
if (abortController?.signal.aborted) {
|
||||
clear()
|
||||
} else if (err?.message) {
|
||||
sendUserToast('Failed to generate code: ' + err.message, true)
|
||||
} else {
|
||||
sendUserToast('Failed to generate code', true)
|
||||
console.error(err)
|
||||
}
|
||||
} finally {
|
||||
genLoading = false
|
||||
@@ -364,39 +354,38 @@
|
||||
]
|
||||
}}
|
||||
disabled={blockPopupOpen}
|
||||
onClose={() => {
|
||||
// Escape or a click on the overlay closes the box mid-request, taking its Stop with it.
|
||||
if (blockPopupOpen) abortController?.abort()
|
||||
}}
|
||||
>
|
||||
{#snippet trigger()}
|
||||
{#if inlineScript}
|
||||
<Button
|
||||
size="xs"
|
||||
color={genLoading ? 'red' : 'light'}
|
||||
btnClasses={twMerge(genLoading ? '!px-3 z-[5000]' : '!px-2')}
|
||||
propagateEvent={!genLoading}
|
||||
on:click={genLoading ? () => abortController?.abort() : handleAiButtonClick}
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
btnClasses="!px-2"
|
||||
disabled={genLoading}
|
||||
on:click={handleAiButtonClick}
|
||||
bind:element={button}
|
||||
iconOnly
|
||||
title="Generate code from prompt"
|
||||
startIcon={genLoading ? { icon: Ban } : { icon: Wand2, classes: 'text-ai' }}
|
||||
startIcon={{ icon: Wand2, classes: 'text-ai' }}
|
||||
{...btnProps}
|
||||
/>
|
||||
{:else}
|
||||
<Button
|
||||
title="Generate code from prompt"
|
||||
btnClasses={twMerge('!font-medium', genLoading ? 'z-[5000]' : 'text-ai')}
|
||||
size="xs"
|
||||
color={genLoading ? 'red' : 'light'}
|
||||
spacingSize="md"
|
||||
startIcon={genLoading ? { icon: Ban } : { icon: Wand2 }}
|
||||
propagateEvent={!genLoading}
|
||||
on:click={genLoading ? () => abortController?.abort() : handleAiButtonClick}
|
||||
btnClasses="!font-medium text-ai"
|
||||
unifiedSize="sm"
|
||||
variant="subtle"
|
||||
startIcon={{ icon: Wand2 }}
|
||||
disabled={genLoading}
|
||||
on:click={handleAiButtonClick}
|
||||
bind:element={button}
|
||||
{...btnProps}
|
||||
>
|
||||
{#if genLoading}
|
||||
Stop
|
||||
{:else}
|
||||
AI Gen
|
||||
{/if}
|
||||
AI Gen
|
||||
</Button>
|
||||
{/if}
|
||||
{/snippet}
|
||||
@@ -412,18 +401,24 @@
|
||||
<LoadingIcon />
|
||||
{/if}
|
||||
</div>
|
||||
<div class="flex justify-end pt-2">
|
||||
<Button
|
||||
unifiedSize="sm"
|
||||
variant="default"
|
||||
startIcon={{ icon: Ban }}
|
||||
onClick={() => abortController?.abort()}
|
||||
>
|
||||
Stop
|
||||
</Button>
|
||||
</div>
|
||||
{:else if $copilotInfo.enabled}
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex flex-row justify-between items-center w-96 gap-2">
|
||||
<ToggleButtonGroup class="w-auto shrink-0 h-auto" bind:selected={mode}>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton value={'gen'} label="Generate from scratch" class="px-2" {item} />
|
||||
<ToggleButton value={'edit'} label="Edit existing code" class="px-2" {item} />
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
|
||||
<ProviderModelSelector />
|
||||
</div>
|
||||
<ToggleButtonGroup class="w-auto self-start h-auto" bind:selected={mode}>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton value={'gen'} label="Generate from scratch" class="px-2" {item} />
|
||||
<ToggleButton value={'edit'} label="Edit existing code" class="px-2" {item} />
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
<div class="flex w-96 items-start">
|
||||
<textarea
|
||||
bind:this={input}
|
||||
@@ -456,6 +451,9 @@
|
||||
startIcon={{ icon: Wand2 }}
|
||||
/>
|
||||
</div>
|
||||
<div class="flex w-96 justify-end items-center gap-1 -mt-3">
|
||||
<ProviderModelSelector {model} onPick={setScriptGenModelPick} />
|
||||
</div>
|
||||
{#if promptHistory.length > 0}
|
||||
<div class="w-96 flex flex-col gap-1">
|
||||
{#each promptHistory as p}
|
||||
|
||||
@@ -264,7 +264,7 @@ input_name2: expression2
|
||||
{:else}
|
||||
Enable step input completion in the{' '}
|
||||
<a
|
||||
href="#user-settings"
|
||||
href="#user-settings-ai"
|
||||
class="inline-flex flex-row items-center gap-1"
|
||||
onclick={(e) => {
|
||||
if (!isNewTabClick(e)) close()
|
||||
|
||||
@@ -203,7 +203,7 @@
|
||||
let plusMenuOpen = $state(false)
|
||||
let editingMessageIndex = $state<number | null>(null)
|
||||
const groupChatItems = createChatItemGrouper()
|
||||
const chatItems = $derived(groupChatItems(messages, chatHost.lookupTools))
|
||||
const chatItems = $derived(groupChatItems(messages, chatHost.groupingTools))
|
||||
|
||||
// Mounting a message parses its markdown, so a long transcript mounted at once blocks the
|
||||
// page for every message in it. Only the tail is mounted when a transcript arrives; older
|
||||
@@ -523,7 +523,7 @@
|
||||
return
|
||||
}
|
||||
// Otherwise (folders / multi-select): summarize to avoid a flood of toasts. The only
|
||||
// per-file rejection left is non-text content (binary files are skipped).
|
||||
// per-file rejection left is binary content other than images.
|
||||
const lead = added.length
|
||||
? `Attached ${added.length}, skipped ${rejected.length}`
|
||||
: `Skipped ${rejected.length} file${rejected.length === 1 ? '' : 's'}`
|
||||
@@ -663,10 +663,9 @@
|
||||
const entries = await readDroppedEntries(Array.from(dt.items ?? []))
|
||||
const source: FileToAttach[] = entries.length > 0 ? entries : flatFiles
|
||||
// Top-level files attach to the message (images were already reserved
|
||||
// from dt.files before the walk). Folder children keep riding the
|
||||
// session store as a snapshot — including nested images, which are
|
||||
// deliberately NOT attached (the FSA path never extracts folder
|
||||
// contents either); they are summarized as skipped there.
|
||||
// from dt.files before the walk). Folder children ride the session store
|
||||
// as a snapshot, nested images included: they become image rows the
|
||||
// preview can show, never message attachments, as on the FSA path.
|
||||
const topLevelText: File[] = []
|
||||
const folderEntries: FileToAttach[] = []
|
||||
for (const entry of source) {
|
||||
|
||||
@@ -1,239 +1,74 @@
|
||||
<script lang="ts">
|
||||
import * as monaco from 'monaco-editor'
|
||||
import AIChatInput from './AIChatInput.svelte'
|
||||
import { aiChatManager, AIMode } from './AIChatManager.svelte'
|
||||
import type { Selection } from 'monaco-editor'
|
||||
import ChatTypingIndicator from './ChatTypingIndicator.svelte'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import { onDestroy } from 'svelte'
|
||||
import type { AIChatEditorHandler } from './monaco-adapter'
|
||||
import { getModifierKey } from '$lib/utils'
|
||||
import { clickOutside } from '$lib/utils'
|
||||
import InlinePrompt from './InlinePrompt.svelte'
|
||||
|
||||
interface Props {
|
||||
editor: monaco.editor.IStandaloneCodeEditor
|
||||
selection: Selection | null
|
||||
selectedCode: string
|
||||
show: boolean
|
||||
editorHandler: AIChatEditorHandler
|
||||
/** The line the box sits over. */
|
||||
line: number
|
||||
/** Resolving to `false` keeps the box open with its text. */
|
||||
onSend: (prompt: string) => Promise<boolean>
|
||||
/** `refocus` unless closing on a click, which already put the focus where the user wants it. */
|
||||
onClose: (refocus: boolean) => void
|
||||
}
|
||||
|
||||
let { editor, selection, selectedCode, show = $bindable(false), editorHandler }: Props = $props()
|
||||
let { editor, line, onSend, onClose }: Props = $props()
|
||||
|
||||
let widget: AIChatWidget | null = $state(null)
|
||||
let widgetElement: HTMLElement | null = $state(null)
|
||||
let aiChatInput: AIChatInput | null = $state(null)
|
||||
let processing = $state(false)
|
||||
let marginToAdd = $state(0)
|
||||
let prompt: InlinePrompt | undefined = $state()
|
||||
|
||||
class AIChatWidget implements monaco.editor.IContentWidget {
|
||||
private domNode: HTMLElement
|
||||
public position: monaco.IPosition
|
||||
editor: monaco.editor.IStandaloneCodeEditor
|
||||
private originalPadding: number = 0
|
||||
private editorHandler: AIChatEditorHandler
|
||||
|
||||
constructor(
|
||||
lineNumber: number,
|
||||
domNode: HTMLElement,
|
||||
editor: monaco.editor.IStandaloneCodeEditor,
|
||||
editorHandler: AIChatEditorHandler
|
||||
) {
|
||||
this.domNode = domNode
|
||||
this.position = { lineNumber, column: 0 }
|
||||
this.editor = editor
|
||||
this.editorHandler = editorHandler
|
||||
this.ensureSpaceAbove()
|
||||
|
||||
this.editor.onDidScrollChange((e) => {
|
||||
this.domNode.style.visibility = 'inherit'
|
||||
$effect(() => {
|
||||
const domNode = widgetElement
|
||||
if (!domNode) return
|
||||
const widget: monaco.editor.IContentWidget = {
|
||||
// Monaco's overflow layer, which draws above the buttons hosts float over the editor.
|
||||
allowEditorOverflow: true,
|
||||
getId: () => 'ai-inline-chat-widget',
|
||||
getDomNode: () => domNode,
|
||||
getPosition: () => ({
|
||||
position: { lineNumber: line, column: 1 },
|
||||
preference: [monaco.editor.ContentWidgetPositionPreference.ABOVE]
|
||||
})
|
||||
}
|
||||
|
||||
private ensureSpaceAbove() {
|
||||
const widgetHeight = 100
|
||||
const additionalPadding = 15
|
||||
const linesHeight = 20 * this.position.lineNumber
|
||||
if (linesHeight < widgetHeight + additionalPadding) {
|
||||
// Add top margin to editor to make space
|
||||
const editorDom = this.editor.getDomNode()
|
||||
if (editorDom) {
|
||||
const neededPadding = widgetHeight + additionalPadding - linesHeight
|
||||
this.originalPadding = this.editor.getOption(monaco.editor.EditorOption.padding)?.top || 0
|
||||
this.editor.updateOptions({
|
||||
padding: {
|
||||
top: neededPadding
|
||||
}
|
||||
})
|
||||
// Trigger layout update
|
||||
this.editor.layout()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private restoreEditorSpacing() {
|
||||
if (this.position.lineNumber < 10) {
|
||||
const editorDom = this.editor.getDomNode()
|
||||
if (editorDom) {
|
||||
this.editor.updateOptions({
|
||||
padding: {
|
||||
top: this.originalPadding
|
||||
}
|
||||
})
|
||||
this.editor.layout()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getId(): string {
|
||||
return 'ai-inline-chat-widget'
|
||||
}
|
||||
|
||||
getDomNode(): HTMLElement {
|
||||
return this.domNode
|
||||
}
|
||||
|
||||
getAddedLines(): number {
|
||||
if (!this.editorHandler || !this.editorHandler.groupChanges) {
|
||||
return 0
|
||||
}
|
||||
|
||||
let totalAddedLines = 0
|
||||
let totalRemovedLines = 0
|
||||
for (const group of this.editorHandler.groupChanges) {
|
||||
for (const change of group.changes) {
|
||||
if (change.type === 'added_block') {
|
||||
// Count newlines in the added content
|
||||
const lines = change.value.split('\n').length - 1
|
||||
totalAddedLines += Math.max(1, lines)
|
||||
} else if (change.type === 'deleted') {
|
||||
const lines = change.range.endLine - change.range.startLine + 1
|
||||
totalRemovedLines += Math.max(1, lines)
|
||||
}
|
||||
}
|
||||
}
|
||||
return totalAddedLines - totalRemovedLines
|
||||
}
|
||||
|
||||
getPosition(): monaco.editor.IContentWidgetPosition {
|
||||
return {
|
||||
position: this.position,
|
||||
preference: [monaco.editor.ContentWidgetPositionPreference.ABOVE]
|
||||
}
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this.restoreEditorSpacing()
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup function to safely remove widget and cancel inline requests
|
||||
function cleanupWidget(reason?: string) {
|
||||
aiChatManager.cancelInlineRequest(reason ?? 'aiChatInlineWidget destroyed')
|
||||
if (widget) {
|
||||
try {
|
||||
widget.dispose()
|
||||
editor.removeContentWidget(widget)
|
||||
} catch (error) {
|
||||
console.warn('Failed to remove content widget:', error)
|
||||
}
|
||||
widget = null
|
||||
}
|
||||
}
|
||||
|
||||
// Create/remove widget based on show state
|
||||
$effect(() => {
|
||||
if (show && !widget && widgetElement && selection) {
|
||||
if (aiChatManager.mode !== AIMode.SCRIPT) {
|
||||
aiChatManager.changeMode(AIMode.SCRIPT)
|
||||
}
|
||||
const startLine = selection.startLineNumber
|
||||
widget = new AIChatWidget(startLine, widgetElement, editor, editorHandler)
|
||||
editor.addContentWidget(widget)
|
||||
if (aiChatInput) {
|
||||
aiChatInput.focusInput()
|
||||
}
|
||||
} else if (!show && widget) {
|
||||
cleanupWidget('aiChatInlineWidget hidden')
|
||||
}
|
||||
})
|
||||
|
||||
onDestroy(() => {
|
||||
cleanupWidget('aiChatInlineWidget destroyed')
|
||||
})
|
||||
|
||||
export function focusInput() {
|
||||
setTimeout(() => {
|
||||
aiChatInput?.focusInput()
|
||||
}, 130)
|
||||
}
|
||||
|
||||
// Reactive effect to update margin when review state changes
|
||||
$effect(() => {
|
||||
const isInReviewMode = aiChatManager.pendingNewCode !== undefined
|
||||
|
||||
if (isInReviewMode && widget) {
|
||||
const addedLines = widget.getAddedLines()
|
||||
if (widgetElement) {
|
||||
marginToAdd = addedLines * 25
|
||||
widgetElement.style.marginTop = `-${marginToAdd}px`
|
||||
}
|
||||
} else {
|
||||
marginToAdd = 0
|
||||
const padding = editor.getOption(monaco.editor.EditorOption.padding).top
|
||||
// Monaco cuts off a widget taller than what is above its line.
|
||||
const room = domNode.offsetHeight + 16
|
||||
const missing = room - editor.getTopForLineNumber(line)
|
||||
if (missing > 0) editor.updateOptions({ padding: { top: padding + missing } })
|
||||
// Nor does it draw one whose line is out of view.
|
||||
const top = editor.getTopForLineNumber(line)
|
||||
const bottom = top + editor.getOption(monaco.editor.EditorOption.lineHeight)
|
||||
const lowest = bottom - editor.getLayoutInfo().height
|
||||
editor.setScrollTop(Math.min(Math.max(editor.getScrollTop(), lowest), top - room))
|
||||
editor.addContentWidget(widget)
|
||||
// That layer is not cut at the editor's edge: scrolled up, the box would cover its toolbar.
|
||||
const scroll = editor.onDidScrollChange(() => {
|
||||
const above = editor.getTopForLineNumber(line) - editor.getScrollTop()
|
||||
const hidden = above < domNode.offsetHeight
|
||||
domNode.classList.toggle('opacity-0', hidden)
|
||||
domNode.classList.toggle('pointer-events-none', hidden)
|
||||
})
|
||||
// Monaco places the widget, and takes its focus with it, on its next render.
|
||||
const timeout = setTimeout(() => prompt?.focus(), 130)
|
||||
return () => {
|
||||
clearTimeout(timeout)
|
||||
scroll.dispose()
|
||||
editor.updateOptions({ padding: { top: padding } })
|
||||
editor.removeContentWidget(widget)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
{#snippet pendingApplyHint()}
|
||||
<span class="text-xs text-primary pr-1">
|
||||
{getModifierKey()}↓ to apply
|
||||
</span>
|
||||
{/snippet}
|
||||
|
||||
{#if show}
|
||||
<div bind:this={widgetElement} class="w-[300px] -mt-2 relative">
|
||||
{#if processing}
|
||||
<div class="absolute -top-5 left-2 pointer-events-none z-10">
|
||||
<ChatTypingIndicator loading={processing} compact />
|
||||
</div>
|
||||
{/if}
|
||||
<AIChatInput
|
||||
bind:this={aiChatInput}
|
||||
availableContext={aiChatManager.contextManager.getAvailableContext()}
|
||||
selectedContext={aiChatManager.contextManager.getSelectedContext()}
|
||||
onClickOutside={() => {
|
||||
show = false
|
||||
}}
|
||||
onSendRequest={async (instructions) => {
|
||||
if (!selection || processing) {
|
||||
return
|
||||
}
|
||||
|
||||
processing = true
|
||||
|
||||
try {
|
||||
const reply = await aiChatManager.sendInlineRequest(instructions, selectedCode, selection)
|
||||
if (reply) {
|
||||
await aiChatManager.applyScriptEditorCode(reply)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Inline AI request failed:', error)
|
||||
if (error instanceof Error) {
|
||||
sendUserToast('AI request failed: ' + error.message, true)
|
||||
} else {
|
||||
sendUserToast('AI request failed: Unknown error', true)
|
||||
}
|
||||
} finally {
|
||||
processing = false
|
||||
}
|
||||
|
||||
focusInput()
|
||||
}}
|
||||
showContext={false}
|
||||
className="-ml-2"
|
||||
bottomRightSnippet={aiChatManager.pendingNewCode ? pendingApplyHint : undefined}
|
||||
loading={processing}
|
||||
onCancel={() => aiChatManager.cancelInlineRequest('user pressed stop')}
|
||||
disabled={processing}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
<div
|
||||
bind:this={widgetElement}
|
||||
class="w-[300px] -mt-2 z-20"
|
||||
use:clickOutside={{ onClickOutside: () => onClose(false) }}
|
||||
>
|
||||
<InlinePrompt
|
||||
bind:this={prompt}
|
||||
ariaLabel="Prompt about the selected code"
|
||||
{onSend}
|
||||
onClose={() => onClose(true)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
contextElementKey,
|
||||
createAttachedFileContextElement,
|
||||
isMentionContext,
|
||||
isPickContext,
|
||||
isSameContextElement,
|
||||
type AppDomSelectorElement,
|
||||
type ContextElement
|
||||
} from './context'
|
||||
import { AIMode } from './AIChatManager.svelte'
|
||||
@@ -85,19 +85,10 @@
|
||||
onEditEnd?: () => void
|
||||
className?: string
|
||||
onClickOutside?: () => void
|
||||
onSendRequest?: (instructions: string) => void
|
||||
showContext?: boolean
|
||||
bottomRightSnippet?: Snippet
|
||||
/** Shows "Press Esc again to clear" next to the send button. */
|
||||
clearHint?: boolean
|
||||
onKeyDown?: (e: KeyboardEvent) => void
|
||||
// When provided, overrides `chatHost.loading` for the send/stop
|
||||
// button — useful for callers driving their own request lifecycle
|
||||
// (e.g. the inline ⌘K widget runs requests outside the global
|
||||
// `chatHost.loading` flag).
|
||||
loading?: boolean
|
||||
// Called when the user clicks Stop. Defaults to `chatHost.cancel()`.
|
||||
onCancel?: () => void
|
||||
// Observe the composer draft as it changes (the text is local state —
|
||||
// `chatHost.instructions` only carries programmatic prompts). Used by
|
||||
// sessions to persist the typed-but-unsent prompt with the session draft.
|
||||
@@ -144,13 +135,9 @@
|
||||
onEditEnd = () => {},
|
||||
className = '',
|
||||
onClickOutside = () => {},
|
||||
onSendRequest = undefined,
|
||||
showContext = true,
|
||||
bottomRightSnippet,
|
||||
clearHint = false,
|
||||
onKeyDown = undefined,
|
||||
loading,
|
||||
onCancel,
|
||||
onDraftChange = undefined,
|
||||
initialAttachments = undefined,
|
||||
onAttachmentsChange = undefined,
|
||||
@@ -637,9 +624,7 @@
|
||||
chatHost.mode === AIMode.GLOBAL
|
||||
)
|
||||
|
||||
const domSelectorChips = $derived(
|
||||
(selectedContext ?? []).filter((c): c is AppDomSelectorElement => c.type === 'app_dom_selector')
|
||||
)
|
||||
const pickChips = $derived((selectedContext ?? []).filter(isPickContext))
|
||||
|
||||
const contextKey = contextElementKey
|
||||
|
||||
@@ -984,6 +969,12 @@
|
||||
chatManager.contextManager?.consumeMentionContext()
|
||||
}
|
||||
|
||||
/** Apart from the mentions, which an answer to a question consumes too: it carries no pick. */
|
||||
function consumePicksIfGlobal() {
|
||||
if (chatHost.mode !== AIMode.GLOBAL) return
|
||||
chatManager.contextManager?.consumePickContext()
|
||||
}
|
||||
|
||||
/** `midTurn`: Ctrl/⌘+Enter, which sends a message queued behind a running turn into that
|
||||
* turn instead of after it (`ChatViewHost.sendQueuedMidTurn`). */
|
||||
function sendRequest({ midTurn = false }: { midTurn?: boolean } = {}) {
|
||||
@@ -1036,6 +1027,7 @@
|
||||
)
|
||||
// Consumed at enqueue, not at flush: the entry above pinned them.
|
||||
consumeMentionsIfGlobal()
|
||||
consumePicksIfGlobal()
|
||||
contextTextareaComponent?.clearForSend()
|
||||
}
|
||||
// With an empty composer, this marks what is already queued.
|
||||
@@ -1063,6 +1055,7 @@
|
||||
// when given no override, and the consume below empties it.
|
||||
const carried = chatHost.mode === AIMode.GLOBAL ? [...selectedContext] : undefined
|
||||
consumeMentionsIfGlobal()
|
||||
consumePicksIfGlobal()
|
||||
// A host that refuses the turn puts the draft back itself (see AIChatManager's
|
||||
// restoreToInput and FlowChatViewHost's upload failure): restoring here too
|
||||
// would double the text and every attachment.
|
||||
@@ -1072,8 +1065,7 @@
|
||||
images: sent.images,
|
||||
files: sent.files,
|
||||
blobs: sent.blobs,
|
||||
contextOverride: carried,
|
||||
contextOverrideOrigin: carried ? 'pinned' : undefined
|
||||
contextOverride: carried
|
||||
})
|
||||
// clearForSend() pre-zaps the textarea's mention-sync so the wipe doesn't
|
||||
// drop `selectedContext` before the send has settled its context: the pin
|
||||
@@ -1086,9 +1078,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
// A custom `onSendRequest` consumer (e.g. the inline ⌘K widget) has no chip
|
||||
// display, so it gets the fully expanded text; the default path keeps tokens
|
||||
// for the conversation bubble and expands them for the LLM inside the manager.
|
||||
/** Enter in a plain textarea. Ctrl/⌘ sends without stopping, and that press stops here for
|
||||
* the same reason as in `ContextTextarea`: pages bind their own Ctrl/⌘+Enter on the window. */
|
||||
function sendFromEnter(e: KeyboardEvent) {
|
||||
@@ -1098,14 +1087,6 @@
|
||||
sendRequest({ midTurn })
|
||||
}
|
||||
|
||||
function submitRequest(options: { midTurn?: boolean } = {}) {
|
||||
if (onSendRequest) {
|
||||
onSendRequest(expanded(chatDraft(draft.text, draft.pastes)))
|
||||
} else {
|
||||
sendRequest(options)
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (editingMessageIndex !== null) {
|
||||
focusInput()
|
||||
@@ -1342,12 +1323,11 @@
|
||||
<!-- The turn stays `loading` while parked on a question, but a drafted answer
|
||||
is what the button should ship then — otherwise the only pointer action on
|
||||
a typed answer would be Stop. Anything else keeps Stop. -->
|
||||
{@const isLoading = (loading ?? chatHost.loading) && !questionAnsweredBySend}
|
||||
{@const isLoading = chatHost.loading && !questionAnsweredBySend}
|
||||
{@const emptyDraft = draft.isEmpty}
|
||||
<!-- A text-free GLOBAL draft with context chips is a valid turn (Enter
|
||||
already sends it), so the button stays enabled there for pointer/touch
|
||||
parity — mirrors the sendRequest guard. Custom onSendRequest consumers
|
||||
(inline ⌘K) and editor copilots need content. -->
|
||||
parity — mirrors the sendRequest guard. Editor copilots need content. -->
|
||||
{@const needsText = chatHost.requiresMessageText && draft.text.trim() === ''}
|
||||
<!-- The wording is about the attachment, so it earns its place only once there is one:
|
||||
an empty composer is the idle state, not a refusal. -->
|
||||
@@ -1359,10 +1339,7 @@
|
||||
pendingBlobs > 0 ||
|
||||
ingestionHolds > 0 ||
|
||||
needsText ||
|
||||
(emptyDraft &&
|
||||
(onSendRequest !== undefined ||
|
||||
chatHost.mode !== AIMode.GLOBAL ||
|
||||
selectedContext.length === 0))}
|
||||
(emptyDraft && (chatHost.mode !== AIMode.GLOBAL || selectedContext.length === 0))}
|
||||
<!-- Accent only once there is something to send, so the button lights up as the draft
|
||||
becomes sendable; idle and Stop stay quiet. -->
|
||||
<div class="relative flex shrink-0">
|
||||
@@ -1389,9 +1366,9 @@
|
||||
disabled={!isLoading && sendDisabled}
|
||||
on:click={() => {
|
||||
if (isLoading) {
|
||||
onCancel ? onCancel() : chatHost.cancel()
|
||||
chatHost.cancel()
|
||||
} else if (!sendDisabled) {
|
||||
submitRequest()
|
||||
sendRequest()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
@@ -1399,11 +1376,11 @@
|
||||
{/snippet}
|
||||
|
||||
<!-- One wrapping row for every badge-shaped chip: selected context (or, when the
|
||||
picker row is hidden — showContext=false in GLOBAL/session mode — the raw-app
|
||||
inspector's DOM picks, which always show), then message files. Only image
|
||||
picker row is hidden — showContext=false in GLOBAL/session mode — the preview elements
|
||||
and code the user picked, which always show), then message files. Only image
|
||||
thumbnails get their own row (different height). -->
|
||||
{#snippet badgeRow()}
|
||||
{@const contextChips = showContext ? selectedContext : domSelectorChips}
|
||||
{@const contextChips = showContext ? selectedContext : pickChips}
|
||||
{#if contextChips.length > 0 || draft.files.length > 0 || pendingFiles > 0 || draft.blobs.length > 0 || pendingBlobs > 0}
|
||||
<div class="flex flex-row flex-wrap items-center gap-1 px-2.5 pt-2">
|
||||
{#each contextChips as element (contextKey(element))}
|
||||
@@ -1502,7 +1479,6 @@
|
||||
!e.defaultPrevented &&
|
||||
e.target instanceof HTMLTextAreaElement &&
|
||||
editingMessageIndex === null &&
|
||||
onSendRequest === undefined &&
|
||||
draft.isEmpty &&
|
||||
pendingImages === 0 &&
|
||||
pendingFiles === 0 &&
|
||||
@@ -1515,9 +1491,8 @@
|
||||
// Empty means no attachment still decoding/reading either —
|
||||
// recalling over an attachments-only draft would clobber it.
|
||||
// Textarea only — ArrowUp on the wrapper's buttons/badges must not
|
||||
// mutate the composer; and main composer only — the edit input and
|
||||
// custom-send consumers (inline widget) have their own history
|
||||
// semantics.
|
||||
// mutate the composer; and main composer only — the edit input has
|
||||
// its own history semantics.
|
||||
if (
|
||||
chatHost.queuedMessage ||
|
||||
chatHost.queuedImages.length > 0 ||
|
||||
@@ -1564,7 +1539,7 @@
|
||||
if (disabled) {
|
||||
return
|
||||
}
|
||||
submitRequest({ midTurn: withModifier })
|
||||
sendRequest({ midTurn: withModifier })
|
||||
}}
|
||||
{disabled}
|
||||
{onKeyDown}
|
||||
@@ -1582,7 +1557,7 @@
|
||||
{@render toolbarRow()}
|
||||
{/snippet}
|
||||
</ContextTextarea>
|
||||
{#if !bottomRightSnippet && !toolbarInBox}
|
||||
{#if !toolbarInBox}
|
||||
<div class="absolute bottom-1 right-1">
|
||||
{@render sendStopButton()}
|
||||
</div>
|
||||
@@ -1623,11 +1598,9 @@
|
||||
class={twMerge('resize-none', CHAT_INPUT_PADDING)}
|
||||
{disabled}
|
||||
></textarea>
|
||||
{#if !bottomRightSnippet}
|
||||
<div class="absolute bottom-1 right-1">
|
||||
{@render sendStopButton()}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="absolute bottom-1 right-1">
|
||||
{@render sendStopButton()}
|
||||
</div>
|
||||
</div>
|
||||
{#if showAppContextTooltip}
|
||||
<Portal target="body">
|
||||
@@ -1681,20 +1654,13 @@
|
||||
class={twMerge('resize-none', COMPOSER_FIELD_RESET, CHAT_INPUT_PADDING)}
|
||||
{disabled}
|
||||
></textarea>
|
||||
{#if !bottomRightSnippet}
|
||||
<div class="absolute bottom-1 right-1">
|
||||
{@render sendStopButton()}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="absolute bottom-1 right-1">
|
||||
{@render sendStopButton()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{#if toolbar && !toolbarInBox}
|
||||
<div class="mt-1">{@render toolbar()}</div>
|
||||
{/if}
|
||||
{#if bottomRightSnippet}
|
||||
<div class="absolute bottom-1 right-1">
|
||||
{@render bottomRightSnippet()}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AttachedBlob } from './blobUtils'
|
||||
import { SecretCheckFailed, checkSubmission, checkText, saveSecretRequest } from './secretRequest'
|
||||
import type { ChatViewHost } from './chatViewHost'
|
||||
import type { ScriptLang } from '$lib/gen/types.gen'
|
||||
import { JobService, type CompletedJob } from '$lib/gen'
|
||||
@@ -25,6 +26,9 @@ import {
|
||||
type ToolCallbacks,
|
||||
type ToolDisplayMessage,
|
||||
type UserQuestionDisplay,
|
||||
type SecretRequest,
|
||||
type SecretSubmission,
|
||||
type SecretRequestOutcome,
|
||||
type RunFormAnswer,
|
||||
type RunFormDisplay,
|
||||
type RunFormDraft,
|
||||
@@ -36,17 +40,14 @@ import {
|
||||
createJobUpdateReader,
|
||||
deriveChatJobStatus,
|
||||
pendingToolImagesMessage,
|
||||
type ToolImage,
|
||||
trimJob
|
||||
} from './shared'
|
||||
import type {
|
||||
ChatCompletionMessageParam,
|
||||
ChatCompletionSystemMessageParam
|
||||
} from 'openai/resources/chat/completions.mjs'
|
||||
import {
|
||||
prepareInlineChatSystemPrompt,
|
||||
prepareScriptSystemMessage,
|
||||
prepareScriptTools
|
||||
} from './script/core'
|
||||
import { prepareScriptSystemMessage, prepareScriptTools } from './script/core'
|
||||
import type { ScriptLintResult } from './shared'
|
||||
import { navigatorTools, prepareNavigatorSystemMessage } from './navigator/core'
|
||||
import { loadApiTools } from './api/apiTools'
|
||||
@@ -105,6 +106,7 @@ import {
|
||||
getWorkspaceCopilotInfo,
|
||||
loadWorkspaceCopilotInfo,
|
||||
resolveModelFor,
|
||||
setLastModelPick,
|
||||
tryResolveModelFor,
|
||||
workspaceCopilotInfoFailed,
|
||||
type AiTarget,
|
||||
@@ -121,11 +123,13 @@ import {
|
||||
createAppFrontendFileContextElement,
|
||||
flattenDatatablesToAppContextElements,
|
||||
isMentionContext,
|
||||
isPickContext,
|
||||
isSameContextElement,
|
||||
type CodeSelection,
|
||||
type ContextElement,
|
||||
type PickContext,
|
||||
type AppDatatableElement
|
||||
} from './context'
|
||||
import type { Selection } from 'monaco-editor'
|
||||
import type AIChatInput from './AIChatInput.svelte'
|
||||
import { prepareApiSystemMessage, prepareApiUserMessage } from './api/core'
|
||||
import {
|
||||
@@ -202,8 +206,8 @@ import {
|
||||
assembleGlobalTools,
|
||||
type GlobalAssemblyOpts
|
||||
} from './global/globalAssembly'
|
||||
import type { LookupTools } from './toolGroups'
|
||||
import { chatLookupTools } from './lookupTools'
|
||||
import type { GroupingTools } from './toolGroups'
|
||||
import { chatGroupingTools } from './groupingTools'
|
||||
import { formatChatJobCompletion } from './datatableTools'
|
||||
import { loadMcpServers, type McpServer } from './global/mcpTools'
|
||||
import type { PipelineAIChatHelpers } from './pipeline/core'
|
||||
@@ -211,7 +215,7 @@ import { scopedKey, onUserChange, migrateLegacyLocalStorage } from '$lib/userSco
|
||||
import { getLocalSetting, storeLocalSetting } from '$lib/utils'
|
||||
import { AttachedFilesStore } from './files/attachedFiles.svelte'
|
||||
import { SessionArtifactsStore } from './artifacts/artifactsState.svelte'
|
||||
import type { ArtifactVersionTarget } from '$lib/components/sessions/previewRouter'
|
||||
import type { ArtifactVersionTarget, ImageSource } from '$lib/components/sessions/previewRouter'
|
||||
import { appendAttachedFilesRoster } from './files/fileTools'
|
||||
import { ENTER_PLAN_MODE_TOOL, EXIT_PLAN_MODE_TOOL } from './planMode'
|
||||
import { PlanModeController, type PlanModeHost } from './planModeController.svelte'
|
||||
@@ -465,7 +469,7 @@ function refreshFreeTierUsage(workspace: string | undefined) {
|
||||
* context snapshot always move together so a flush can't drop one. */
|
||||
type QueuedEntry = {
|
||||
draft: DraftSnapshot
|
||||
context: ContextElement[] | undefined
|
||||
context: ContextElement[]
|
||||
}
|
||||
|
||||
/** Plan mode's view of the chat it runs in. A function rather than an object literal in the
|
||||
@@ -531,7 +535,6 @@ export class AIChatManager implements ChatViewHost {
|
||||
/** Markdown artifacts the copilot created for the current session. */
|
||||
artifacts = new SessionArtifactsStore()
|
||||
abortController: AbortController | undefined = undefined
|
||||
inlineAbortController: AbortController | undefined = undefined
|
||||
// Flag to skip Responses API if it's not available (e.g., Azure region doesn't support it)
|
||||
skipResponsesApi = $state(false)
|
||||
|
||||
@@ -685,6 +688,8 @@ export class AIChatManager implements ChatViewHost {
|
||||
* mounts of it each reorder the schema SchemaForm edits in place. */
|
||||
isRunFormTabOpen?: (toolCallId: string) => boolean
|
||||
openArtifact?: (artifactId: string, name: string, version?: ArtifactVersionTarget) => void
|
||||
/** Show an image in the session's preview panel. Set by a session runtime only. */
|
||||
openImage?: (source: ImageSource, label: string) => void
|
||||
closeArtifact?: (artifactId: string) => void
|
||||
#loading = $state<boolean>(false)
|
||||
get loading(): boolean {
|
||||
@@ -790,7 +795,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
/** Images buffered by tools (e.g. take_screenshot) during the current tool batch,
|
||||
* keyed by toolId. Drained by appendPendingToolImages into a follow-up user message
|
||||
* after the batch. Cleared at each turn start so an aborted batch can't leak. */
|
||||
private pendingToolImages = new Map<string, AttachedImage[]>()
|
||||
private pendingToolImages = new Map<string, ToolImage[]>()
|
||||
/** Model of the most recent loop iteration, recorded via onBeforeIteration.
|
||||
* The selector stays switchable mid-flight, so when a request fails neither
|
||||
* the send-time nor the currently-selected model necessarily names the one
|
||||
@@ -841,6 +846,13 @@ export class AIChatManager implements ChatViewHost {
|
||||
* Set before `moving`, which waits for the editors to hand over their pending edits. */
|
||||
moveStarted = $state(false)
|
||||
onWorkModeChanged: ((mode: AIWorkMode) => void) | undefined = undefined
|
||||
/** The model and effort the session record holds. Unset outside sessions. */
|
||||
modelPickResolver: (() => ReasoningProviderModel | undefined) | undefined = undefined
|
||||
onModelPicked: ((model: ReasoningProviderModel) => void) | undefined = undefined
|
||||
/** `replaced`: the pick `model` stands in for, when the workspace does not offer it. */
|
||||
onModelSettled:
|
||||
| ((model: ReasoningProviderModel, replaced: ReasoningProviderModel | undefined) => void)
|
||||
| undefined = undefined
|
||||
/** The protected workspace the session was opted into working in directly (`direct_in`). */
|
||||
directInResolver: (() => string | undefined) | undefined = undefined
|
||||
get directIn(): string | undefined {
|
||||
@@ -926,9 +938,9 @@ export class AIChatManager implements ChatViewHost {
|
||||
...(this.workModesAvailable && !this.#useOnly ? Object.values(this.#workModeSwitches) : [])
|
||||
])
|
||||
)
|
||||
// A getter: the manager is built while the tool modules that lookupTools.ts imports still load.
|
||||
get lookupTools(): LookupTools {
|
||||
return chatLookupTools()
|
||||
// A getter: the manager is built while the tool modules that groupingTools.ts imports still load.
|
||||
get groupingTools(): GroupingTools {
|
||||
return chatGroupingTools()
|
||||
}
|
||||
/** Whether a tool the call was made with is no longer shipped: a switch to Use withdraws
|
||||
* every write while its card waits. The mode transitions are not assembled, so never are. */
|
||||
@@ -992,6 +1004,22 @@ export class AIChatManager implements ChatViewHost {
|
||||
{ resolve: (value: boolean) => void; toolName?: string }
|
||||
>()
|
||||
private userQuestionCallbacks = new Map<string, (choices: string[] | undefined) => void>()
|
||||
// An open secret card. The manager runs its save, so it alone settles it: the card is a
|
||||
// form, and Stop cannot withdraw a save already sent.
|
||||
#secretRequests = new Map<
|
||||
string,
|
||||
{
|
||||
request: SecretRequest
|
||||
resolve: (outcome: SecretRequestOutcome | undefined) => void
|
||||
save?: Promise<void>
|
||||
/** What a refused or failed try already wrote, which a retry updates. */
|
||||
own: Set<string>
|
||||
/** Saved, but its connection check failed: the card stays open to retry or keep it. */
|
||||
saved?: SecretRequestOutcome
|
||||
/** The turn stopped while the save was in flight. */
|
||||
stopped?: boolean
|
||||
}
|
||||
>()
|
||||
// Kept apart from confirmationCallbacks: YOLO answers those, and never answers these.
|
||||
// Resolved undefined when the turn stops first.
|
||||
private scopeCallbacks = new Map<string, (decision: ScopeDecision | undefined) => void>()
|
||||
@@ -1161,10 +1189,28 @@ export class AIChatManager implements ChatViewHost {
|
||||
}
|
||||
|
||||
get currentModel(): ReasoningProviderModel | undefined {
|
||||
// Subscribes only: the model helpers read through `get()`, which tracks nothing.
|
||||
void this.#sessionModel.current
|
||||
const info = this.aiInfo
|
||||
return info && tryResolveModelFor(info)
|
||||
return info && tryResolveModelFor(info, this.#modelPick)
|
||||
}
|
||||
|
||||
/** A session's own once it has one, so that a pick in another chat never moves it. */
|
||||
get #modelPick(): ReasoningProviderModel | undefined {
|
||||
return this.modelPickResolver?.() ?? this.#sessionModel.current
|
||||
}
|
||||
|
||||
/** The user picks `model` for this chat. It is also the one new sessions start on. */
|
||||
pickModel = (model: ReasoningProviderModel) => {
|
||||
this.onModelPicked?.(model)
|
||||
setLastModelPick(model)
|
||||
}
|
||||
|
||||
/** Pins a session to the model it sends with, so that nothing but a pick moves it from here on.
|
||||
* A pick its workspace does not offer is replaced for good: offered again, it stays replaced. */
|
||||
#settleModel() {
|
||||
const own = this.modelPickResolver?.()
|
||||
const model = this.currentModel
|
||||
if (!model || (own?.model === model.model && own.provider === model.provider)) return
|
||||
this.onModelSettled?.(model, own)
|
||||
}
|
||||
|
||||
/** Resolved at each request, after any fork commit. Undefined for other chats, whose requests
|
||||
@@ -1935,7 +1981,11 @@ export class AIChatManager implements ChatViewHost {
|
||||
{ role: 'user', content: getCompactionSummaryPrompt() }
|
||||
],
|
||||
abortController,
|
||||
{ maxTokensCap: SUMMARY_OUTPUT_RESERVE_TOKENS, ...target }
|
||||
{
|
||||
maxTokensCap: SUMMARY_OUTPUT_RESERVE_TOKENS,
|
||||
...target,
|
||||
forceModelProvider: target && resolveModelFor(target.info, this.#modelPick)
|
||||
}
|
||||
)
|
||||
const formatted = formatCompactSummary(raw)
|
||||
if (!formatted) {
|
||||
@@ -2190,6 +2240,9 @@ export class AIChatManager implements ChatViewHost {
|
||||
this.loading = true
|
||||
let result: 'ok' | 'empty' | 'aborted' | 'error' = 'error'
|
||||
try {
|
||||
// A failed load is reported by the summary request, which needs it too.
|
||||
await this.sessionAiTarget().catch(() => {})
|
||||
this.#settleModel()
|
||||
// Everything is the prefix, nothing is kept verbatim: keepFrom and
|
||||
// displayKeepFrom point past the end so the kept tail is empty.
|
||||
result = await this.runSummarization(
|
||||
@@ -2451,6 +2504,113 @@ export class AIChatManager implements ChatViewHost {
|
||||
return true
|
||||
}
|
||||
|
||||
requestSecret = (
|
||||
toolId: string,
|
||||
request: SecretRequest
|
||||
): Promise<SecretRequestOutcome | undefined> => {
|
||||
return new Promise((resolve) => {
|
||||
this.#secretRequests.set(toolId, { request, resolve, own: new Set() })
|
||||
// The tool checks the path before it asks, so a stop during that check has already
|
||||
// settled every open request: this one would park the turn for good.
|
||||
if (this.abortController?.signal.aborted) void this.#settleSecretRequest(toolId, undefined)
|
||||
})
|
||||
}
|
||||
|
||||
/** Saves the value the user typed on the card. Rejects with the server's refusal, which the
|
||||
* card shows; the request stays open for another try. */
|
||||
saveSecret = (toolId: string, submission: SecretSubmission): Promise<void> => {
|
||||
const entry = this.#secretRequests.get(toolId)
|
||||
if (!entry) return Promise.reject(new Error('This request is no longer open.'))
|
||||
if (entry.save) return entry.save
|
||||
const { request } = entry
|
||||
const save = (async () => {
|
||||
const saved = await saveSecretRequest(request, submission, entry.own)
|
||||
const check = await checkSubmission(request, submission)
|
||||
const outcome = check ? { ...saved, check } : saved
|
||||
if (check && !check.ok && !entry.stopped) {
|
||||
entry.saved = outcome
|
||||
throw new SecretCheckFailed(check.error)
|
||||
}
|
||||
return this.#settleSecretRequest(toolId, outcome)
|
||||
})().catch((e) => {
|
||||
entry.save = undefined
|
||||
if (entry.stopped) void this.#settleSecretRequest(toolId, entry.saved)
|
||||
throw e
|
||||
})
|
||||
entry.save = save
|
||||
return save
|
||||
}
|
||||
|
||||
dismissSecret = (toolId: string): void => {
|
||||
const entry = this.#secretRequests.get(toolId)
|
||||
// After a failed check the resource exists: dismissing keeps it, as the card says.
|
||||
if (entry && !entry.save) void this.#settleSecretRequest(toolId, entry.saved)
|
||||
}
|
||||
|
||||
/** The one writer of a settled secret card. In a live turn the tool then returns the outcome
|
||||
* to the model. After a stop the turn is gone, so a save that lands then is told on the
|
||||
* model's next turn, as a detached job's result is, and written to this chat's history. */
|
||||
#settleSecretRequest(toolId: string, outcome: SecretRequestOutcome | undefined): Promise<void> {
|
||||
const entry = this.#secretRequests.get(toolId)
|
||||
if (!entry) return Promise.resolve()
|
||||
this.#secretRequests.delete(toolId)
|
||||
const { label } = entry.request
|
||||
this.displayMessages = this.displayMessages.map((m) =>
|
||||
m.role === 'tool' && m.tool_call_id === toolId && m.secretRequest
|
||||
? {
|
||||
...m,
|
||||
error: undefined,
|
||||
isLoading: false,
|
||||
content: outcome
|
||||
? entry.request.resource
|
||||
? `Saved ${label} as a draft of ${outcome.path}${outcome.check ? (outcome.check.ok ? ' · test passed' : ' · test failed') : ''}`
|
||||
: `Saved ${label} as a draft of ${outcome.path}`
|
||||
: `Asked for ${label} — dismissed`,
|
||||
secretRequest: outcome
|
||||
? { ...m.secretRequest, saving: false, saved: outcome }
|
||||
: { ...m.secretRequest, saving: false, canceled: true }
|
||||
}
|
||||
: m
|
||||
)
|
||||
// The drafts the card saved are this session's changes, deployed from its panel, whether
|
||||
// they landed during the turn or after it stopped.
|
||||
if (outcome) {
|
||||
for (const variable of outcome.variables) this.recordModifiedItem('variable', variable)
|
||||
if (entry.request.resource) this.recordModifiedItem('resource', outcome.path)
|
||||
}
|
||||
if (!entry.stopped) {
|
||||
entry.resolve(outcome)
|
||||
return Promise.resolve()
|
||||
}
|
||||
const note = outcome
|
||||
? this.queueModelNote(
|
||||
entry.request.resource
|
||||
? `The user saved ${label} after the turn stopped: it is a draft of the resource ${outcome.path}, referenced as "$res:${outcome.path}", with its secrets in drafts of ${outcome.variables.join(', ')}.${checkText(outcome)} Nothing is deployed, so no run can read it until it is.`
|
||||
: `The user's ${label} was saved after the turn stopped: it is a draft of the secret variable ${outcome.path}, referenced as "$var:${outcome.path}". Nothing is deployed, so no run can read it until it is.`
|
||||
)
|
||||
: Promise.resolve()
|
||||
// The variable is saved whatever happens here, so a failed write must not reach the card.
|
||||
const written = note
|
||||
.then(async () => {
|
||||
await Promise.all([this.#persistBackgroundJobs(), this.#persistModifiedItems()])
|
||||
})
|
||||
.catch((e) => console.error('Failed to persist a secret saved after stop', e))
|
||||
this.#lateSecretWrites.add(written)
|
||||
void written.finally(() => this.#lateSecretWrites.delete(written))
|
||||
return written
|
||||
}
|
||||
|
||||
// Written into the conversation on screen, so a chat switch waits for them.
|
||||
#lateSecretWrites = new Set<Promise<void>>()
|
||||
|
||||
/** Lets every in-flight secret save land and be written to this chat. */
|
||||
#secretSavesLanded(): Promise<unknown> {
|
||||
return Promise.allSettled([
|
||||
...[...this.#secretRequests.values()].flatMap((entry) => (entry.save ? [entry.save] : [])),
|
||||
...this.#lateSecretWrites
|
||||
])
|
||||
}
|
||||
|
||||
requestRunArgs = (
|
||||
toolId: string,
|
||||
form: RunFormDisplay,
|
||||
@@ -2720,7 +2880,8 @@ export class AIChatManager implements ChatViewHost {
|
||||
#takeQueue(): QueuedEntry {
|
||||
const taken = {
|
||||
draft: this.#queuedDraft.take(),
|
||||
context: this.queuedContext
|
||||
// Not undefined, which would send the live selection: that of the next message.
|
||||
context: this.queuedContext ?? []
|
||||
}
|
||||
this.queuedContext = undefined
|
||||
this.#queueSendsMidTurnIn = undefined
|
||||
@@ -2752,7 +2913,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
images: queued.draft.images,
|
||||
files: queued.draft.files
|
||||
})
|
||||
if (queued.context?.length) {
|
||||
if (queued.context.length) {
|
||||
const merged = [...queued.context]
|
||||
for (const c of this.queuedContext ?? []) {
|
||||
if (!merged.some((m) => isSameContextElement(m, c))) {
|
||||
@@ -2763,33 +2924,23 @@ export class AIChatManager implements ChatViewHost {
|
||||
}
|
||||
}
|
||||
|
||||
/** Put a draft's pinned DOM selector chips back as the live selection, so the
|
||||
* restored draft and the selection stay coherent (its instruction targets the
|
||||
* element it was written for). No-op when the draft pinned no DOM chips, so a
|
||||
* plain-text draft leaves the live selection untouched.
|
||||
/** Put a draft's pinned picks back as the live selection, so the restored draft and the
|
||||
* selection stay coherent (its instruction targets what it was written for). No-op when
|
||||
* the draft pinned none, so a plain-text draft leaves the live selection untouched.
|
||||
*
|
||||
* `keepExisting` when the restored text was merged into a draft the user was
|
||||
* already writing: that draft's own chips must survive alongside, or its
|
||||
* instruction — still sitting in the composer — would be retargeted at this
|
||||
* draft's element. Otherwise the restore replaces, since any chip selected
|
||||
* since belongs to a draft that is being replaced too. */
|
||||
#restoreDomContext(context: ContextElement[] | undefined, keepExisting = false) {
|
||||
const domChips = (context ?? []).filter((c) => c.type === 'app_dom_selector')
|
||||
if (domChips.length === 0) return
|
||||
const existing = keepExisting
|
||||
? (this.contextManager?.getSelectedContext().filter((c) => c.type === 'app_dom_selector') ??
|
||||
[])
|
||||
: []
|
||||
this.contextManager?.clearSelectedDomElements()
|
||||
// addSelectedDomElement dedups on (selector, appPath), so a chip both drafts
|
||||
// share collapses to one.
|
||||
for (const c of [...domChips, ...existing]) {
|
||||
this.contextManager?.addSelectedDomElement(c)
|
||||
}
|
||||
* instruction, still sitting in the composer, would be retargeted at this
|
||||
* draft's pick. Otherwise the restore replaces preview elements, since any
|
||||
* selected since belongs to a draft that is being replaced too. */
|
||||
#restorePickContext(context: ContextElement[] | undefined, keepExisting = false) {
|
||||
const picks = (context ?? []).filter(isPickContext)
|
||||
if (picks.length === 0) return
|
||||
this.contextManager?.restorePickContext(picks, keepExisting)
|
||||
}
|
||||
|
||||
/** Give back the mentions a send carried when its text returns to the composer,
|
||||
* so its `@` tokens still have entries to bind to. Additive, unlike the DOM
|
||||
* so its `@` tokens still have entries to bind to. Additive, unlike the pick
|
||||
* restore above: dropping the entries this send did not carry would strand the
|
||||
* tokens naming them in a draft whose text now shares the same composer.
|
||||
*
|
||||
@@ -2815,7 +2966,9 @@ export class AIChatManager implements ChatViewHost {
|
||||
*
|
||||
* Gated on `sendInFlight` as well as `loading`: `loading` only rises after a
|
||||
* send's attachment upkeep, so between the two a click would slip past. */
|
||||
sendOrQueue(text: string, context?: ContextElement[]) {
|
||||
sendOrQueue(text: string, picks: PickContext[] = []) {
|
||||
// The composer's own picks stay there: they belong to the draft being written in it.
|
||||
const context = [...this.#contextWithoutPicks(), ...picks]
|
||||
if (this.loading || this.sendInFlight || this.sendPending) {
|
||||
this.queueMessage(text, [], context)
|
||||
return
|
||||
@@ -2823,6 +2976,10 @@ export class AIChatManager implements ChatViewHost {
|
||||
void this.sendRequest({ instructions: text, contextOverride: context })
|
||||
}
|
||||
|
||||
#contextWithoutPicks(): ContextElement[] {
|
||||
return this.contextManager.getSelectedContext().filter((c) => !isPickContext(c))
|
||||
}
|
||||
|
||||
/** Remove the queued message and put it back into the input, images included. */
|
||||
dequeueMessage() {
|
||||
if (!this.#hasQueuedMessage()) {
|
||||
@@ -2838,27 +2995,31 @@ export class AIChatManager implements ChatViewHost {
|
||||
// the composer targets the element the draft was written for, not whatever
|
||||
// is selected now. If its text was prepended onto an existing draft, that
|
||||
// draft's chips are kept too — both instructions now share one composer.
|
||||
this.#restoreDomContext(queued.context, mergedIntoDraft)
|
||||
this.#restorePickContext(queued.context, mergedIntoDraft)
|
||||
// The queue aggregates several enqueues into one entry and records no
|
||||
// originating mode, so the mode now is the closest signal available. A
|
||||
// recall after a mid-turn mode switch can therefore miss a restore.
|
||||
this.#restoreMentionContext(queued.context, this.mode)
|
||||
}
|
||||
|
||||
/** Put what the user typed back where they can see it: into the input
|
||||
* when it's mounted, otherwise back into the queue so it reappears with
|
||||
* the chat panel instead of being silently dropped. */
|
||||
/** Put what the user typed back where they can see it, with its picks: into the input
|
||||
* when it's mounted, beside the picks there, otherwise back into the queue so it reappears
|
||||
* with the chat panel instead of being silently dropped. */
|
||||
private restoreToInput(
|
||||
text: string,
|
||||
images: AttachedImage[] = [],
|
||||
files: AttachedTextFile[] = []
|
||||
files: AttachedTextFile[] = [],
|
||||
context: ContextElement[] = []
|
||||
): boolean {
|
||||
if (this.aiChatInput) {
|
||||
return this.aiChatInput.prependText(text, images, files) === true
|
||||
const mergedIntoDraft = this.aiChatInput.prependText(text, images, files) === true
|
||||
this.#restorePickContext(context, true)
|
||||
return mergedIntoDraft
|
||||
}
|
||||
// Merge onto anything already queued (see #restoreQueue) — replacing would
|
||||
// silently drop a message queued while this one was in flight.
|
||||
this.#queuedDraft.prepend({ text, images, files })
|
||||
const draft = { text, images, files, pastes: [], blobs: [] }
|
||||
this.#restoreQueue({ draft, context })
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -3037,7 +3198,8 @@ export class AIChatManager implements ChatViewHost {
|
||||
artifacts: this.artifacts,
|
||||
access: this.#toolAccess,
|
||||
getChatId: () => this.historyManager.getCurrentChatId(),
|
||||
openArtifact: this.openArtifact
|
||||
openArtifact: this.openArtifact,
|
||||
openImage: this.openImage
|
||||
}
|
||||
: {}),
|
||||
testActiveFlow: async (storagePath: string, args?: Record<string, any>, memoryId?: string) =>
|
||||
@@ -3432,29 +3594,28 @@ export class AIChatManager implements ChatViewHost {
|
||||
}
|
||||
}
|
||||
|
||||
// Roll a turn that produced nothing usable back out of the transcript and
|
||||
// hand its text back to the composer for editing/resending. `restoreToInput`
|
||||
// is false when a queued message is about to take over (a user cancel with
|
||||
// something queued) — then the rolled-back prompt is dropped rather than
|
||||
// shoved back into the input, so the handoff to the queued message is clean.
|
||||
private restoreUnsentTurn = async (
|
||||
displayLenAfterUser: number,
|
||||
modelLenAfterUser: number,
|
||||
instructions: string,
|
||||
pastes: PasteAttachment[],
|
||||
restoreToInput: boolean = true,
|
||||
images: AttachedImage[] = [],
|
||||
files: AttachedTextFile[] = []
|
||||
): Promise<boolean> => {
|
||||
/** Hand a rolled-back message back to the composer with its picks and mentions, or with none
|
||||
* of them: on a draft that declined the text, they would retarget what is being written. */
|
||||
#returnToComposer(
|
||||
draft: Pick<DraftSnapshot, 'text' | 'pastes' | 'images' | 'files'>,
|
||||
context: ContextElement[] | undefined,
|
||||
originMode: AIMode,
|
||||
{ replacePicks = false } = {}
|
||||
) {
|
||||
const { text, pastes, images, files } = draft
|
||||
if (!this.aiChatInput?.restoreInstructions(text, pastes, images, files)) return
|
||||
this.#restorePickContext(context, !replacePicks)
|
||||
this.#restoreMentionContext(context, originMode)
|
||||
}
|
||||
|
||||
// Roll a turn that produced nothing usable back out of the transcript.
|
||||
#dropUnsentTurn(displayLenAfterUser: number, modelLenAfterUser: number) {
|
||||
this.displayMessages = this.displayMessages.slice(0, displayLenAfterUser - 1)
|
||||
this.messages = this.messages.slice(0, modelLenAfterUser - 1)
|
||||
// The rolled-back turn's files must not stay registered: the message
|
||||
// referencing them is gone, so leaving them would keep stale content
|
||||
// readable by the tools on later turns.
|
||||
this.#syncMessageFiles()
|
||||
if (!restoreToInput) return false
|
||||
// An occupied composer declines the restore and keeps its own draft.
|
||||
return this.aiChatInput?.restoreInstructions(instructions, pastes, images, files) === true
|
||||
}
|
||||
|
||||
// Bytes each live composer has staged toward its next send (committed
|
||||
@@ -3664,7 +3825,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
abortController,
|
||||
callbacks,
|
||||
get modelProvider() {
|
||||
return info ? resolveModelFor(info) : getCurrentModel()
|
||||
return info ? resolveModelFor(info, self.#modelPick) : getCurrentModel()
|
||||
},
|
||||
get webSearch() {
|
||||
return isWebSearchEnabledForProvider(this.modelProvider.provider, info)
|
||||
@@ -3751,92 +3912,6 @@ export class AIChatManager implements ChatViewHost {
|
||||
}
|
||||
}
|
||||
|
||||
sendInlineRequest = async (instructions: string, selectedCode: string, selection: Selection) => {
|
||||
// Validate inputs
|
||||
if (!instructions.trim()) {
|
||||
throw new Error('Instructions are required')
|
||||
}
|
||||
// Use a separate abort controller for inline requests to avoid interfering with main chat
|
||||
this.inlineAbortController = new AbortController()
|
||||
const lang = this.scriptEditorOptions?.lang ?? 'bun'
|
||||
const selectedContext: ContextElement[] = [...this.contextManager.getSelectedContext()]
|
||||
const startLine = selection.startLineNumber
|
||||
const endLine = selection.endLineNumber
|
||||
selectedContext.push({
|
||||
type: 'code_piece',
|
||||
lang,
|
||||
title: `L${startLine}-L${endLine}`,
|
||||
startLine,
|
||||
endLine,
|
||||
content: selectedCode
|
||||
})
|
||||
|
||||
const systemMessage: ChatCompletionSystemMessageParam = {
|
||||
role: 'system',
|
||||
content: prepareInlineChatSystemPrompt(lang, {
|
||||
workflowAsCode: this.scriptEditorOptions?.workflowAsCode ?? false
|
||||
})
|
||||
}
|
||||
|
||||
let reply = ''
|
||||
|
||||
try {
|
||||
const userMessage = prepareScriptUserMessage(instructions, selectedContext)
|
||||
const messages = [userMessage]
|
||||
|
||||
const params = {
|
||||
messages,
|
||||
abortController: this.inlineAbortController,
|
||||
callbacks: {
|
||||
onNewToken: (token: string) => {
|
||||
reply += token
|
||||
},
|
||||
onMessageEnd: () => {},
|
||||
setToolStatus: () => {},
|
||||
removeToolStatus: () => {}
|
||||
},
|
||||
systemMessage
|
||||
}
|
||||
|
||||
await this.chatRequest({ ...params })
|
||||
|
||||
// Validate we received a response
|
||||
if (!reply.trim()) {
|
||||
throw new Error('AI response was empty')
|
||||
}
|
||||
|
||||
// Try to extract new code from response
|
||||
const newCodeMatch = reply.match(/<new_code>([\s\S]*?)<\/new_code>/i)
|
||||
if (newCodeMatch && newCodeMatch[1]) {
|
||||
const code = newCodeMatch[1].trim()
|
||||
if (!code) {
|
||||
throw new Error('AI response contained empty code block')
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
// Fallback: try to take everything after the last <new_code> tag
|
||||
const lastNewCodeMatch = reply.match(/<new_code>([\s\S]*)/i)
|
||||
if (lastNewCodeMatch && lastNewCodeMatch[1]) {
|
||||
const code = lastNewCodeMatch[1].trim().replace(/```/g, '')
|
||||
if (!code) {
|
||||
throw new Error('AI response contained empty code block')
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
// If no code tags found, throw error with helpful message
|
||||
throw new Error('AI response did not contain valid code. Please try rephrasing your request.')
|
||||
} catch (error) {
|
||||
// if abort controller is aborted, don't throw an error
|
||||
if (this.inlineAbortController?.signal.aborted) {
|
||||
return
|
||||
}
|
||||
console.error('Unexpected error in sendInlineRequest:', error)
|
||||
throw new Error('An unexpected error occurred. Please try again.')
|
||||
}
|
||||
}
|
||||
|
||||
// Optional pre-flight hook called once per send, after the user's message
|
||||
// bubble + loading indicator are shown optimistically but before the request
|
||||
// goes out. Sessions use this to commit/materialise the workspace (creating a
|
||||
@@ -3850,6 +3925,8 @@ export class AIChatManager implements ChatViewHost {
|
||||
* Counted, not boolean: a send recursively flushes queued messages, and the
|
||||
* inner one finishing doesn't mean the outer is done. */
|
||||
#sendsInFlight = $state(0)
|
||||
/** Every send ever started, for telling whether one began during an await. */
|
||||
#sendsStarted = 0
|
||||
get sendInFlight(): boolean {
|
||||
return this.#sendsInFlight > 0
|
||||
}
|
||||
@@ -3952,13 +4029,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const { draft, context = [] } = this.#takeQueue()
|
||||
// Pinned at enqueue, so consumed from the live selection as any pinned send does.
|
||||
for (const c of context) {
|
||||
if (c.type === 'app_dom_selector') {
|
||||
this.contextManager?.removeSelectedDomElement(c.selector, c.appPath)
|
||||
}
|
||||
}
|
||||
const { draft, context } = this.#takeQueue()
|
||||
if (this.mode === AIMode.SCRIPT || this.mode === AIMode.FLOW) {
|
||||
this.contextManager?.updateContextOnRequest({})
|
||||
}
|
||||
@@ -3997,6 +4068,10 @@ export class AIChatManager implements ChatViewHost {
|
||||
}
|
||||
|
||||
sendRequest = async (options: Parameters<typeof this.sendRequestImpl>[0] = {}) => {
|
||||
// Before any await, during which a pick in another session would move this one. Again once
|
||||
// the workspace is committed, which may not offer this model. Not while another tab runs the
|
||||
// session: storing the record here would overwrite what that tab stored.
|
||||
if (!this.runHeldElsewhere) this.#settleModel()
|
||||
if (this.#ready) {
|
||||
this.#sendsAwaitingReady++
|
||||
try {
|
||||
@@ -4008,8 +4083,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
}
|
||||
// The shared manager has no chat on screen: turns render only in a session's own chat.
|
||||
// One started here would still stream, spend tokens and apply tool calls, entirely
|
||||
// off-screen, so refuse it. `sendInlineRequest` is exempt: the ⌘K widget renders its own
|
||||
// composer inside Monaco.
|
||||
// off-screen, so refuse it.
|
||||
if (this === aiChatManager) {
|
||||
console.error('sendRequest called with no chat UI mounted; dropping the turn')
|
||||
sendUserToast('This action needs the AI chat. Start an AI session to continue.', true)
|
||||
@@ -4045,7 +4119,8 @@ export class AIChatManager implements ChatViewHost {
|
||||
this.restoreToInput(
|
||||
expanded(chatDraft(options.instructions ?? this.instructions, options.pastes ?? [])),
|
||||
options.images,
|
||||
options.files
|
||||
options.files,
|
||||
options.contextOverride
|
||||
)
|
||||
}
|
||||
sendUserToast(
|
||||
@@ -4058,6 +4133,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
return false
|
||||
}
|
||||
this.#sendsInFlight++
|
||||
this.#sendsStarted++
|
||||
try {
|
||||
return await this.sendRequestImpl(options)
|
||||
} finally {
|
||||
@@ -4080,12 +4156,6 @@ export class AIChatManager implements ChatViewHost {
|
||||
// contextManager. Set whenever a send settles its context ahead of the
|
||||
// turn: a composer submit at the click, a queued message at enqueue.
|
||||
contextOverride?: ContextElement[]
|
||||
/** Where `contextOverride` came from. 'pinned' (default): the chips were
|
||||
* selected for THIS message, so they are consumed from the live selection
|
||||
* on send. 'replay': an edit/retry resending an older message's context —
|
||||
* those chips were consumed long ago, and removing them again would strip
|
||||
* an identical selection the user has since made in the composer. */
|
||||
contextOverrideOrigin?: 'pinned' | 'replay'
|
||||
/** Auto-send of a queued draft: on preflight failure the caller re-queues
|
||||
* it, so the composer restore must not also fire (the draft would exist
|
||||
* twice — queue chip and composer). */
|
||||
@@ -4159,6 +4229,8 @@ export class AIChatManager implements ChatViewHost {
|
||||
// resolved to `/clear` or `/compact` must not strand its resend reservation.
|
||||
if (COMPACT_COMMAND_RE.test(trimmed) || CLEAR_COMMAND_RE.test(trimmed)) {
|
||||
this.#releaseOutgoingReservation(reservationKey)
|
||||
// It carries no pick either.
|
||||
this.#restorePickContext(options.contextOverride, true)
|
||||
}
|
||||
// `/compact`: summarize the conversation locally to free up context.
|
||||
if (COMPACT_COMMAND_RE.test(trimmed)) {
|
||||
@@ -4228,17 +4300,16 @@ export class AIChatManager implements ChatViewHost {
|
||||
// restore is keyed to requestedMode: a GLOBAL submit whose mode
|
||||
// flipped during the upkeep awaits above still gets its mentions
|
||||
// back, while a send that started outside GLOBAL consumed none.
|
||||
const taken =
|
||||
this.aiChatInput?.restoreInstructions(
|
||||
this.instructions,
|
||||
this.#returnToComposer(
|
||||
{
|
||||
text: this.instructions,
|
||||
pastes,
|
||||
options.images ?? [],
|
||||
options.files ?? []
|
||||
) === true
|
||||
if (taken) {
|
||||
this.#restoreDomContext(options.contextOverride, true)
|
||||
this.#restoreMentionContext(options.contextOverride, requestedMode)
|
||||
}
|
||||
images: options.images ?? [],
|
||||
files: options.files ?? []
|
||||
},
|
||||
options.contextOverride,
|
||||
requestedMode
|
||||
)
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -4266,7 +4337,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
// that does not write a token would break that and need one here.
|
||||
if (!this.instructions.trim() && files.length === 0) {
|
||||
sendUserToast(`${sendModel.model} can't read images. Switch to a vision model first.`, true)
|
||||
if (!options.queued) this.restoreToInput('', requestedImages)
|
||||
if (!options.queued) this.restoreToInput('', requestedImages, [], options.contextOverride)
|
||||
return false
|
||||
}
|
||||
sendUserToast(
|
||||
@@ -4291,7 +4362,12 @@ export class AIChatManager implements ChatViewHost {
|
||||
// awaits above occupies the composer, and this restore must merge
|
||||
// into it (or queue), never be refused by it.
|
||||
if (!options.queued) {
|
||||
this.restoreToInput(expanded(chatDraft(this.instructions, pastes)), images, files)
|
||||
this.restoreToInput(
|
||||
expanded(chatDraft(this.instructions, pastes)),
|
||||
images,
|
||||
files,
|
||||
options.contextOverride
|
||||
)
|
||||
}
|
||||
sendUserToast('This session is running in another tab. Your message was kept.', true)
|
||||
}
|
||||
@@ -4349,16 +4425,11 @@ export class AIChatManager implements ChatViewHost {
|
||||
console.error('AIChatManager beforeSend hook failed', e)
|
||||
rollbackOptimisticSend()
|
||||
if (!options.queued) {
|
||||
// Mentions were consumed at submit, so they come back with the text or
|
||||
// not at all. Only when the composer took it: it declines when the
|
||||
// user has started a new draft, and restoring then would put these
|
||||
// mentions on that draft and every turn after it.
|
||||
const taken =
|
||||
this.aiChatInput?.restoreInstructions(this.instructions, pastes, images, files) === true
|
||||
if (taken) {
|
||||
this.#restoreDomContext(options.contextOverride, true)
|
||||
this.#restoreMentionContext(options.contextOverride, requestedMode)
|
||||
}
|
||||
this.#returnToComposer(
|
||||
{ text: this.instructions, pastes, images, files },
|
||||
options.contextOverride,
|
||||
requestedMode
|
||||
)
|
||||
}
|
||||
sendUserToast(
|
||||
`Could not prepare the session before sending: ${
|
||||
@@ -4416,14 +4487,11 @@ export class AIChatManager implements ChatViewHost {
|
||||
})
|
||||
if (accepted === false) this.#restoreQueue(next)
|
||||
} else {
|
||||
// Same pairing as the beforeSend catch above: mentions ride back with the
|
||||
// text, only if the composer took it.
|
||||
const taken =
|
||||
this.aiChatInput?.restoreInstructions(this.instructions, pastes, images, files) === true
|
||||
if (taken) {
|
||||
this.#restoreDomContext(options.contextOverride, true)
|
||||
this.#restoreMentionContext(options.contextOverride, requestedMode)
|
||||
}
|
||||
this.#returnToComposer(
|
||||
{ text: this.instructions, pastes, images, files },
|
||||
options.contextOverride,
|
||||
requestedMode
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -4524,27 +4592,16 @@ export class AIChatManager implements ChatViewHost {
|
||||
// it belongs to whatever the user has selected since. Otherwise read the
|
||||
// current selection.
|
||||
const oldSelectedContext =
|
||||
options.contextOverride ?? this.contextManager?.getSelectedContext() ?? []
|
||||
// DOM selector chips are one-shot: they ride with this message (captured in
|
||||
options.contextOverride ??
|
||||
(options.synthetic
|
||||
? this.#contextWithoutPicks()
|
||||
: (this.contextManager?.getSelectedContext() ?? []))
|
||||
// Pick chips are one-shot: they ride with this message (captured in
|
||||
// oldSelectedContext) and render above it, but must not persist in the input
|
||||
// for the next turn. Clearing here leaves oldSelectedContext untouched.
|
||||
if (options.contextOverrideOrigin === 'replay') {
|
||||
// Edit/retry: the override is a copy of an already-sent message's
|
||||
// context, consumed on its original send. The live selection belongs to
|
||||
// the composer's own draft — touching it here would strip it.
|
||||
} else if (options.contextOverride) {
|
||||
// A pinned submit consumes only the chips it carried. Drop just those
|
||||
// from the live selection (still there if the user didn't re-select); a
|
||||
// newer selection made since is left intact.
|
||||
for (const c of options.contextOverride) {
|
||||
if (c.type === 'app_dom_selector') {
|
||||
// Match appPath too: another app's live chip can share this
|
||||
// selector, and dropping it would discard a newer selection.
|
||||
this.contextManager?.removeSelectedDomElement(c.selector, c.appPath)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.contextManager?.clearSelectedDomElements()
|
||||
// for the next turn. Whoever pinned a snapshot has already taken them out: what
|
||||
// is live then, or when the client sends, is the composer's next message's.
|
||||
if (!options.contextOverride && !options.synthetic) {
|
||||
this.contextManager?.consumePickContext()
|
||||
}
|
||||
if (this.mode === AIMode.SCRIPT || this.mode === AIMode.FLOW) {
|
||||
this.contextManager?.updateContextOnRequest(options)
|
||||
@@ -4552,6 +4609,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
// loading + abortController were set optimistically before beforeSend, above.
|
||||
this.#automaticScroll = true
|
||||
|
||||
this.#settleModel()
|
||||
const model = this.currentModel
|
||||
if (model) {
|
||||
const chatId = this.historyManager.getCurrentChatId()
|
||||
@@ -4624,7 +4682,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
}
|
||||
: m
|
||||
)
|
||||
// For restoreUnsentTurn: the compact composer form (with paste tokens),
|
||||
// For the restore after a rollback: the compact composer form (with paste tokens),
|
||||
// not the expanded LLM text, plus the rollback anchor after the user turn.
|
||||
const sentInstructions = this.instructions
|
||||
const sentPastes = pastes
|
||||
@@ -4703,7 +4761,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
this.modifiedItems ? [...this.modifiedItems] : undefined
|
||||
)
|
||||
}
|
||||
// Rollback anchors for restoreUnsentTurn: captured after compaction so
|
||||
// Rollback anchors for #dropUnsentTurn: captured after compaction so
|
||||
// they index into the (possibly compacted) stored history. The summary
|
||||
// path shrinks displayMessages too, so the display anchor must also be
|
||||
// read here, not before compaction.
|
||||
@@ -4822,6 +4880,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
onToolBlockedByPlanMode: this.planMode.noteBlockedTool,
|
||||
isToolWithdrawn: this.isToolWithdrawn,
|
||||
requestUserQuestion: this.requestUserQuestion,
|
||||
requestSecret: this.requestSecret,
|
||||
requestRunArgs: this.requestRunArgs,
|
||||
markRunFormStarted: this.markRunFormStarted,
|
||||
markRunFormEnded: this.markRunFormEnded,
|
||||
@@ -4937,27 +4996,16 @@ export class AIChatManager implements ChatViewHost {
|
||||
// about to auto-send (see the flush below) — drop the rolled-back
|
||||
// prompt instead of restoring it to the input so the handoff is clean.
|
||||
const willAutoSendQueued = this.wasCancelledByUser() && this.#hasQueuedMessage()
|
||||
const textRestored = await this.restoreUnsentTurn(
|
||||
displayLenAfterUser,
|
||||
modelLenAfterUser,
|
||||
sentInstructions,
|
||||
sentPastes,
|
||||
!willAutoSendQueued,
|
||||
sentImages,
|
||||
files
|
||||
)
|
||||
// restoreUnsentTurn hands the text/pastes/images back for a resend, but
|
||||
// the DOM selector chips were already consumed from the live selection
|
||||
// before the request went out. Restore this turn's own chips so the
|
||||
// resend keeps its element scope — replacing (not merging) any chips
|
||||
// selected during the stream, so the restored draft stays coherent.
|
||||
// Only when the composer actually took the text back: on a queued-message
|
||||
// handoff, or when a draft typed during the stream made the composer
|
||||
// decline, this prompt is dropped — restoring its chips would then
|
||||
// retarget whatever draft is sitting there.
|
||||
if (textRestored) {
|
||||
this.#restoreDomContext(oldSelectedContext)
|
||||
this.#restoreMentionContext(oldSelectedContext, requestedMode)
|
||||
this.#dropUnsentTurn(displayLenAfterUser, modelLenAfterUser)
|
||||
if (!willAutoSendQueued) {
|
||||
// Elements picked during the stream are replaced, so that the restored
|
||||
// draft stays coherent.
|
||||
this.#returnToComposer(
|
||||
{ text: sentInstructions, pastes: sentPastes, images: sentImages, files },
|
||||
oldSelectedContext,
|
||||
requestedMode,
|
||||
{ replacePicks: true }
|
||||
)
|
||||
}
|
||||
if (this.displayMessages.length === 0) {
|
||||
// saveChat no-ops on an empty transcript; the chat persisted earlier
|
||||
@@ -5129,6 +5177,14 @@ export class AIChatManager implements ChatViewHost {
|
||||
resolveQuestion(undefined)
|
||||
}
|
||||
this.userQuestionCallbacks.clear()
|
||||
for (const [toolId, entry] of this.#secretRequests) {
|
||||
// The turn ends now, but the save cannot be withdrawn: settledToolDisplay shows the card
|
||||
// as saving, and the save settles it when it lands.
|
||||
if (entry.save) {
|
||||
entry.stopped = true
|
||||
entry.resolve(undefined)
|
||||
} else void this.#settleSecretRequest(toolId, entry.saved)
|
||||
}
|
||||
for (const [toolId, entry] of this.#runForms) {
|
||||
entry.resolve?.(undefined)
|
||||
// Stopping the turn is the form's other way out, and the draft dies with this loop:
|
||||
@@ -5151,15 +5207,6 @@ export class AIChatManager implements ChatViewHost {
|
||||
this.cancelLoadingTools()
|
||||
}
|
||||
|
||||
cancelInlineRequest = (reason?: string) => {
|
||||
const cancelReason = reason ?? 'inline_cancelled'
|
||||
console.log('cancelling inline request:', {
|
||||
reason: cancelReason,
|
||||
inlineAbortController: this.inlineAbortController
|
||||
})
|
||||
this.inlineAbortController?.abort(cancelReason)
|
||||
}
|
||||
|
||||
/**
|
||||
* The images of a stored user turn as the model saw them. Anything resending
|
||||
* a turn (retry, edit) must read them from here, never from the transcript
|
||||
@@ -5265,16 +5312,15 @@ export class AIChatManager implements ChatViewHost {
|
||||
// the element the message was about. An edit passes `editedContext` (the edit
|
||||
// box was seeded from this message's chips and the user may have changed
|
||||
// them); a bare Retry passes nothing and falls back to the original
|
||||
// contextElements. `undefined` for modes that don't attach context leaves the
|
||||
// live-selection behavior. An empty array is a deliberate "no context".
|
||||
// contextElements. A message stored without any gets an empty array, as `undefined`
|
||||
// would send the live selection, which is the composer's.
|
||||
this.instructions = newContent ?? userMessage.content
|
||||
// Prune the truncated messages' file registrations BEFORE the resend
|
||||
// re-registers its own — the other way around would delete the fresh rows.
|
||||
this.#syncMessageFiles()
|
||||
this.sendRequest({
|
||||
pastes: pastes ?? userMessage.pastes,
|
||||
contextOverride: editedContext ?? userMessage.contextElements,
|
||||
contextOverrideOrigin: 'replay',
|
||||
contextOverride: editedContext ?? userMessage.contextElements ?? [],
|
||||
images: images ?? sentImages,
|
||||
// The bubble copy is authoritative for files: the API message carries
|
||||
// only a reference (content lives in the store), so nothing ever strips
|
||||
@@ -5284,21 +5330,18 @@ export class AIChatManager implements ChatViewHost {
|
||||
})
|
||||
}
|
||||
|
||||
addSelectedLinesToContext = (
|
||||
lines: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
moduleId?: string
|
||||
) => {
|
||||
if (!moduleId) {
|
||||
this.changeMode(AIMode.SCRIPT)
|
||||
}
|
||||
this.contextManager?.addSelectedLinesToContext(lines, startLine, endLine, moduleId)
|
||||
attachCodeSelection(selection: CodeSelection) {
|
||||
this.contextManager.addCodeSelection(selection)
|
||||
this.focusInput()
|
||||
}
|
||||
|
||||
saveAndClear = async () => {
|
||||
this.cancel('saveAndClear')
|
||||
const sends = this.#sendsStarted
|
||||
await this.#secretSavesLanded()
|
||||
// The composer stays open meanwhile, so a turn may have started: it keeps its chat.
|
||||
// Not `sendInFlight`, which `/clear` itself is.
|
||||
if (this.#sendsStarted !== sends) return
|
||||
// Drop any message queued in this conversation so it can't auto-send into
|
||||
// the fresh chat or linger as a card across the switch.
|
||||
this.#clearQueue()
|
||||
@@ -5336,6 +5379,10 @@ export class AIChatManager implements ChatViewHost {
|
||||
// chat already carries the turn's own checkpoint. Gated on `sendInFlight`
|
||||
// too, for the pre-`loading` window `sendOrQueue` documents.
|
||||
if (this.loading || this.sendInFlight) return
|
||||
// A save settles its card in whatever conversation is on screen when it lands.
|
||||
await this.#secretSavesLanded()
|
||||
// The composer stays open meanwhile, so a turn may have started.
|
||||
if (this.loading || this.sendInFlight) return
|
||||
const chat = await this.historyManager.loadPastChat(id)
|
||||
if (chat) {
|
||||
// Drop any message queued in the current conversation so it doesn't
|
||||
@@ -5754,6 +5801,12 @@ export class AIChatManager implements ChatViewHost {
|
||||
userQuestion: message.userQuestion
|
||||
? { ...message.userQuestion, canceled: true }
|
||||
: undefined,
|
||||
secretRequest:
|
||||
message.secretRequest && !message.secretRequest.saved
|
||||
? this.#secretRequests.get(message.tool_call_id)?.save
|
||||
? { ...message.secretRequest, saving: true }
|
||||
: { ...message.secretRequest, canceled: true }
|
||||
: message.secretRequest,
|
||||
runForm: message.runForm
|
||||
? settledRunForm({ ...message.runForm, canceled: runState === 'idle' })
|
||||
: undefined
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { DisplayMessage } from './shared'
|
||||
import type { AttachedImage } from './imageUtils'
|
||||
import { AIChatManager, AIMode, AIAutonomyMode, aiChatManager } from './AIChatManager.svelte'
|
||||
import { AIWorkMode, USE_MODE_WITHDRAWN } from './workMode'
|
||||
import { createAppDomSelectorElement, createCodeSelection } from './context'
|
||||
import { makePasteToken } from './pasteTokens'
|
||||
import { PLAN_MODE_MESSAGES } from './planModeMessages'
|
||||
import { runChatLoop } from './chatLoop'
|
||||
@@ -38,6 +39,8 @@ const mocks = vi.hoisted(() => ({
|
||||
getJob: vi.fn(),
|
||||
getJobUpdates: vi.fn(),
|
||||
whoami: vi.fn(),
|
||||
saveSecretRequest: vi.fn(),
|
||||
checkSubmission: vi.fn(),
|
||||
workspace: 'test_workspace' as string | undefined,
|
||||
// The workspace being browsed, which a session chat's own workspace need not be.
|
||||
navWorkspace: undefined as string | undefined,
|
||||
@@ -167,6 +170,17 @@ vi.mock('./api/apiTools', () => ({
|
||||
loadApiTools: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./secretRequest', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('./secretRequest')>()),
|
||||
saveSecretRequest: mocks.saveSecretRequest,
|
||||
checkSubmission: mocks.checkSubmission
|
||||
}))
|
||||
|
||||
vi.mock('$lib/components/resourceConnectionTest', () => ({
|
||||
canTestUnsaved: vi.fn(),
|
||||
testUnsavedResource: vi.fn()
|
||||
}))
|
||||
|
||||
// Mock only runChatLoop; keep the real truncateToToolPairedPrefix (pure) that
|
||||
// the manager uses to commit partial output.
|
||||
vi.mock('./chatLoop', async (importOriginal) => ({
|
||||
@@ -532,6 +546,112 @@ describe('AIChatManager run form', () => {
|
||||
})
|
||||
})
|
||||
|
||||
// Stop cannot withdraw a save already sent, so the card must end on what the save did.
|
||||
describe('AIChatManager secret request', () => {
|
||||
it('ends the turn at stop, and settles the card on a save that lands after it', async () => {
|
||||
const manager = new AIChatManager()
|
||||
const request = { workspace: 'test_workspace', path: 'u/a/key', label: 'API key' }
|
||||
manager.displayMessages = [
|
||||
{ role: 'tool', tool_call_id: 'call_s', content: '', isLoading: true, secretRequest: request }
|
||||
]
|
||||
let land!: (outcome: { path: string; replaced: boolean; variables: string[] }) => void
|
||||
mocks.saveSecretRequest.mockReturnValueOnce(new Promise((resolve) => (land = resolve)))
|
||||
|
||||
const toolResult = manager.requestSecret('call_s', request)
|
||||
const saved = manager.saveSecret('call_s', {
|
||||
path: 'u/a/key',
|
||||
replace: false,
|
||||
secrets: { '': 'sk-1' }
|
||||
})
|
||||
manager.cancel()
|
||||
expect(await toolResult).toBeUndefined()
|
||||
|
||||
// Opening another chat first would settle this card in that one, so it waits.
|
||||
const loadPast = vi.spyOn(manager.historyManager, 'loadPastChat').mockResolvedValue(undefined)
|
||||
const switched = manager.loadPastChat('other')
|
||||
await Promise.resolve()
|
||||
expect(loadPast).not.toHaveBeenCalled()
|
||||
|
||||
// A follow-up sent while it waits keeps its conversation.
|
||||
manager.loading = true
|
||||
land({ path: 'u/a/key', replaced: false, variables: ['u/a/key'] })
|
||||
await saved
|
||||
await switched
|
||||
expect(loadPast).not.toHaveBeenCalled()
|
||||
const card = manager.displayMessages[0]
|
||||
expect(card.role === 'tool' && card.secretRequest).toMatchObject({
|
||||
saved: { path: 'u/a/key' },
|
||||
saving: false
|
||||
})
|
||||
})
|
||||
|
||||
it('records the drafts and tells the model of a failed check when the save lands after stop', async () => {
|
||||
const manager = new AIChatManager()
|
||||
manager.initModifiedItemsTracking()
|
||||
const note = vi.spyOn(manager, 'queueModelNote').mockResolvedValue(undefined)
|
||||
const request = {
|
||||
workspace: 'test_workspace',
|
||||
path: 'u/a/s3',
|
||||
label: 'S3',
|
||||
resource: { type: 's3', value: {}, secretFields: [{ field: 'secretKey', label: 'Secret key' }] }
|
||||
}
|
||||
manager.displayMessages = [
|
||||
{ role: 'tool', tool_call_id: 'call_l', content: '', isLoading: true, secretRequest: request }
|
||||
]
|
||||
let land!: (outcome: { path: string; replaced: boolean; variables: string[] }) => void
|
||||
mocks.saveSecretRequest.mockReturnValueOnce(new Promise((resolve) => (land = resolve)))
|
||||
mocks.checkSubmission.mockResolvedValueOnce({ ok: false, error: 'InvalidAccessKeyId' })
|
||||
|
||||
void manager.requestSecret('call_l', request)
|
||||
const saved = manager.saveSecret('call_l', { path: 'u/a/s3', replace: false, secrets: {} })
|
||||
manager.cancel()
|
||||
land({ path: 'u/a/s3', replaced: false, variables: ['u/a/s3'] })
|
||||
await saved
|
||||
|
||||
expect([...(manager.modifiedItems ?? [])].sort()).toEqual(['resource:u/a/s3', 'variable:u/a/s3'])
|
||||
expect(note).toHaveBeenCalledWith(expect.stringContaining('InvalidAccessKeyId'))
|
||||
})
|
||||
})
|
||||
|
||||
// The resource exists once saved, so a failed check must never read as dismissed.
|
||||
describe('AIChatManager secret connection check', () => {
|
||||
it('keeps the card open on a failed check, and settles it as saved when the user keeps it', async () => {
|
||||
const manager = new AIChatManager()
|
||||
const request = {
|
||||
workspace: 'test_workspace',
|
||||
path: 'u/a/db',
|
||||
label: 'Postgres',
|
||||
resource: {
|
||||
type: 'postgresql',
|
||||
value: {},
|
||||
secretFields: [{ field: 'password', label: 'Password' }]
|
||||
}
|
||||
}
|
||||
manager.displayMessages = [
|
||||
{ role: 'tool', tool_call_id: 'call_c', content: '', isLoading: true, secretRequest: request }
|
||||
]
|
||||
mocks.saveSecretRequest.mockResolvedValueOnce({
|
||||
path: 'u/a/db',
|
||||
replaced: false,
|
||||
variables: ['u/a/db']
|
||||
})
|
||||
mocks.checkSubmission.mockResolvedValueOnce({ ok: false, error: 'Network is unreachable' })
|
||||
|
||||
const toolResult = manager.requestSecret('call_c', request)
|
||||
await expect(
|
||||
manager.saveSecret('call_c', { path: 'u/a/db', replace: false, secrets: { password: 'x' } })
|
||||
).rejects.toThrow('Network is unreachable')
|
||||
const open = manager.displayMessages[0]
|
||||
expect(open.role === 'tool' && open.secretRequest?.saved).toBeFalsy()
|
||||
|
||||
manager.dismissSecret('call_c')
|
||||
expect(await toolResult).toMatchObject({
|
||||
path: 'u/a/db',
|
||||
check: { ok: false, error: 'Network is unreachable' }
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('AIChatManager.sendOrQueue', () => {
|
||||
// The programmatic senders (an editor's "AI Fix", an arriving hand-off) have no
|
||||
// composer to enforce the composer's rule for them: a second loop on one manager
|
||||
@@ -1204,6 +1324,17 @@ describe('AIChatManager user questions', () => {
|
||||
})
|
||||
})
|
||||
|
||||
function pick(content: string, line = 1) {
|
||||
return createCodeSelection(
|
||||
{ kind: 'script', path: 'f/a/b' },
|
||||
{ content, startLine: line, endLine: line, lang: 'bun' }
|
||||
)
|
||||
}
|
||||
|
||||
function element(selector: string) {
|
||||
return createAppDomSelectorElement({ selector, appPath: 'f/app', tagName: 'div' })
|
||||
}
|
||||
|
||||
describe('AIChatManager queued messages', () => {
|
||||
const model = { provider: 'openai', model: 'gpt-4o' }
|
||||
|
||||
@@ -1520,6 +1651,14 @@ describe('AIChatManager queued messages', () => {
|
||||
.filter((c) => c.type === 'app_dom_selector')
|
||||
.map((c) => c.selector)
|
||||
).toEqual(['div.a'])
|
||||
|
||||
// Nor when the message was stored without context.
|
||||
seed()
|
||||
delete (manager.displayMessages[0] as any).contextElements
|
||||
manager.restartGeneration(0)
|
||||
await vi.waitFor(() => expect(manager.displayMessages[0]).toHaveProperty('contextElements'))
|
||||
expect(sentChipSelectors()).toEqual([])
|
||||
expect(cm.getSelectedContext()).toEqual([chipA])
|
||||
})
|
||||
|
||||
// The loop, not the send, owns the vision strip: it re-applies it per iteration
|
||||
@@ -2409,7 +2548,7 @@ describe('AIChatManager queued messages', () => {
|
||||
const input = createInputMock()
|
||||
const manager = createManager(input)
|
||||
replyWith('done')
|
||||
// cancel before any usable output → the rollback (restoreUnsentTurn) path
|
||||
// cancel before any usable output → the rollback path
|
||||
mocks.runChatLoop.mockImplementationOnce(async ({ abortController }: any) => {
|
||||
abortController.abort('user_cancelled')
|
||||
throw new Error('aborted')
|
||||
@@ -2508,8 +2647,8 @@ describe('AIChatManager queued messages', () => {
|
||||
{ role: 'tool' as const, tool_call_id: 'shot', content: 'Screenshot attached below' }
|
||||
)
|
||||
config.callbacks.attachToolImage('shot', {
|
||||
dataUrl: 'data:image/png;base64,iVBORw0KGgo=',
|
||||
name: 'shot.png'
|
||||
image: { dataUrl: 'data:image/png;base64,iVBORw0KGgo=', name: 'shot.png' },
|
||||
caption: 'Screenshot(s) of the app preview:'
|
||||
})
|
||||
leavePage.forEach((fn) => fn())
|
||||
return {
|
||||
@@ -2831,8 +2970,7 @@ describe('AIChatManager queued messages', () => {
|
||||
|
||||
await manager.sendRequest({
|
||||
instructions: 'why does this retry',
|
||||
contextOverride: carried,
|
||||
contextOverrideOrigin: 'pinned'
|
||||
contextOverride: carried
|
||||
})
|
||||
|
||||
expect(cm.getSelectedContext()).toEqual([mention])
|
||||
@@ -2856,8 +2994,7 @@ describe('AIChatManager queued messages', () => {
|
||||
|
||||
await manager.sendRequest({
|
||||
instructions: 'why does this retry',
|
||||
contextOverride: [mention],
|
||||
contextOverrideOrigin: 'pinned'
|
||||
contextOverride: [mention]
|
||||
})
|
||||
|
||||
expect(cm.getSelectedContext()).toEqual([mention])
|
||||
@@ -2876,8 +3013,7 @@ describe('AIChatManager queued messages', () => {
|
||||
const pending = manager.sendRequest({
|
||||
instructions: 'describe this image',
|
||||
images: [{ id: 'img-1', dataUrl: 'data:image/png;base64,AAAA' } as any],
|
||||
contextOverride: [mention],
|
||||
contextOverrideOrigin: 'pinned'
|
||||
contextOverride: [mention]
|
||||
})
|
||||
manager.mode = AIMode.SCRIPT
|
||||
await pending
|
||||
@@ -2918,6 +3054,73 @@ describe('AIChatManager queued messages', () => {
|
||||
expect(chips.map((c) => c.selector)).toEqual(['div.a'])
|
||||
})
|
||||
|
||||
it('carries code attached in a session on its next message, and only there', async () => {
|
||||
replyWith('done')
|
||||
const manager = createManager(createInputMock())
|
||||
manager.mode = AIMode.GLOBAL
|
||||
manager.isSessionChat = true
|
||||
const selection = pick('return 1', 2)
|
||||
manager.listenForContextChange({}, 'parent')
|
||||
manager.attachCodeSelection(selection)
|
||||
// The composer's context is rebuilt whenever the page's workspace or its schemas change.
|
||||
manager.listenForContextChange({}, 'parent')
|
||||
manager.listenForContextChange({}, 'fork')
|
||||
expect(manager.mode).toBe(AIMode.GLOBAL)
|
||||
|
||||
await manager.sendRequest({ instructions: 'make it 2' })
|
||||
|
||||
const { messages } = mocks.runChatLoop.mock.calls.at(-1)![0] as any
|
||||
expect(messages.at(-1).content).toContain('path: f/a/b, lines 2-2:\n```bun\nreturn 1\n```')
|
||||
expect(manager.contextManager.getSelectedContext()).toEqual([])
|
||||
})
|
||||
|
||||
it('sends a queued message with its own picks and leaves the next one its own', async () => {
|
||||
replyWith('done')
|
||||
const manager = createManager(createInputMock())
|
||||
manager.mode = AIMode.GLOBAL
|
||||
manager.queueMessage('first', [], [pick('before')])
|
||||
// The lines change and are queued again, then picked once more as they were at first.
|
||||
manager.queueMessage('second', [], [pick('after')])
|
||||
manager.attachCodeSelection(pick('before'))
|
||||
|
||||
await manager.sendRequest({ instructions: 'running', contextOverride: [] })
|
||||
|
||||
const { messages } = mocks.runChatLoop.mock.calls.at(-1)![0] as any
|
||||
expect(messages.at(-1).content).toContain('before')
|
||||
expect(messages.at(-1).content).toContain('after')
|
||||
expect(manager.contextManager.getSelectedContext()).toEqual([pick('before')])
|
||||
})
|
||||
|
||||
it('leaves what is attached for the next message out of one queued without it', async () => {
|
||||
replyWith('done')
|
||||
const manager = createManager(createInputMock())
|
||||
manager.mode = AIMode.GLOBAL
|
||||
const selection = pick('return 1', 2)
|
||||
manager.queueMessage('queued')
|
||||
manager.attachCodeSelection(selection)
|
||||
|
||||
await manager.sendRequest({ instructions: 'running', contextOverride: [] })
|
||||
|
||||
const { messages } = mocks.runChatLoop.mock.calls.at(-1)![0] as any
|
||||
expect(messages.at(-1).content).toContain('queued')
|
||||
expect(messages.at(-1).content).not.toContain('SELECTED CODE')
|
||||
expect(manager.contextManager.getSelectedContext()).toEqual([selection])
|
||||
})
|
||||
|
||||
it('leaves code attached in the composer there when a prompt sent past it comes back', () => {
|
||||
const manager = createManager(createInputMock())
|
||||
manager.attachCodeSelection(pick('for the composer'))
|
||||
manager.loading = true
|
||||
manager.sendOrQueue('make it red', [element('div.prompt')])
|
||||
|
||||
manager.dequeueMessage()
|
||||
|
||||
expect(manager.contextManager.getSelectedContext()).toEqual([
|
||||
element('div.prompt'),
|
||||
pick('for the composer')
|
||||
])
|
||||
})
|
||||
|
||||
// Restoration is only coherent when the text it belongs to actually lands in the
|
||||
// composer. Both cases below leave another draft sitting there, so replacing its
|
||||
// chips would silently retarget an instruction the user is still writing.
|
||||
@@ -3032,8 +3235,7 @@ describe('AIChatManager queued messages', () => {
|
||||
|
||||
const accepted = await manager.sendRequest({
|
||||
instructions: '@f/etl/sync fix this',
|
||||
contextOverride: [mention],
|
||||
contextOverrideOrigin: 'pinned'
|
||||
contextOverride: [mention]
|
||||
})
|
||||
|
||||
expect(accepted).toBe(false)
|
||||
@@ -3053,8 +3255,7 @@ describe('AIChatManager queued messages', () => {
|
||||
|
||||
await manager.sendRequest({
|
||||
instructions: '@f/etl/sync fix this',
|
||||
contextOverride: [mention],
|
||||
contextOverrideOrigin: 'pinned'
|
||||
contextOverride: [mention]
|
||||
})
|
||||
|
||||
expect(mocks.runChatLoop).not.toHaveBeenCalled()
|
||||
@@ -3095,8 +3296,7 @@ describe('AIChatManager queued messages', () => {
|
||||
|
||||
await manager.sendRequest({
|
||||
instructions: '@f/etl/sync fix this',
|
||||
contextOverride: [mention],
|
||||
contextOverrideOrigin: 'pinned'
|
||||
contextOverride: [mention]
|
||||
})
|
||||
|
||||
expect(manager.contextManager.getSelectedContext()).toEqual([])
|
||||
@@ -3115,8 +3315,7 @@ describe('AIChatManager queued messages', () => {
|
||||
|
||||
await manager.sendRequest({
|
||||
instructions: 'fix this',
|
||||
contextOverride: [mention],
|
||||
contextOverrideOrigin: 'pinned'
|
||||
contextOverride: [mention]
|
||||
})
|
||||
|
||||
expect(manager.contextManager.getSelectedContext()).toEqual([])
|
||||
@@ -4924,6 +5123,25 @@ describe('AIChatManager cross-tab run seams', () => {
|
||||
expect(manager.queuedMessage).toBe('race loser')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['at the start of the send', () => true],
|
||||
// Announced during the send's own awaits.
|
||||
['once it is under way', (reads: number) => reads > 1]
|
||||
])('keeps the pick of a refused prompt, refused %s', async (_, held) => {
|
||||
const manager = new AIChatManager()
|
||||
manager.isSessionChat = true
|
||||
manager.mode = AIMode.GLOBAL
|
||||
let reads = 0
|
||||
manager.runHeldElsewhereResolver = () => held(++reads)
|
||||
const selection = element('div.prompt')
|
||||
|
||||
manager.sendOrQueue('make it red', [selection])
|
||||
|
||||
await vi.waitFor(() => expect(manager.queuedMessage).toBe('make it red'))
|
||||
expect(mocks.runChatLoop).not.toHaveBeenCalled()
|
||||
expect(manager.queuedContext).toEqual([selection])
|
||||
})
|
||||
|
||||
// A synthetic (auto-resume) prompt is client-authored: a refusal must
|
||||
// release it rather than hand it back as a draft the user never wrote —
|
||||
// staged instructions would otherwise block every later auto-resume.
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
import { messageDraft, segments } from './chatDraft'
|
||||
import { lineCountLabel } from './pasteTokens'
|
||||
import ExpandableImage from '$lib/components/common/image/ExpandableImage.svelte'
|
||||
import { imageContentKey } from './files/imageFiles'
|
||||
import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte'
|
||||
|
||||
const operatingWorkspace = useOperatingWorkspace()
|
||||
@@ -178,6 +179,13 @@
|
||||
src={image.dataUrl}
|
||||
alt={image.name ?? 'attached image'}
|
||||
class="max-h-40 max-w-[min(20rem,100%)] rounded-lg border border-border-light"
|
||||
onOpen={chatHost.openImage
|
||||
? () =>
|
||||
chatHost.openImage?.(
|
||||
{ kind: 'message', hash: imageContentKey(image.dataUrl) },
|
||||
image.name ?? 'Image'
|
||||
)
|
||||
: undefined}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user