Engineering Practices for Generating Desktop Applications with Large Language Models
Code generation models are evolving from simple function completion to generating fully runnable applications. This article explores the engineering practices necessary to build usable desktop tools using large language models (LLMs). Using a batch video-to-audio extraction tool as an example, it details how to establish verifiable acceptance criteria, write structured prompts, review critical engineering details like asynchronous task scheduling and file handling, and design comprehensive testing strategies to transform AI-generated code into a deliverable software tool.
Engineering Practices for Generating Desktop Applications with Large Language Models
Code generation models are shifting from “completing a function” to “generating a runnable small application.” At this stage, the focus of evaluating results should not remain on generation speed or code volume, but on three more practical questions: Can the code pass runtime validation on the first try? Does the functionality cover all requirements? Are the UI and task scheduling engineering-ready? Many improvements in a model’s coding capability come from post-training optimization rather than fundamental architectural changes. For developers, this means that prompts, requirement decomposition, code review, and acceptance methods will directly impact the final delivery quality.
Let’s use a typical requirement as an example: generating a desktop batch video and audio extraction tool. The tool needs to support importing various video files, extracting audio tracks into common audio formats, providing a file list, target format selection, output directory setting, executing conversion, progress display, status prompts, and an exit function. It also requires that the UI does not freeze during conversion, errors are prompted, and same-name files are not randomly overwritten.
I. Establish Verifiable Acceptance Criteria First
Faced with descriptions like “friendly interface, comprehensive features, smooth operation,” code generation models can often only make reasonable guesses. In engineering practice, these should be converted into verifiable standards first.
- Runnability. The application can start normally with a clear entry point, dependencies can be installed, and there are no unhandled exceptions on the first run.
- Functional Completeness. File import, format selection, output directory, task execution, progress feedback, cancel or exit, and error prompts can all be actually operated.
- Non-functional Quality. Time-consuming media processing tasks must not block the main interface; progress updates and status bars should accurately reflect task status; exceptions should be displayed in tiers; duplicate task starts should be restricted.
- Maintainability. The UI layer, task scheduling layer, media processing layer, and configuration and logging modules should be relatively separate, avoiding stacking all logic in a single event handler function.
- Boundary Condition Handling. Empty file lists, unreadable files, corrupted files, unsupported formats, output directories without write permissions, missing external media processing capabilities, and same-name outputs should all have clear behaviors.
Among these, “not freezing the UI” is the constraint that best tests the quality of the generated solution. Desktop application interfaces usually run in a single event loop. If a time-consuming transcoding or extraction task is executed directly within a button click event, the main thread will be unable to respond for a long time, and the operating system will consider the window unresponsive. The correct approach is to put time-consuming tasks into background worker threads or task queues, leaving the main thread responsible only for UI rendering and event handling.
An acceptable execution flow can be expressed with the following pseudocode:
function startConversion(files, targetFormat, outputDir):issues = validateInputs(files, targetFormat, outputDir)if issues not empty:showErrors(issues)returnif not mediaCapability.ready():showMessage("Missing media processing capabilities. Please install or configure.")returnsetUiRunning(true)worker = createBackgroundWorker(function(cancelToken):tasks = expandFilesAndValidate(files)total = tasks.sizefor index, task in enumerate(tasks):if cancelToken.cancelled:breaktempOutput = buildTemporaryOutputPath(task, outputDir)try:mediaEngine.extractAudio(task.source, tempOutput, targetFormat)finalOutput = deduplicateName(tempOutput, outputDir)atomicMove(tempOutput, finalOutput)reportItemSuccess(task.source, finalOutput)catch error:reportItemError(task.source, friendlyMessage(error))cleanupTemporaryFile(tempOutput)reportProgress(index + 1, total)end)worker.onProgress = progress -> ui.dispatch(updateProgressBar, progress)worker.onError = error -> ui.dispatch(showStatus, error)worker.onFinished = result -> ui.dispatch(showSummary, result)worker.start()
This structure contains several key points: time-consuming code executes in a worker thread; progress and errors are passed back via a thread-safe UI dispatch mechanism; UI updates are always done on the main thread; tasks support cancellation; failed items have cleanup logic; and same-name outputs have a deduplication strategy.
II. Write Vague Requirements into Structured Prompts
When asking the model to generate a complete application at once, the prompt should not just be a feature list. A more effective approach is to organize it by “Goal, Environment, Features, Boundary Conditions, Architecture Constraints, Acceptance Method, and Deliverables.”
Goal:Generate a cross-platform desktop batch audio extraction tool with a clear UI that can run directly.Environment:Use a mainstream scripting language and its standard desktop UI library; do not rely on components that are not publicly available.Features:1. Support importing single files, multiple files, and directories;2. The file list supports viewing, removing, and clearing;3. Allow selecting the target audio format and output directory;4. Support starting conversion, canceling tasks, and exiting the program;5. Display total progress, current file, and status prompts;6. Provide a summary after successful or failed conversion.Boundary Conditions:1. Tasks cannot start with an empty list;2. Unsupported file formats should be skipped with a prompt;3. Directory imports must be recursive but avoid symlink loops;4. Prompt if the output directory is not writable;5. Same-name output files should be automatically numbered and not silently overwritten;6. If external media processing capabilities are missing, prompt before starting and provide handling suggestions;7. Conversion should use temporary files and atomically move them upon success to avoid leaving partial files.Architecture Constraints:UI events must not directly execute time-consuming tasks; use a background task queue; progress updates, exception messages, and completion callbacks must be thread-safe.Acceptance:Provide startup instructions, dependency descriptions, key module explanations, and a self-test checklist.
The closer the prompt is to the acceptance criteria, the easier the generated result is to review. Details like “behavior upon failure” and “how to handle same-name files,” if not clearly specified, may lead the model to adopt different strategies such as silent skipping, direct overwriting, or interrupting the entire task.
III. Engineering Details Worth Reviewing in Generated Code
Complete features are just the first layer. A deliverable small tool also needs to handle a large number of details.
1. File Import and Directory Expansion
When importing directories recursively, it should be clear whether to include subdirectories, ignore hidden files, and how to handle symlinks. A more robust implementation will first maintain a pending collection, normalize paths, and then deduplicate them to prevent the same file from being added repeatedly. For long file lists, UI updates should be batched rather than triggering a full redraw every time a file is added.
2. Format Recognition and Output Validation
Video and audio formats have issues where the container, encoding method, and extension do not completely match. The implementation cannot blindly trust extensions; at the very least, it should check file readability before entering the task and catch parsing failures during the media processing stage. Target formats should match processing capabilities and not just accept arbitrary strings via a UI dropdown box.
3. Output Naming and Anti-Overwriting
Auto-numbering same-name outputs is a typical “small feature, high value” design. In implementation, first check if the target path exists, then generate a candidate path of “original name plus sequence number,” and use atomic creation or atomic move to prevent overwriting existing files under concurrent or race conditions. Temporary files should ideally be located on the same file system to ensure the move operation is atomic.
4. External Capability Pre-check
Audio and video processing usually relies on external codec capabilities or runtime libraries. The application should perform capability detection upon startup or before starting a task, rather than waiting until the first file fails to expose the problem. If the pre-check fails, actionable advice should be provided to the user, such as checking the installation, configuring paths, or using supported input formats. Error prompts should avoid throwing out a long string of underlying logs directly.
5. Task Cancellation and Exit
Cancellation is not simply setting a flag to true. The background task should check the cancellation status before and after processing each file, terminating the current external process if necessary and cleaning up temporary files. When the user closes the window, the system should determine if there are unfinished tasks and ask whether to wait, cancel, or exit. If the UI is destroyed directly while tasks are still running, residual processes or temporary files may be left behind.
6. Error Grading and Summary
It is recommended to distinguish between global errors and single-item errors. An un-writable output directory or missing dependencies are global issues that should prevent the task from starting; a single corrupted file is a single-item issue that can be logged to allow processing of other files to continue. After the task ends, display the number of successes, skips, failures, and the output directory so the user knows where the results are and which files need to be retried.
7. Logging and Privacy
Local media processing tools usually involve user files. Logs should record timestamps, task status, error categories, and path summaries, but should not upload file contents or sensitive paths without explanation. If diagnostic information is needed, allow the user to explicitly export it and warn that it may contain local paths.
IV. Testing and Acceptance Cannot Just Look at “Can It Start”
Passing a syntax check is only the minimum requirement for generated code. It is recommended to design acceptance tests across at least the following dimensions:
- Functional Testing: Single file import, batch import, recursive directory import, format switching, output directory setting, start, cancel, exit, summary display.
- Exception Testing: Empty files, corrupted files, unsupported formats, read-only output directory, insufficient disk space, missing external processing capabilities, same-name files, file names with spaces and non-ASCII characters.
- UI Testing: Window resizing, long list scrolling, dragging the window during long tasks, status bar updates, whether the progress bar is continuously responsive.
- Resource Testing: Large numbers of small files, small numbers of large files, consecutive tasks, repeated tasks, whether temporary files are cleaned up after cancellation.
- Maintainability Check: Are module boundaries clear, are exceptions caught, are there default values for configurations, are there comments on critical paths, and are dependencies documented?
A practical minimal acceptance checklist can include:
- Can it start according to the documentation and complete a real conversion?
- Is the UI movable and is the cancel button clickable during conversion?
- Are there clear prompts for empty lists and unsupported formats?
- Do same-name outputs generate new files instead of overwriting?
- Does it prevent the task and prompt when the output directory is not writable?
- Can other files continue to be processed after a single file failure?
- Are there residual background tasks after exiting?
- Are temporary files cleaned up after success or failure?
V. Revisiting the Default Output Directory
“Whether the default output directory after conversion is the current program directory” seems like a minor issue, but it actually involves path semantics and deployment security. Generated code often uses the current working directory as the default value, but for a packaged desktop application, the current working directory might differ from the executable file’s directory; moreover, the program installation directory is usually not writable. Therefore, the output directory cannot rely on an implicit current directory.
A more robust rule is: provide an explicit default directory on first launch, such as a fixed subdirectory under the user’s documents directory; persist the user’s choice after they select an output directory; if the configuration becomes invalid or the directory is not writable, prompt for selection again. The output path should be saved as a normalized absolute path, with moderate truncation applied when displayed in the UI. The directory must be verified to exist and be writable before the task starts, rather than discovering write failures after the conversion is complete.
VI. Conclusion
The value of using large language models to generate desktop tools lies in quickly translating requirements into an initially structured implementation, not in replacing engineering validation. For tasks like batch media processing, what truly determines usability is often the asynchronous task model, input validation, output atomicity, dependency pre-checking, error recovery, and path strategies. Writing these engineering constraints into the prompt and then verifying them item by item through review and testing is the only way to transform “generated a piece of code” into “delivered a usable tool.”
