The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(cli): add a terminal progress bar to human output (#28099)
Weikof20f184f0c66
diff --git a/packages/twenty-cli/package.json b/packages/twenty-cli/package.jsonindex 2df996f3c01..642284af9f6 100644--- a/packages/twenty-cli/package.json+++ b/packages/twenty-cli/package.json@@ -34,6 +34,7 @@"lodash.startcase": "^4.4.0","npm-pick-manifest": "^11.0.1","semver": "7.6.3",+ "string-width": "^8.2.0","twenty-client-sdk": "workspace:*","twenty-shared": "workspace:*","undici": "^7.29.0",diff --git a/packages/twenty-cli/src/__tests__/utils/set-standard-error-terminal-for-test.ts b/packages/twenty-cli/src/__tests__/utils/set-standard-error-terminal-for-test.tsnew file mode 100644index 00000000000..767de086a56--- /dev/null+++ b/packages/twenty-cli/src/__tests__/utils/set-standard-error-terminal-for-test.ts@@ -0,0 +1,23 @@+import { isDefined } from 'twenty-shared/utils';++export const setStandardErrorTerminalForTest = () => {+ const descriptors = {+ isTTY: Object.getOwnPropertyDescriptor(process.stderr, 'isTTY'),+ columns: Object.getOwnPropertyDescriptor(process.stderr, 'columns'),+ };++ Object.defineProperties(process.stderr, {+ isTTY: { value: true, configurable: true, writable: true },+ columns: { value: 80, configurable: true, writable: true },+ });++ return () => {+ for (const [property, descriptor] of Object.entries(descriptors)) {+ if (isDefined(descriptor)) {+ Object.defineProperty(process.stderr, property, descriptor);+ } else {+ Reflect.deleteProperty(process.stderr, property);+ }+ }+ };+};diff --git a/packages/twenty-cli/src/app/deployment/apply-app-build.ts b/packages/twenty-cli/src/app/deployment/apply-app-build.tsindex 594604e6c16..4a65055d350 100644--- a/packages/twenty-cli/src/app/deployment/apply-app-build.ts+++ b/packages/twenty-cli/src/app/deployment/apply-app-build.ts@@ -140,15 +140,15 @@ export const applyAppBuild = async ({hint: 'Run twenty app apply --create to register it and install it in this workspace.',});- output.progress('Registering the app…');+ output.progress({ message: 'Registering the app…' });await runPhase('registration', () =>registerApp({ application, target, signal }),);- output.progress('Installing the development app…');+ output.progress({ message: 'Installing the development app…' });await runPhase('installation', () =>installDevelopmentApp({ application, target, signal }),);- output.progress('Computing metadata plan…');+ output.progress({ message: 'Computing metadata plan…' });return {actions: await runPhase('preview', preview),@@ -161,20 +161,20 @@ export const applyAppBuild = async ({appPath,});- output.progress(`Computing metadata plan on ${target.apiUrl}…`);+ output.progress({ message: `Computing metadata plan on ${target.apiUrl}…` });const { actions, isRegistrationCreated } = await previewOrBootstrap();const summary = getAppPlanSummary(actions);if (outputMode === 'human') {- output.progress(- formatAppPlanActions({+ output.progress({+ message: formatAppPlanActions({actions,summary,inferDeletionFromMissingEntities,stream: process.stderr,}),- );+ });}if (summary.destructive > 0) {@@ -198,9 +198,9 @@ export const applyAppBuild = async ({);}- output.progress(- `Uploading ${build.files.length} ${build.files.length === 1 ? 'file' : 'files'}…`,- );+ output.progress({+ message: `Uploading ${build.files.length} ${build.files.length === 1 ? 'file' : 'files'}…`,+ });await runPhase('upload', () =>uploadAppFiles({build,@@ -210,7 +210,7 @@ export const applyAppBuild = async ({progress: upload,}),);- output.progress('Synchronizing the app…');+ output.progress({ message: 'Synchronizing the app…' });const { actions: appliedActions, acknowledgedUniversalIdentifier } =await runPhase('sync', () =>diff --git a/packages/twenty-cli/src/app/dev/__tests__/create-dev-output.spec.ts b/packages/twenty-cli/src/app/dev/__tests__/create-dev-output.spec.tsindex 1ce53e586a4..38fdb523d33 100644--- a/packages/twenty-cli/src/app/dev/__tests__/create-dev-output.spec.ts+++ b/packages/twenty-cli/src/app/dev/__tests__/create-dev-output.spec.ts@@ -30,6 +30,7 @@ describe('dev stream output', () => {},};const output = createDevOutput(context);+ output.output.progress({ message: 'Uploading files…', percentage: 25 });for (let index = 0; index < 1000; index += 1)output.output.warn({ code: 'WARNING', message: `warning ${index}` });const first = output.emit(@@ -45,7 +46,8 @@ describe('dev stream output', () => {'progress',expect.objectContaining({messages: expect.arrayContaining([- { message: '968 additional progress messages omitted.' },+ { message: 'Uploading files…', percentage: 25 },+ { message: '969 additional progress messages omitted.' },]),}),context.signal,diff --git a/packages/twenty-cli/src/app/dev/create-dev-output.ts b/packages/twenty-cli/src/app/dev/create-dev-output.tsindex 12396d62a52..830dc78a5ea 100644--- a/packages/twenty-cli/src/app/dev/create-dev-output.ts+++ b/packages/twenty-cli/src/app/dev/create-dev-output.ts@@ -1,17 +1,34 @@import { once } from 'node:events';+import { isNonEmptyString } from '@sniptt/guards';+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';+import { formatProgressLine } from '@/output/format-progress-line';import { formatWarningLine } from '@/output/style';import { type Output } from '@/output/types/output.type';+type DevOutputMessage = { message: string; code?: string; percentage?: number };++const formatDevOutputMessage = ({+ message,+ code,+ percentage,+}: DevOutputMessage) => {+ if (isNonEmptyString(code)) {+ return formatWarningLine(message);+ }++ return formatProgressLine({ message, percentage });+};+export const createDevOutput = (context: TargetCommandContext) => {- const messages: { message: string; code?: string }[] = [];+ const messages: DevOutputMessage[] = [];let delivery = Promise.resolve();let omittedMessages = 0;const output: Output = {...context.output,- progress: (message) => {- if (messages.length < 32) messages.push({ message });+ progress: (progress) => {+ if (messages.length < 32) messages.push(progress);else omittedMessages += 1;},warn: (warning) => {@@ -41,9 +58,7 @@ export const createDevOutput = (context: TargetCommandContext) => {);} else {const text = [- ...pendingMessages.map((message) =>- message.code ? formatWarningLine(message.message) : message.message,- ),+ ...pendingMessages.map(formatDevOutputMessage),event.message,].filter((message) => message.length > 0)diff --git a/packages/twenty-cli/src/app/exec/read-exec-manifest.ts b/packages/twenty-cli/src/app/exec/read-exec-manifest.tsindex 197cc1235fe..d99d5d94007 100644--- a/packages/twenty-cli/src/app/exec/read-exec-manifest.ts+++ b/packages/twenty-cli/src/app/exec/read-exec-manifest.ts@@ -27,7 +27,7 @@ export const readExecManifest = async ({warn: output.warn,});- output.progress(`Reading app definitions in ${project.path}…`);+ output.progress({ message: `Reading app definitions in ${project.path}…` });const worker = await runAppWorker({request: { type: 'buildManifest', appPath: project.path },signal,@@ -90,7 +90,7 @@ export const readExecManifest = async ({if (outputMode === 'human') {for (const diagnostic of diagnostics) {- output.progress(formatToolingDiagnostic(diagnostic));+ output.progress({ message: formatToolingDiagnostic(diagnostic) });}}if (!result.success) {diff --git a/packages/twenty-cli/src/app/generate-app-client.ts b/packages/twenty-cli/src/app/generate-app-client.tsindex b1baecad733..c4225854b10 100644--- a/packages/twenty-cli/src/app/generate-app-client.ts+++ b/packages/twenty-cli/src/app/generate-app-client.ts@@ -17,7 +17,7 @@ export const fetchAppClientSchema = async ({applicationUniversalIdentifier: string;context: TargetCommandContext;}) => {- output.progress('Fetching the application schema…');+ output.progress({ message: 'Fetching the application schema…' });const data = await createMetadataClient({ target, signal }).query({__name: 'ApplicationCoreGraphqlSchema',@@ -48,7 +48,7 @@ export const generateAppClientFromSchema = async ({sdk: ProjectSdk;context: TargetCommandContext;}) => {- output.progress('Generating the typed API client…');+ output.progress({ message: 'Generating the typed API client…' });const workerRun = await runAppWorker({request: { type: 'generateSourceClient', appPath, schema },@@ -65,7 +65,7 @@ export const generateAppClientFromSchema = async ({if (outputMode === 'human') {for (const diagnostic of diagnostics) {- output.progress(formatToolingDiagnostic(diagnostic));+ output.progress({ message: formatToolingDiagnostic(diagnostic) });}}diff --git a/packages/twenty-cli/src/app/publish/publish-app-to-npm.ts b/packages/twenty-cli/src/app/publish/publish-app-to-npm.tsindex 0d7ff5e6253..f944c2322ea 100644--- a/packages/twenty-cli/src/app/publish/publish-app-to-npm.ts+++ b/packages/twenty-cli/src/app/publish/publish-app-to-npm.ts@@ -20,9 +20,9 @@ export const publishAppToNpm = async ({isDefined(process.env.ACTIONS_ID_TOKEN_REQUEST_URL) &&process.env.TWENTY_APP_PUBLISH_DISABLE_PROVENANCE !== 'true';- context.output.progress(- `Publishing ${packedApp.name}@${packedApp.version} to npm…`,- );+ context.output.progress({+ message: `Publishing ${packedApp.name}@${packedApp.version} to npm…`,+ });await runNpmCommand({args: ['publish',@@ -38,7 +38,7 @@ export const publishAppToNpm = async ({signal: context.signal,canInteract: isInteractionAllowed(context),...(context.outputMode === 'human'- ? { onOutput: context.output.progress }+ ? { onOutput: (message: string) => context.output.progress({ message }) }: {}),});diff --git a/packages/twenty-cli/src/app/publish/publish-app-to-server.ts b/packages/twenty-cli/src/app/publish/publish-app-to-server.tsindex 81c7aecc54f..f4112959f6f 100644--- a/packages/twenty-cli/src/app/publish/publish-app-to-server.ts+++ b/packages/twenty-cli/src/app/publish/publish-app-to-server.ts@@ -60,9 +60,9 @@ export const publishAppToServer = async ({fileId = upload.fileId;completedPhases.push(phase);phase = 'upload';- output.progress(- `Uploading ${packedApp.name}@${packedApp.version} to ${target.apiUrl}…`,- );+ output.progress({+ message: `Uploading ${packedApp.name}@${packedApp.version} to ${target.apiUrl}…`,+ });const status = await putUploadFile({uploadUrl: upload.uploadUrl,contentType: upload.contentType,@@ -79,7 +79,7 @@ export const publishAppToServer = async ({completedPhases.push(phase);signal.throwIfAborted();- output.progress('Registering the uploaded app…');+ output.progress({ message: 'Registering the uploaded app…' });phase = 'register';const result = await client.mutation({__name: 'CompleteAppTarballUpload',diff --git a/packages/twenty-cli/src/app/publish/with-packed-app.ts b/packages/twenty-cli/src/app/publish/with-packed-app.tsindex c1360007f01..39218c46685 100644--- a/packages/twenty-cli/src/app/publish/with-packed-app.ts+++ b/packages/twenty-cli/src/app/publish/with-packed-app.ts@@ -35,7 +35,7 @@ export const withPackedApp = async <TResult>({);try {- output.progress('Packing the built app…');+ output.progress({ message: 'Packing the built app…' });const stdout = await runNpmCommand({args: ['pack',diff --git a/packages/twenty-cli/src/app/read-application-identifier.ts b/packages/twenty-cli/src/app/read-application-identifier.tsindex 516fe60dbb5..3c8b3a37970 100644--- a/packages/twenty-cli/src/app/read-application-identifier.ts+++ b/packages/twenty-cli/src/app/read-application-identifier.ts@@ -54,7 +54,7 @@ export const readApplicationIdentifier = async ({if (outputMode === 'human') {for (const diagnostic of identity.diagnostics) {- output.progress(formatToolingDiagnostic(diagnostic));+ output.progress({ message: formatToolingDiagnostic(diagnostic) });}}diff --git a/packages/twenty-cli/src/app/record-pull-base.ts b/packages/twenty-cli/src/app/record-pull-base.tsindex 87c86ed1f57..671c0e507e5 100644--- a/packages/twenty-cli/src/app/record-pull-base.ts+++ b/packages/twenty-cli/src/app/record-pull-base.ts@@ -18,7 +18,7 @@ export const recordPullBase = async ({sourceFingerprints?: Record<string, string>;context: TargetCommandContext;}): Promise<PullBaseRecording> => {- output.progress('Recording the pull base…');+ output.progress({ message: 'Recording the pull base…' });try {const workspaceId = await fetchWorkspaceId({ target, signal });diff --git a/packages/twenty-cli/src/app/run-app-operation.ts b/packages/twenty-cli/src/app/run-app-operation.tsindex 36964a9c9da..81ccd862dd7 100644--- a/packages/twenty-cli/src/app/run-app-operation.ts+++ b/packages/twenty-cli/src/app/run-app-operation.ts@@ -69,9 +69,9 @@ const runAppOperation = async <TData>({warn: output.warn,});- output.progress(- `${PROGRESS_VERBS[operation]} ${project.name} with twenty ${CLI_VERSION}…`,- );+ output.progress({+ message: `${PROGRESS_VERBS[operation]} ${project.name} with twenty ${CLI_VERSION}…`,+ });const startedAt = performance.now();const readBuildResult = ({@@ -89,7 +89,7 @@ const runAppOperation = async <TData>({if (outputMode === 'human') {for (const diagnostic of diagnostics) {- output.progress(formatToolingDiagnostic(diagnostic));+ output.progress({ message: formatToolingDiagnostic(diagnostic) });}}diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-publish.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-publish.spec.tsindex d9e89b7fee7..87097c71538 100644--- a/packages/twenty-cli/src/commands/app/__tests__/app-publish.spec.ts+++ b/packages/twenty-cli/src/commands/app/__tests__/app-publish.spec.ts@@ -215,6 +215,23 @@ describe.skipIf(process.platform === 'win32')('app publish', () => {await expect(access(invocations[1].args[1])).rejects.toThrow();});+ it('forwards npm output as human progress', async () => {+ const result = await runCliForTest([+ 'app',+ 'publish',+ '--path',+ appPath,+ '--format',+ 'human',+ ]);++ expect(result.exitCode).toBe(0);+ expect(result.stderr).toContain(+ 'npm output must not corrupt the CLI JSON\n',+ );+ expect(result.stderr).not.toContain('[object Object]');+ });+it.each([true, false])('keeps the SDK provenance opt-out, disabled=%s',async (disabled) => {diff --git a/packages/twenty-cli/src/commands/app/add/run-app-add-command.ts b/packages/twenty-cli/src/commands/app/add/run-app-add-command.tsindex 26219efd69f..fb6023b1be5 100644--- a/packages/twenty-cli/src/commands/app/add/run-app-add-command.ts+++ b/packages/twenty-cli/src/commands/app/add/run-app-add-command.ts@@ -31,7 +31,7 @@ export const runAppAddCommand: CommandRun = async (context) => {}for (const diagnostic of identity.diagnostics) {- output.progress(formatToolingDiagnostic(diagnostic));+ output.progress({ message: formatToolingDiagnostic(diagnostic) });}const { entity, name, files } = await prepareAppAddFiles({diff --git a/packages/twenty-cli/src/commands/app/dev/run-app-dev-command.ts b/packages/twenty-cli/src/commands/app/dev/run-app-dev-command.tsindex 0051cfe5896..2765baceee4 100644--- a/packages/twenty-cli/src/commands/app/dev/run-app-dev-command.ts+++ b/packages/twenty-cli/src/commands/app/dev/run-app-dev-command.ts@@ -132,7 +132,7 @@ export const runAppDevCommand: CommandRun<TargetCommandContext> = async (if (context.outputMode === 'human' && Array.isArray(diagnostics)) {for (const diagnostic of diagnostics.filter(isToolingDiagnostic)) {- output.progress(formatToolingDiagnostic(diagnostic));+ output.progress({ message: formatToolingDiagnostic(diagnostic) });}}diff --git a/packages/twenty-cli/src/commands/app/exec/run-app-exec-command.ts b/packages/twenty-cli/src/commands/app/exec/run-app-exec-command.tsindex 43325574bfb..1711cd120b1 100644--- a/packages/twenty-cli/src/commands/app/exec/run-app-exec-command.ts+++ b/packages/twenty-cli/src/commands/app/exec/run-app-exec-command.ts@@ -38,9 +38,10 @@ export const runAppExecCommand: CommandRun<TargetCommandContext> = async (});const manifest = await readExecManifest(context);if (selector.kind === 'hook') {- output.progress(- 'Executing the hook only; this does not install or uninstall the app.',- );+ output.progress({+ message:+ 'Executing the hook only; this does not install or uninstall the app.',+ });}const result = await executeAppFunction({manifest,@@ -49,9 +50,9 @@ export const runAppExecCommand: CommandRun<TargetCommandContext> = async (target,signal,onExecuting: (name) =>- output.progress(- `Executing ${formatDataValue(name)} on ${target.apiUrl}…`,- ),+ output.progress({+ message: `Executing ${formatDataValue(name)} on ${target.apiUrl}…`,+ }),});const human = formatFunctionExecution(result,@@ -60,7 +61,7 @@ export const runAppExecCommand: CommandRun<TargetCommandContext> = async (if (result.status !== 'SUCCESS') {if (outputMode === 'human') {- output.progress(human);+ output.progress({ message: human });}throw new CliError({code: 'EXECUTION_FAILED',diff --git a/packages/twenty-cli/src/commands/app/function-logs/run-app-logs-command.ts b/packages/twenty-cli/src/commands/app/function-logs/run-app-logs-command.tsindex 66fa13da325..d4fbb597cc9 100644--- a/packages/twenty-cli/src/commands/app/function-logs/run-app-logs-command.ts+++ b/packages/twenty-cli/src/commands/app/function-logs/run-app-logs-command.ts@@ -24,7 +24,7 @@ export const runAppLogsCommand: CommandRun<TargetCommandContext> = async (const { options, output, outputMode, signal, target } = context;const warn = (warning: CliWarning) => {if (outputMode === 'human') {- output.progress(formatWarningLine(warning.message));+ output.progress({ message: formatWarningLine(warning.message) });} else {output.warn(warning);}@@ -62,11 +62,11 @@ export const runAppLogsCommand: CommandRun<TargetCommandContext> = async ();if (outputMode === 'human') {for (const diagnostic of identity.diagnostics) {- output.progress(formatToolingDiagnostic(diagnostic));+ output.progress({ message: formatToolingDiagnostic(diagnostic) });}- output.progress(- `Watching ${formatDataValue(identity.application.displayName ?? applicationUniversalIdentifier)} logs on ${target.apiUrl}. New executions only. Press Ctrl+C to stop.`,- );+ output.progress({+ message: `Watching ${formatDataValue(identity.application.displayName ?? applicationUniversalIdentifier)} logs on ${target.apiUrl}. New executions only. Press Ctrl+C to stop.`,+ });}try {diff --git a/packages/twenty-cli/src/commands/app/generate-client/run-app-generate-client-command.ts b/packages/twenty-cli/src/commands/app/generate-client/run-app-generate-client-command.tsindex 355e20b7665..093e9ef07ce 100644--- a/packages/twenty-cli/src/commands/app/generate-client/run-app-generate-client-command.ts+++ b/packages/twenty-cli/src/commands/app/generate-client/run-app-generate-client-command.ts@@ -55,7 +55,7 @@ export const runAppGenerateClientCommand: CommandRun<if (outputMode === 'human') {for (const diagnostic of identity.diagnostics) {- output.progress(formatToolingDiagnostic(diagnostic));+ output.progress({ message: formatToolingDiagnostic(diagnostic) });}}diff --git a/packages/twenty-cli/src/commands/app/init/run-app-init-command.ts b/packages/twenty-cli/src/commands/app/init/run-app-init-command.tsindex 6f5511f2f17..2cb9444ded6 100644--- a/packages/twenty-cli/src/commands/app/init/run-app-init-command.ts+++ b/packages/twenty-cli/src/commands/app/init/run-app-init-command.ts@@ -52,7 +52,7 @@ export const runAppInitCommand: CommandRun = async ({});const location = displayPath === '.' ? 'the current directory' : displayPath;- output.progress(`Creating ${appName} in ${location}…`);+ output.progress({ message: `Creating ${appName} in ${location}…` });await createAppProject({appDirectory,diff --git a/packages/twenty-cli/src/commands/app/install/run-app-install-command.ts b/packages/twenty-cli/src/commands/app/install/run-app-install-command.tsindex f44749f7c92..9a49d5197cc 100644--- a/packages/twenty-cli/src/commands/app/install/run-app-install-command.ts+++ b/packages/twenty-cli/src/commands/app/install/run-app-install-command.ts@@ -24,7 +24,9 @@ export const runAppInstallCommand: CommandRun<TargetCommandContext> = async (});});- output.progress(`Installing the registered app on ${target.apiUrl}…`);+ output.progress({+ message: `Installing the registered app on ${target.apiUrl}…`,+ });const result = await installRegisteredApp({universalIdentifier,@@ -32,7 +34,9 @@ export const runAppInstallCommand: CommandRun<TargetCommandContext> = async (target,signal,onQueued: (jobId) =>- output.progress(`Waiting for installation ${formatDataValue(jobId)}…`),+ output.progress({+ message: `Waiting for installation ${formatDataValue(jobId)}…`,+ }),});return {diff --git a/packages/twenty-cli/src/commands/app/plan/run-app-plan-command.ts b/packages/twenty-cli/src/commands/app/plan/run-app-plan-command.tsindex d519b6654e3..fdbd8d6a96f 100644--- a/packages/twenty-cli/src/commands/app/plan/run-app-plan-command.ts+++ b/packages/twenty-cli/src/commands/app/plan/run-app-plan-command.ts@@ -17,9 +17,9 @@ export const runAppPlanCommand: CommandRun<TargetCommandContext> = async (} = await runAppBuild({ context });const inferDeletionFromMissingEntities = context.options.delete !== false;- context.output.progress(- 'Computing metadata plan (read-only, nothing will be applied)…',- );+ context.output.progress({+ message: 'Computing metadata plan (read-only, nothing will be applied)…',+ });const actions = await fetchAppPlan({build,diff --git a/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts b/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.tsindex 47b72d21fd0..c9362d3a860 100644--- a/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts+++ b/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts@@ -77,15 +77,16 @@ export const runAppPullCommand: CommandRun<TargetCommandContext> = async ({message: `This project declares application ${identity.application.universalIdentifier}, not ${universalIdentifier}. Pull it into a different directory.`,});}- output.progress(`Exporting the app from ${target.apiUrl}…`);+ output.progress({ message: `Exporting the app from ${target.apiUrl}…` });const [workspaceId, applicationExport] = await Promise.all([fetchWorkspaceId({ target, signal }),fetchAppExport({ universalIdentifier, target, signal }),]);- output.progress(- 'Reconciling local definitions. Changed workspace entities replace local edits…',- );+ output.progress({+ message:+ 'Reconciling local definitions. Changed workspace entities replace local edits…',+ });const worker = await runAppWorker({request: {@@ -121,7 +122,7 @@ export const runAppPullCommand: CommandRun<TargetCommandContext> = async ({if (outputMode === 'human') {for (const diagnostic of diagnostics) {- output.progress(formatToolingDiagnostic(diagnostic));+ output.progress({ message: formatToolingDiagnostic(diagnostic) });}}diff --git a/packages/twenty-cli/src/commands/app/translations/extract/run-app-translations-extract-command.ts b/packages/twenty-cli/src/commands/app/translations/extract/run-app-translations-extract-command.tsindex 9a3843940a9..724f19be333 100644--- a/packages/twenty-cli/src/commands/app/translations/extract/run-app-translations-extract-command.ts+++ b/packages/twenty-cli/src/commands/app/translations/extract/run-app-translations-extract-command.ts@@ -22,7 +22,9 @@ export const runAppTranslationsExtractCommand: CommandRun = async (context) => {});const sdk = await resolveSourceSdk({ appPath: project.path });- output.progress(`Extracting translatable strings from ${project.name}…`);+ output.progress({+ message: `Extracting translatable strings from ${project.name}…`,+ });const worker = await runAppWorker({request: { type: 'extractTranslations', appPath: project.path, locale },signal,@@ -53,7 +55,7 @@ export const runAppTranslationsExtractCommand: CommandRun = async (context) => {if (outputMode === 'human') {for (const diagnostic of diagnostics) {- output.progress(formatToolingDiagnostic(diagnostic));+ output.progress({ message: formatToolingDiagnostic(diagnostic) });}}if (!result.success) {diff --git a/packages/twenty-cli/src/commands/app/uninstall/run-app-uninstall-command.ts b/packages/twenty-cli/src/commands/app/uninstall/run-app-uninstall-command.tsindex 4dacca490d3..192387d2a81 100644--- a/packages/twenty-cli/src/commands/app/uninstall/run-app-uninstall-command.ts+++ b/packages/twenty-cli/src/commands/app/uninstall/run-app-uninstall-command.ts@@ -28,7 +28,7 @@ export const runAppUninstallCommand: CommandRun<TargetCommandContext> = async (throw fail(error, 'identity');});- output.progress(`Checking the app on ${target.apiUrl}…`);+ output.progress({ message: `Checking the app on ${target.apiUrl}…` });const installedApp = await fetchInstalledApp({universalIdentifier,@@ -65,7 +65,7 @@ export const runAppUninstallCommand: CommandRun<TargetCommandContext> = async (throw fail(error, 'confirmation');});- output.progress(`Uninstalling ${appName}…`);+ output.progress({ message: `Uninstalling ${appName}…` });await uninstallApp({ universalIdentifier, target, signal }).catch((error: unknown) => {diff --git a/packages/twenty-cli/src/oauth/sign-in-with-browser.ts b/packages/twenty-cli/src/oauth/sign-in-with-browser.tsindex 02f01805094..ebfd5e6d519 100644--- a/packages/twenty-cli/src/oauth/sign-in-with-browser.ts+++ b/packages/twenty-cli/src/oauth/sign-in-with-browser.ts@@ -39,15 +39,18 @@ export const signInWithBrowser = async ({);authorizationUrl.searchParams.set('state', state);- output.progress(- `Opening your browser to sign in to ${new URL(apiUrl).host}…`,- );+ output.progress({+ message: `Opening your browser to sign in to ${new URL(apiUrl).host}…`,+ });openBrowser(authorizationUrl.href);- output.progress(`If nothing opens, visit: ${authorizationUrl.href}`);- output.progress(- 'Waiting for you to approve in the browser. Press Ctrl+C to cancel.',- );+ output.progress({+ message: `If nothing opens, visit: ${authorizationUrl.href}`,+ });+ output.progress({+ message:+ 'Waiting for you to approve in the browser. Press Ctrl+C to cancel.',+ });const code = await callbackServer.waitForCode();const tokens = await requestOAuthTokens({diff --git a/packages/twenty-cli/src/output/__tests__/create-output.spec.ts b/packages/twenty-cli/src/output/__tests__/create-output.spec.tsnew file mode 100644index 00000000000..0a1986b378d--- /dev/null+++ b/packages/twenty-cli/src/output/__tests__/create-output.spec.ts@@ -0,0 +1,261 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createStandardInputStub } from '@/__tests__/utils/create-standard-input-stub';+import { setStandardErrorTerminalForTest } from '@/__tests__/utils/set-standard-error-terminal-for-test';+import { CliError } from '@/output/cli-error';+import { createCancelledError } from '@/output/create-cancelled-error';+import { createOutput } from '@/output/create-output';++let stdout: string;+let stderr: string;+let combined: string;+let restoreTerminal: () => void;+let previousExitCode: typeof process.exitCode;++beforeEach(() => {+ stdout = '';+ stderr = '';+ combined = '';+ previousExitCode = process.exitCode;+ restoreTerminal = setStandardErrorTerminalForTest();+ vi.stubEnv('CI', '');+ vi.stubEnv('TERM', 'xterm-256color');+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(+ createStandardInputStub({ isTerminal: false }),+ );+ vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {+ stdout += String(chunk);+ combined += String(chunk);++ return true;+ });+ vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => {+ stderr += String(chunk);+ combined += String(chunk);++ return true;+ });+});++afterEach(() => {+ restoreTerminal();+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+ process.exitCode = previousExitCode;+});++describe('terminal progress', () => {+ it('updates one stderr line even when stdin is not a terminal', () => {+ const output = createOutput({ mode: 'human', command: 'data export' });++ output.progress({ message: 'Exporting companies…', percentage: 25 });+ output.progress({ message: 'Exporting companies…', percentage: 75 });++ expect(stdout).toBe('');+ expect(stderr).toContain('█████░░░░░░░░░░░░░░░ 25%');+ expect(stderr).toContain('\u001b[1G\u001b[2KExporting companies…');+ expect(stderr).toContain('███████████████░░░░░ 75%');+ expect(stderr).not.toContain('\n');+ });++ it.each([+ { terminal: false, ci: '', term: 'xterm' },+ { terminal: true, ci: 'true', term: 'xterm' },+ { terminal: true, ci: '1', term: 'xterm' },+ { terminal: true, ci: '', term: 'dumb' },+ ])(+ 'uses plain lines for $terminal / $ci / $term',+ ({ terminal, ci, term }) => {+ process.stderr.isTTY = terminal;+ vi.stubEnv('CI', ci);+ vi.stubEnv('TERM', term);+ const output = createOutput({ mode: 'human', command: 'data export' });++ output.progress({ message: 'Exporting companies…', percentage: 25 });+ output.progress({ message: 'Exporting companies…', percentage: 75 });++ expect(stderr).toBe(+ 'Exporting companies… 25%\nExporting companies… 75%\n',+ );+ expect(stdout).toBe('');+ },+ );++ it.each(['false', '0'])('allows a bar when CI is %s', (ci) => {+ vi.stubEnv('CI', ci);+ const output = createOutput({ mode: 'human', command: 'data export' });++ output.progress({ message: 'Exporting companies…', percentage: 25 });++ expect(stderr).toContain('█');+ });++ it('shortens the bar to fit the terminal and falls back to lines if too narrow', () => {+ process.stderr.columns = 40;+ const output = createOutput({ mode: 'human', command: 'data export' });++ output.progress({ message: 'Exporting companies…', percentage: 25 });++ expect(stderr.length).toBeLessThan(40);+ expect(stderr).toContain('░');+ output.progress({ message: 'Downloading CSV…' });+ stderr = '';+ process.stderr.columns = 25;+ output.progress({ message: 'Exporting companies…', percentage: 75 });++ expect(stderr).toBe('Exporting companies… 75%\n');+ });++ it.each([+ '界'.repeat(12),+ '\u001b[32m' + '界'.repeat(12) + '\u001b[0m',+ '👨👩👧👦'.repeat(12),+ 'e\u0301'.repeat(24),+ ])('fits a bar to displayed terminal columns for %s', (message) => {+ process.stderr.columns = 40;+ const output = createOutput({ mode: 'human', command: 'data export' });++ output.progress({ message, percentage: 25 });++ expect(stderr).toBe(`${message} ██░░░░░░ 25%`);+ output.progress({ message: 'Downloading CSV…' });+ expect(stderr).toBe(+ `${message} ██░░░░░░ 25%\u001b[1G\u001b[2KDownloading CSV…\n`,+ );+ });++ it('uses a plain line when wide text leaves no room for a bar', () => {+ process.stderr.columns = 35;+ const output = createOutput({ mode: 'human', command: 'data export' });+ const message = '界'.repeat(12);++ output.progress({ message, percentage: 25 });++ expect(stderr).toBe(`${message} 25%\n`);+ });++ it('includes percentages in NDJSON progress and omits them when absent', () => {+ const output = createOutput({ mode: 'ndjson', command: 'data export' });++ output.progress({ message: 'Starting export…', percentage: 0 });+ output.progress({ message: 'Exporting companies…', percentage: 25 });+ output.progress({ message: 'Downloading CSV…' });++ expect(stderr).toBe('');+ expect(+ stdout+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line)),+ ).toEqual([+ {+ schemaVersion: 1,+ command: 'data export',+ type: 'progress',+ sequence: 1,+ data: { message: 'Starting export…', percentage: 0 },+ },+ {+ schemaVersion: 1,+ command: 'data export',+ type: 'progress',+ sequence: 2,+ data: { message: 'Exporting companies…', percentage: 25 },+ },+ {+ schemaVersion: 1,+ command: 'data export',+ type: 'progress',+ sequence: 3,+ data: { message: 'Downloading CSV…' },+ },+ ]);+ });++ it('clears the bar before the next ordinary progress line', () => {+ const output = createOutput({ mode: 'human', command: 'data export' });++ output.progress({ message: 'Exporting companies…', percentage: 100 });+ output.progress({ message: 'Downloading CSV…' });++ expect(stderr).toContain('\u001b[1G\u001b[2KDownloading CSV…\n');+ });++ it('clears the bar before a success line on stdout', () => {+ const output = createOutput({ mode: 'human', command: 'data export' });++ output.progress({ message: 'Exporting companies…', percentage: 100 });+ output.succeed({ data: {}, human: 'Exported companies' });++ expect(combined).toContain('\u001b[1G\u001b[2KExported companies\n');+ expect(stdout).toBe('Exported companies\n');+ });++ it('clears the bar when a warning is queued', () => {+ const output = createOutput({ mode: 'human', command: 'data export' });++ output.progress({ message: 'Exporting companies…', percentage: 25 });+ output.warn({ code: 'WARNING', message: 'A warning' });++ expect(stderr.endsWith('\u001b[1G\u001b[2K')).toBe(true);+ output.succeed({ data: {}, human: 'Done' });+ expect(combined).toContain('Done\n');+ expect(stderr).toContain('A warning');+ });++ it.each([+ new CliError({+ code: 'NETWORK_ERROR',+ message: 'The connection was lost.',+ }),+ createCancelledError(),+ ])('clears the bar before $code', (error) => {+ const output = createOutput({ mode: 'human', command: 'data export' });++ output.progress({ message: 'Exporting companies…', percentage: 25 });+ output.fail(error);++ const cleared = stderr.indexOf('\u001b[1G\u001b[2K');++ expect(cleared).toBeGreaterThan(0);+ expect(stderr.indexOf(error.message)).toBeGreaterThan(cleared);+ expect(process.exitCode).toBe(error.exitCode);+ });++ it('keeps JSON diagnostics plain and emits one result envelope', () => {+ const output = createOutput({ mode: 'json', command: 'data export' });++ output.progress({ message: 'Exporting companies…', percentage: 25 });+ output.succeed({ data: { bytes: 42 }, human: 'Done' });++ expect(stderr).toBe('Exporting companies… 25%\n');+ expect(JSON.parse(stdout)).toMatchObject({ ok: true, data: { bytes: 42 } });+ expect(stdout.trim().split('\n')).toHaveLength(1);+ });++ it('keeps NDJSON progress and results unchanged on a terminal', async () => {+ const output = createOutput({ mode: 'ndjson', command: 'data export' });++ await output.event(+ 'progress',+ { id: 'export-id', progress: 25 },+ new AbortController().signal,+ );+ output.succeed({ data: { bytes: 42 } });++ expect(stderr).toBe('');+ expect(+ stdout+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line)),+ ).toMatchObject([+ {+ type: 'progress',+ sequence: 1,+ data: { id: 'export-id', progress: 25 },+ },+ { type: 'result', sequence: 2, data: { bytes: 42 } },+ ]);+ });+});diff --git a/packages/twenty-cli/src/output/create-output.ts b/packages/twenty-cli/src/output/create-output.tsindex d1d8690cbc0..333440d029f 100644--- a/packages/twenty-cli/src/output/create-output.ts+++ b/packages/twenty-cli/src/output/create-output.ts@@ -1,20 +1,18 @@import { isNonEmptyString } from '@sniptt/guards';import { isDefined } from 'twenty-shared/utils';+import { createProgressOutput } from '@/output/create-progress-output';import { JSON_SCHEMA_VERSION } from '@/output/constants/json-schema-version.constant';import { formatFailureLine, formatWarningLine } from '@/output/style';import { type CliWarning } from '@/output/types/cli-warning.type';import { type OutputMode } from '@/output/types/output-mode.type';import { type Output } from '@/output/types/output.type';+import { writeLine } from '@/output/write-line';import { writeStreamEvent } from '@/output/write-stream-event';import { type PublicTarget } from '@/target/types/public-target.type';-const writeLine = (stream: NodeJS.WriteStream, text: string) => {- stream.write(text.endsWith('\n') ? text : `${text}\n`);-};-const writeJsonLine = (value: unknown) => {- writeLine(process.stdout, JSON.stringify(value));+ writeLine({ stream: process.stdout, text: JSON.stringify(value) });};const indentLines = (text: string) =>@@ -34,6 +32,7 @@ export const createOutput = ({command: string;}): Output => {const warnings: CliWarning[] = [];+ const progressOutput = createProgressOutput({ mode });let eventSequence = 0;const writeEvent = (type: string, data: unknown) => {@@ -49,7 +48,10 @@ export const createOutput = ({const writeHumanWarnings = () => {for (const warning of warnings) {- writeLine(process.stderr, formatWarningLine(warning.message));+ writeLine({+ stream: process.stderr,+ text: formatWarningLine(warning.message),+ });}};@@ -71,16 +73,18 @@ export const createOutput = ({signal,);},- progress: (message) => {+ progress: ({ message, percentage }) => {if (mode === 'ndjson') {- writeEvent('progress', { message });+ writeEvent('progress', { message, percentage });return;}- writeLine(process.stderr, message);+ progressOutput.write({ message, percentage });},warn: (warning) => {+ progressOutput.clear();+if (mode === 'ndjson') {writeEvent('warning', warning);@@ -90,6 +94,8 @@ export const createOutput = ({warnings.push(warning);},succeed: ({ data, human }, target) => {+ progressOutput.clear();+if (mode === 'json') {writeJsonLine({schemaVersion: JSON_SCHEMA_VERSION,@@ -112,12 +118,14 @@ export const createOutput = ({const humanText = human ?? JSON.stringify(data, null, 2);if (isNonEmptyString(humanText)) {- writeLine(process.stdout, humanText);+ writeLine({ stream: process.stdout, text: humanText });}writeHumanWarnings();},fail: (error, target) => {+ progressOutput.clear();+process.exitCode = error.exitCode;const errorPayload = {@@ -146,10 +154,13 @@ export const createOutput = ({return;}- writeLine(process.stderr, formatFailureLine(error.message));+ writeLine({+ stream: process.stderr,+ text: formatFailureLine(error.message),+ });if (isDefined(error.hint)) {- writeLine(process.stderr, indentLines(error.hint));+ writeLine({ stream: process.stderr, text: indentLines(error.hint) });}writeHumanWarnings();diff --git a/packages/twenty-cli/src/output/create-progress-output.ts b/packages/twenty-cli/src/output/create-progress-output.tsnew file mode 100644index 00000000000..b12bc0ac48f--- /dev/null+++ b/packages/twenty-cli/src/output/create-progress-output.ts@@ -0,0 +1,64 @@+import { clearLine, cursorTo } from 'node:readline';+import stringWidth from 'string-width';++import { isDefined } from 'twenty-shared/utils';++import { formatProgressLine } from '@/output/format-progress-line';+import { type OutputMode } from '@/output/types/output-mode.type';+import { type Output } from '@/output/types/output.type';+import { writeLine } from '@/output/write-line';+import { isContinuousIntegration } from '@/utils/is-continuous-integration';++export const createProgressOutput = ({ mode }: { mode: OutputMode }) => {+ let hasActiveBar = false;++ const clear = () => {+ if (!hasActiveBar) {+ return;+ }++ cursorTo(process.stderr, 0);+ clearLine(process.stderr, 0);+ hasActiveBar = false;+ };++ const write: Output['progress'] = ({ message, percentage }) => {+ const progressText = isDefined(percentage) ? `${percentage}%` : '';+ const barWidth = Math.min(+ 20,+ (process.stderr.columns ?? 80) -+ stringWidth(message) -+ progressText.length -+ 5,+ );++ clear();++ if (+ mode !== 'human' ||+ !process.stderr.isTTY ||+ isContinuousIntegration() ||+ process.env.TERM === 'dumb' ||+ !isDefined(percentage) ||+ !Number.isFinite(percentage) ||+ barWidth < 4+ ) {+ writeLine({+ stream: process.stderr,+ text: formatProgressLine({ message, percentage }),+ });++ return;+ }++ const filledWidth = Math.round(+ (Math.min(100, Math.max(0, percentage)) / 100) * barWidth,+ );+ const bar = '█'.repeat(filledWidth) + '░'.repeat(barWidth - filledWidth);++ process.stderr.write(`${message} ${bar} ${progressText}`);+ hasActiveBar = true;+ };++ return { write, clear };+};diff --git a/packages/twenty-cli/src/output/format-progress-line.ts b/packages/twenty-cli/src/output/format-progress-line.tsnew file mode 100644index 00000000000..3bb21930690--- /dev/null+++ b/packages/twenty-cli/src/output/format-progress-line.ts@@ -0,0 +1,9 @@+import { isDefined } from 'twenty-shared/utils';++export const formatProgressLine = ({+ message,+ percentage,+}: {+ message: string;+ percentage?: number;+}) => (isDefined(percentage) ? `${message} ${percentage}%` : message);diff --git a/packages/twenty-cli/src/output/types/output.type.ts b/packages/twenty-cli/src/output/types/output.type.tsindex 533e4824e75..358d172c38b 100644--- a/packages/twenty-cli/src/output/types/output.type.ts+++ b/packages/twenty-cli/src/output/types/output.type.ts@@ -10,7 +10,7 @@ export type Output = {signal: AbortSignal,) => Promise<void>;warn: (warning: CliWarning) => void;- progress: (message: string) => void;+ progress: (progress: { message: string; percentage?: number }) => void;succeed: (result: CommandResult, target?: PublicTarget) => void;fail: (error: CliError, target?: PublicTarget) => void;};diff --git a/packages/twenty-cli/src/output/write-line.ts b/packages/twenty-cli/src/output/write-line.tsnew file mode 100644index 00000000000..a7aedac61fa--- /dev/null+++ b/packages/twenty-cli/src/output/write-line.ts@@ -0,0 +1,9 @@+export const writeLine = ({+ stream,+ text,+}: {+ stream: NodeJS.WriteStream;+ text: string;+}) => {+ stream.write(text.endsWith('\n') ? text : `${text}\n`);+};diff --git a/packages/twenty-cli/src/program/is-interaction-allowed.ts b/packages/twenty-cli/src/program/is-interaction-allowed.tsindex 40801635d61..38f50b1b25e 100644--- a/packages/twenty-cli/src/program/is-interaction-allowed.ts+++ b/packages/twenty-cli/src/program/is-interaction-allowed.ts@@ -1,17 +1,5 @@-import { isNonEmptyString } from '@sniptt/guards';-import { type OutputMode } from '@/output/types/output-mode.type';--const FALSE_VALUES = new Set(['0', 'false']);--const isContinuousIntegration = () => {- const continuousIntegration = process.env.CI;-- return (- isNonEmptyString(continuousIntegration) &&- !FALSE_VALUES.has(continuousIntegration.toLowerCase())- );-};+import { isContinuousIntegration } from '@/utils/is-continuous-integration';export const isInteractionAllowed = ({options,diff --git a/packages/twenty-cli/src/utils/is-continuous-integration.ts b/packages/twenty-cli/src/utils/is-continuous-integration.tsnew file mode 100644index 00000000000..e41d956ff8f--- /dev/null+++ b/packages/twenty-cli/src/utils/is-continuous-integration.ts@@ -0,0 +1,12 @@+import { isNonEmptyString } from '@sniptt/guards';++const FALSE_VALUES = new Set(['0', 'false']);++export const isContinuousIntegration = () => {+ const continuousIntegration = process.env.CI;++ return (+ isNonEmptyString(continuousIntegration) &&+ !FALSE_VALUES.has(continuousIntegration.toLowerCase())+ );+};diff --git a/yarn.lock b/yarn.lockindex 0ce78fb7643..9c334ea600c 100644--- a/yarn.lock+++ b/yarn.lock@@ -51056,6 +51056,7 @@ __metadata:lodash.startcase: "npm:^4.4.0"npm-pick-manifest: "npm:^11.0.1"semver: "npm:7.6.3"+ string-width: "npm:^8.2.0"tinyglobby: "npm:^0.2.15"twenty-client-sdk: "workspace:*"twenty-shared: "workspace:*"