11/** Trusted-window Chromium downloads and clipboard fallback reads. */
22import { app , dialog , ipcMain , session } from 'electron'
3- import type { BrowserWindow , IpcMainInvokeEvent } from 'electron'
4- import { closeSync , createWriteStream , openSync , renameSync , rmSync } from 'node:fs'
5- import { dirname , extname , join } from 'node:path'
3+ import type { BrowserWindow , IpcMainInvokeEvent , SaveDialogOptions , WebContents } from 'electron'
4+ import { createWriteStream , openSync , renameSync , rmSync } from 'node:fs'
5+ import { dirname , join } from 'node:path'
66import { Readable } from 'node:stream'
77import { pipeline } from 'node:stream/promises'
88import { resolveDragFileName } from '@deepseek-ai/dsh-util-file-drag'
@@ -11,37 +11,25 @@ import type { FileSaveResult } from '@deepseek-ai/dsh-client-ui-file-actions/typ
1111import { DESKTOP_IPC } from './ipc.ts'
1212import { resolveDurationMs } from './duration-env.ts'
1313
14- /** Pick a new name without overwriting downloads already on disk. */
15- function reserveDownload ( name : string ) : { path : string ; fd : number } {
16- const destination = join ( app . getPath ( 'downloads' ) , name )
17- const extension = extname ( destination )
18- const stem = destination . slice ( 0 , destination . length - extension . length )
19- for ( let index = 0 ; ; index ++ ) {
20- const path = index === 0 ? destination : `${ stem } (${ index } )${ extension } `
21- try { return { path, fd : openSync ( path , 'wx' ) } }
22- catch ( error ) {
23- if ( typeof error === 'object' && error !== null && 'code' in error && error . code === 'EEXIST' ) continue
24- throw error
25- }
26- }
14+ function saveDialogOptions ( name : string ) : SaveDialogOptions {
15+ return { defaultPath : join ( app . getPath ( 'downloads' ) , name ) , properties : [ 'showOverwriteConfirmation' , 'createDirectory' ] }
2716}
2817
29- /** @param value - untrusted IPC input. @returns captured URL and destination policy . */
30- function saveRequest ( value : unknown ) : { url : URL ; name ?: string ; mediaType ?: string ; mode : 'download' | 'saveAs' } {
18+ /** Accept either mode for compatibility with installed plugins and older clients . */
19+ function saveRequest ( value : unknown ) : { url : URL ; name ?: string ; mediaType ?: string } {
3120 if ( typeof value !== 'object' || value === null
3221 || ! ( 'url' in value ) || typeof value . url !== 'string'
3322 || ( 'name' in value && typeof value . name !== 'string' )
3423 || ( 'mediaType' in value && typeof value . mediaType !== 'string' )
3524 || ! ( 'mode' in value ) || ( value . mode !== 'download' && value . mode !== 'saveAs' ) ) throw new Error ( 'Invalid file save request' )
3625 const url = new URL ( value . url )
3726 const packageDownload = / ^ \/ i p o l l o w o r k - s u i t e \/ e n t e r p r i s e \/ o r g a n i z a t i o n s \/ [ \w - ] { 1 , 200 } \/ p a c k a g e s \/ [ \w - ] { 1 , 200 } \/ f i l e s \/ [ \w - ] { 1 , 200 } \/ d o w n l o a d $ / u. test ( url . pathname )
38- const projectDownload = value . mode === 'download' &&
39- / ^ \/ i p o l l o w o r k - s u i t e \/ e n t e r p r i s e \/ (?: d o w n l o a d \/ [ \w - ] { 1 , 200 } | p r o j e c t s \/ [ \w - ] { 1 , 200 } \/ m e m o r y - v e r s i o n s \/ \d + ) $ / u. test ( url . pathname )
27+ const projectDownload = / ^ \/ i p o l l o w o r k - s u i t e \/ e n t e r p r i s e \/ (?: d o w n l o a d \/ [ \w - ] { 1 , 200 } | p r o j e c t s \/ [ \w - ] { 1 , 200 } \/ m e m o r y - v e r s i o n s \/ \d + ) $ / u. test ( url . pathname )
4028 const appDownload = url . protocol === 'dsh-app:' && url . host === 'app' && ! url . search &&
4129 'name' in value && typeof value . name === 'string' && ! ! value . name . trim ( ) && ( packageDownload || projectDownload )
4230 if ( ( ! appDownload && ! [ 'https:' , 'http:' , 'blob:' , 'data:' ] . includes ( url . protocol ) ) || url . username || url . password )
4331 throw new Error ( 'Unsupported file source' )
44- return { url, mode : value . mode ,
32+ return { url,
4533 ...'name' in value ? { name : value . name as string } : { } ,
4634 ...'mediaType' in value ? { mediaType : value . mediaType as string } : { } ,
4735 }
@@ -52,10 +40,12 @@ function saveRequest(value: unknown): { url: URL; name?: string; mediaType?: str
5240 * @param assertOwner - rejects shell pages, subframes, and unowned windows.
5341 * @param hostUrl - current application Host excluded from image reads.
5442 * @param projectRequest - authenticated fetch for allowlisted project downloads.
43+ * @param isApplicationContents - identifies browser downloads from the application window, including plugin frames.
5544 */
5645export function installFileActions (
5746 assertOwner : ( event : IpcMainInvokeEvent ) => BrowserWindow , hostUrl : ( ) => string | undefined = ( ) => undefined ,
5847 projectRequest ?: ( request : Request ) => Promise < Response > ,
48+ isApplicationContents : ( contents : WebContents ) => boolean = ( ) => false ,
5949) : void {
6050 const timeoutMs = resolveDurationMs ( process . env , 'DSH_DESKTOP_IMAGE_READ_TIMEOUT_MS' , 30_000 )
6151 const maxBytes = Number ( process . env . DSH_DESKTOP_IMAGE_READ_MAX_BYTES ?? 64 * 1024 * 1024 )
@@ -70,30 +60,27 @@ export function installFileActions(
7060 } > ( )
7161 session . defaultSession . on ( 'will-download' , ( _event , item , contents ) => {
7262 const url = item . getURLChain ( ) [ 0 ]
73- if ( url === undefined || ! new URL ( url ) . hash . startsWith ( '#dsh-download=' ) ) return
63+ if ( url === undefined || ! new URL ( url ) . hash . startsWith ( '#dsh-download=' ) ) {
64+ if ( contents && isApplicationContents ( contents ) ) {
65+ const name = resolveDragFileName ( { name : item . getFilename ( ) , mediaType : '' } )
66+ item . setSaveDialogOptions ( saveDialogOptions ( name ) )
67+ }
68+ return
69+ }
7470 const entry = pending . get ( url )
7571 if ( entry === undefined || entry . owner . webContents !== contents ) { item . cancel ( ) ; return }
7672 entry . started ( )
7773 entry . item = item
78- let reserved : string | undefined
7974 try {
8075 assertOwner ( entry . event )
8176 const name = resolveDragFileName ( {
8277 name : entry . request . name ?? item . getFilename ( ) ,
8378 mediaType : item . getMimeType ( ) || entry . request . mediaType || '' ,
8479 } )
85- if ( entry . request . mode === 'saveAs' ) {
86- item . setSaveDialogOptions ( { defaultPath : join ( app . getPath ( 'downloads' ) , name ) , properties : [ 'showOverwriteConfirmation' , 'createDirectory' ] } )
87- } else {
88- const file = reserveDownload ( name )
89- reserved = file . path
90- closeSync ( file . fd )
91- item . setSavePath ( file . path )
92- }
80+ item . setSaveDialogOptions ( saveDialogOptions ( name ) )
9381 item . once ( 'done' , ( _event , state ) => {
9482 try {
9583 if ( state !== 'completed' ) {
96- if ( reserved !== undefined ) rmSync ( reserved , { force : true } )
9784 entry . finish ( state === 'cancelled' ? { status : 'cancelled' } : new Error ( 'File download interrupted' ) )
9885 return
9986 }
@@ -104,11 +91,6 @@ export function installFileActions(
10491 } )
10592 } catch ( error ) {
10693 item . cancel ( )
107- try { if ( reserved !== undefined ) rmSync ( reserved , { force : true } ) }
108- catch ( cleanupError ) {
109- entry . finish ( new AggregateError ( [ error , cleanupError ] , 'File download failed and its partial file could not be removed' ) )
110- return
111- }
11294 entry . finish ( error instanceof Error ? error : new Error ( 'File download unavailable' ) )
11395 }
11496 } )
@@ -125,19 +107,13 @@ export function installFileActions(
125107 }
126108 owner . once ( 'closed' , abort )
127109 contents . on ( 'did-start-navigation' , navigate )
128- let reserved : string | undefined
110+ let temporary : string | undefined
129111 try {
130112 const name = resolveDragFileName ( { name : request . name , mediaType : '' } )
131- let destination : string | undefined
132- if ( request . mode === 'saveAs' ) {
133- const choice = await dialog . showSaveDialog ( owner , {
134- defaultPath : join ( app . getPath ( 'downloads' ) , name ) ,
135- properties : [ 'showOverwriteConfirmation' , 'createDirectory' ] ,
136- } )
137- if ( choice . canceled || ! choice . filePath || lifetime . signal . aborted ) return { status : 'cancelled' }
138- assertOwner ( event )
139- destination = choice . filePath
140- }
113+ const choice = await dialog . showSaveDialog ( owner , saveDialogOptions ( name ) )
114+ if ( choice . canceled || ! choice . filePath || lifetime . signal . aborted ) return { status : 'cancelled' }
115+ assertOwner ( event )
116+ const destination = choice . filePath
141117 const signal = AbortSignal . any ( [ lifetime . signal , AbortSignal . timeout ( downloadTimeoutMs ) ] )
142118 request . url . hash = ''
143119 let response = await projectRequest ( new Request ( request . url , { signal } ) )
@@ -153,16 +129,16 @@ export function installFileActions(
153129 throw new Error ( 'Project download unavailable' )
154130 }
155131 // Stage beside the destination so an interrupted overwrite leaves the previous file intact.
156- const temporary = destination ? join ( dirname ( destination ) , '.ipollowork-download-' + randomUUID ( ) + '.tmp' ) : undefined
157- const file = temporary ? { path : temporary , fd : openSync ( temporary , 'wx' ) } : reserveDownload ( name )
158- reserved = file . path
159- await pipeline ( Readable . fromWeb ( response . body as import ( 'node:stream/web' ) . ReadableStream ) , createWriteStream ( file . path , { fd : file . fd } ) , { signal } )
132+ const stagingPath = join ( dirname ( destination ) , '.ipollowork-download-' + randomUUID ( ) + '.tmp' )
133+ const fd = openSync ( stagingPath , 'wx' )
134+ temporary = stagingPath
135+ await pipeline ( Readable . fromWeb ( response . body as import ( 'node:stream/web' ) . ReadableStream ) , createWriteStream ( stagingPath , { fd } ) , { signal } )
160136 assertOwner ( event )
161137 signal . throwIfAborted ( )
162- if ( destination ) renameSync ( file . path , destination )
163- return { status : 'saved' , path : destination ?? file . path }
138+ renameSync ( stagingPath , destination )
139+ return { status : 'saved' , path : destination }
164140 } catch ( error ) {
165- if ( reserved !== undefined ) rmSync ( reserved , { force : true } )
141+ if ( temporary !== undefined ) rmSync ( temporary , { force : true } )
166142 if ( lifetime . signal . aborted ) return { status : 'cancelled' }
167143 throw error
168144 } finally {
0 commit comments